Question:
/*
Internal.  Makes modal behavior by immediately returning focus to the dialog when user leaves the dialog, and by
styling the background to look faded.

function(parent) {
			var self = this;
			// We listen to focus lost and remember the last one with focus.  This is great for clicks away from dialog.
			this.$frame.addEventListener("blur", function(e) { //$NON-NLS-0$
				self.$lastFocusedElement = e.target;
			}, true);
			this._modalListener = function(e) { //$NON-NLS-0$
				var preventFocus =	!lib.contains(self.$frame, e.target);
				if (preventFocus) {
					for (var i = 0; i<self.$$modalExclusions.length; i++) {
						if (lib.contains(self.$$modalExclusions[i], e.target)) {
							preventFocus = false;
							break;
						}
					}
				}
				if (preventFocus) {
					window.setTimeout(function() {
						(self.$lastFocusedElement || self.$parent).focus();
					}, 0);
					lib.stop(e);
				}
			};
			this.$frameParent.addEventListener("focus", this._modalListener, true);  //$NON-NLS-0$
			this.$frameParent.addEventListener("click", this._modalListener, true);  //$NON-NLS-0$
			var children = this.$frameParent.childNodes;
			var exclude = false;
			this._addedBackdrop = [];
			for (var i=0; i<children.length; i++) {
				for (var j=0; j<this.$$modalExclusions.length; j++) {
					if (lib.contains(this.$$modalExclusions[j], children[i])) {
						exclude = true;
						break;
					}
				}
				if (!exclude && children[i] !== self.$frame && children[i].classList && !children[i].classList.contains("tooltipContainer")) { //$NON-NLS-0$
					var child = children[i];
					if (!child.classList.contains("modalBackdrop")) {  //$NON-NLS-0$
						child.classList.add("modalBackdrop"); //$NON-NLS-0$
						this._addedBackdrop.push(child);
					}
				}
			}

			// When tabbing out of the dialog, using the above technique (restore to last focus) will put the focus on the last element, but
			// we want it on the first element, so let's prevent the user from tabbing out of the dialog.
			lib.trapTabs(this.$frame);
			this.$frame.setAttribute("aria-modal", "true");
		}

def color(
            self, text=None, fore=None, back=None, style=None,
            no_closing=False):

        has_args = (
            (fore is not None) or
            (back is not None) or
            (style is not None)
        )
        if hasattr(text, '__colr__') and not has_args:
            # Use custom __colr__ method in the absence of arguments.
            return str(self._call_dunder_colr(text))

        # Stringify everything before operating on it.
        text = str(text) if text is not None else ''
        if _disabled:
            return text

        # Considered to have unclosed codes if embedded codes exist and
        # the last code was not a color code.
        embedded_codes = get_codes(text)
        has_end_code = embedded_codes and embedded_codes[-1] == closing_code
        # Add closing code if not already added, there is text, and
        # some kind of color/style was used (whether from args, or
        # color codes were included in the text already).
        # If the last code embedded in the text was a closing code,
        # then it is not added.
        # This can be overriden with `no_closing`.
        needs_closing = (
            text and
            (not no_closing) and
            (not has_end_code) and
            (has_args or embedded_codes)
        )
        if needs_closing:
            end = closing_code
        else:
            end = ''
        return ''.join((
            self.color_code(fore=fore, back=back, style=style),
            text,
            end,
        ))

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


Question:
Creates a private key from the file given, either in RSA private key
(.pem) or pkcs8 (.der) format. Other formats will cause an exception to
be thrown.

public static PrivateKey loadPrivateKey(File privateKeyFile) throws InvalidKeySpecException, IOException {
        if ( StringUtils.lowerCase(privateKeyFile.getAbsolutePath()).endsWith(".pem") ) {
            InputStream is = new FileInputStream(privateKeyFile);
            try {
                return PEM.readPrivateKey(is);
            } finally {
                try {is.close();} catch(IOException ignore) {}
            }
        } else if ( StringUtils.lowerCase(privateKeyFile.getAbsolutePath()).endsWith(".der") ) {
            InputStream is = new FileInputStream(privateKeyFile);
            try {
                return RSA.privateKeyFromPKCS8(IOUtils.toByteArray(is));
            } finally {
                try {is.close();} catch(IOException ignore) {}
            }
        } else {
            throw new AmazonClientException("Unsupported file type for private key");
        }
    }

def _transform_call_params(self, params):

        rez = {}
        for k, v in params.items():
            if isinstance(v, dict):
                v = self._transform_call_params(v)
                k_final = k
            else:
                # k = modifier1@modifier2@...modifierN@k_final
                k_split = k.split("@")
                k_final = k_split[-1]
                k_mods  = k_split[:-1]
                for m in k_mods:
                    if (m == "file"):
                        with open(v, 'rb') as f:
                            v = f.read()
                    elif (m == "b64encode"):
                        v = base64.b64encode(v)
                    elif (m == "b64decode"):
                        v = base64.b64decode(v)
                    else:
                        raise Exception("Unknown modifier ('%s') in call parameters. Possible modifiers: file, b64encode, b64decode"%m)
            rez[k_final] = v
        return rez

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


Question:
createSubject Creating the subject using the given context.

@param mixed $context The context used to create the subject.

@access public
@return void

public function createSubject($context)
    {
        global $logger;
        //$copyContext = $this->copy($context);
        //$copyContext = $this->_ensureSecurityMgr($copyContext);
        //$copyContext = $this->_resolveSession($copyContext);
        //$copyContext = $this->_resolvePrincipals($copyContext);
        $subject     = $this->doCreateSubject($context);
        $this->_save($subject);

        return $subject;

    }

public static function hydrate(stdClass $team)
    {
        $hydrated = new TeamEntity();

        if (isset($team->id)) {
            $hydrated->setId($team->id);
        }

        if (isset($team->name)) {
            $hydrated->setName($team->name);
        }

        if (isset($team->organization)) {
            $hydrated->setOrganization(OrgHydrator::hydrate($team->organization));
        }

        if (isset($team->users) && is_array($team->users)) {
            $hydrated->setUsers(UserHydrator::hydrateCollection($team->users));
        }

        if (isset($team->created_by)) {
            $hydrated->setCreatedBy(UserHydrator::hydrate($team->created_by));
        }

        if (isset($team->created_at)) {
            $hydrated->setCreatedAt(new DateTime($team->created_at));
        }

        return $hydrated;
    }

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


Question:
Get layer output type.

@param inputType Array of InputTypes
@return output type as InputType
@throws InvalidKerasConfigurationException Invalid Keras config

@Override
    public InputType getOutputType(InputType... inputType) throws InvalidKerasConfigurationException {
        if (inputType.length > 1)
            throw new InvalidKerasConfigurationException(
                    "Keras Alpha Dropout layer accepts only one input (received " + inputType.length + ")");
        return this.getAlphaDropoutLayer().getOutputType(-1, inputType[0]);
    }

private function BuildRequest(RestTool $restTool)
    {
        $this->_curlHandle = curl_init($restTool->GetRequestUrl());
        if ($this->_curlHandle === false) {
            $this->logger->error('Cannot initialize cURL session');
            throw new Exception('Cannot initialize cURL session');
        }

        curl_setopt($this->_curlHandle, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->_curlHandle, CURLOPT_HEADER, true);

        curl_setopt($this->_curlHandle, CURLOPT_CONNECTTIMEOUT, $this->GetCurlConnectionTimeout());
        curl_setopt($this->_curlHandle, CURLOPT_TIMEOUT, $this->GetCurlResponseTimeout());

        curl_setopt($this->_curlHandle, CURLOPT_RETURNTRANSFER, true);

        if ($this->_root->Config->CertificatesFilePath == '') {
            curl_setopt($this->_curlHandle, CURLOPT_SSL_VERIFYPEER, false);
        } else {
            curl_setopt($this->_curlHandle, CURLOPT_SSL_VERIFYPEER, true);
            curl_setopt($this->_curlHandle, CURLOPT_CAINFO, $this->_root->Config->CertificatesFilePath);
        }

        switch ($restTool->GetRequestType()) {
            case RequestType::POST:
                curl_setopt($this->_curlHandle, CURLOPT_POST, true);
                break;
            case RequestType::PUT:
                curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, 'PUT');
                break;
            case RequestType::DELETE:
                curl_setopt($this->_curlHandle, CURLOPT_CUSTOMREQUEST, "DELETE");
                break;
        }

        curl_setopt($this->_curlHandle, CURLOPT_HTTPHEADER, $restTool->GetRequestHeaders());

        if (!is_null($this->_root->Config->HostProxy)) {
            curl_setopt($this->_curlHandle, CURLOPT_PROXY, $this->_root->Config->HostProxy);
        }

        if (!is_null($this->_root->Config->UserPasswordProxy)) {
            curl_setopt($this->_curlHandle, CURLOPT_PROXYUSERPWD, $this->_root->Config->UserPasswordProxy);
        }

        if ($restTool->GetRequestData()) {
            curl_setopt($this->_curlHandle, CURLOPT_POSTFIELDS, $restTool->GetRequestData());
        }

        /**
         * Hotfix for Travis-CI integration issue.
         * CURLOPT_SSLVERSION is not set correctly, causing SSL requests issue
         */
        if (getenv('TRAVIS')) {
            if (!defined('CURL_SSLVERSION_TLSv1_0')) {
                define('CURL_SSLVERSION_TLSv1_0', 4);
            }

            $options['curl'][CURLOPT_SSLVERSION] = CURL_SSLVERSION_TLSv1_0;
            curl_setopt($this->_curlHandle, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_0);
        }
    }

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


Question:
The instance method sets a new property value.

@param _name name of the property
@param _value value of the property
@throws CacheReloadException on error

@Override
    protected void setProperty(final String _name,
                               final String _value)
        throws CacheReloadException
    {
        if ("ReadOnly".equals(_name)) {
            this.readOnly = "true".equalsIgnoreCase("true");
        }
    }

private void updateRefEntity(EntityType entityType, Attribute attr, Attribute updatedAttr) {
    if (isSingleReferenceType(attr) && isSingleReferenceType(updatedAttr)) {
      dropForeignKey(entityType, attr);

      if (attr.getRefEntity().getIdAttribute().getDataType()
          != updatedAttr.getRefEntity().getIdAttribute().getDataType()) {
        updateColumnDataType(entityType, updatedAttr);
      }

      createForeignKey(entityType, updatedAttr);
    } else if (isMultipleReferenceType(attr) && isMultipleReferenceType(updatedAttr)) {
      throw new MolgenisDataException(
          format(
              "Updating entity [%s] attribute [%s] referenced entity from [%s] to [%s] not allowed for type [%s]",
              entityType.getId(),
              attr.getName(),
              attr.getRefEntity().getId(),
              updatedAttr.getRefEntity().getId(),
              updatedAttr.getDataType().toString()));
    }
  }

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


Question: Marshall the given parameter object.

public void marshall(ApplicationCodeConfigurationDescription applicationCodeConfigurationDescription, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(applicationCodeConfigurationDescription.getCodeContentType(), CODECONTENTTYPE_BINDING);
            protocolMarshaller.marshall(applicationCodeConfigurationDescription.getCodeContentDescription(), CODECONTENTDESCRIPTION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question: Split an S3-prefixed URL into bucket and path.

def bucket_and_path(self, url):
        """"""
        url = compat.as_str_any(url)
        if url.startswith("s3://"):
            url = url[len("s3://"):]
        idx = url.index("/")
        bucket = url[:idx]
        path = url[(idx + 1):]
        return bucket, path

def iter_doc_filepaths(self, **kwargs):

        for shard in self._shards:
            for doc_id, blob in shard.iter_doc_filepaths(**kwargs):
                yield doc_id, blob

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


Question: Extract options from argv

function optionsFrom(argv) {
    var date     = argv.date,
        dates    = utils.parseDate(date),
        options  = { time: argv.hours,
                     dates: dates,
                     billable: argv.billable || argv.b,
                     description: argv.description };
    return options;
}

public function tryGetOptionsForValues(array $values): array
    {
        if ($this->specificFieldOptionLoader) {
            return array_filter(array_map($this->specificFieldOptionLoader, $values));
        } else {
            return (new ArrayFieldOptions(call_user_func($this->fieldOptionsLoader)))->tryGetOptionsForValues($value);
        }
    }

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


Question:
Fills in missing fields in attributes.

@param attrs the attributes to fill missing fields in.

function _fillMissingFields(attrs) {
  var attr;
  for(var i = 0; i < attrs.length; ++i) {
    attr = attrs[i];

    // populate missing name
    if(typeof(attr.name) === 'undefined') {
      if(attr.type && attr.type in pki.oids) {
        attr.name = pki.oids[attr.type];
      } else if(attr.shortName && attr.shortName in _shortNames) {
        attr.name = pki.oids[_shortNames[attr.shortName]];
      }
    }

    // populate missing type (OID)
    if(typeof(attr.type) === 'undefined') {
      if(attr.name && attr.name in pki.oids) {
        attr.type = pki.oids[attr.name];
      } else {
        var error = new Error('Attribute type not specified.');
        error.attribute = attr;
        throw error;
      }
    }

    // populate missing shortname
    if(typeof(attr.shortName) === 'undefined') {
      if(attr.name && attr.name in _shortNames) {
        attr.shortName = _shortNames[attr.name];
      }
    }

    if(typeof(attr.value) === 'undefined') {
      var error = new Error('Attribute value not specified.');
      error.attribute = attr;
      throw error;
    }
  }
}

private static function classRebuild($parts)
    {
        $parts['attribs']['class'] = \array_unique($parts['attribs']['class']);
        $parts['attribs']['class'] = \array_filter($parts['attribs']['class'], 'strlen');
        \sort($parts['attribs']['class']);
        if (!$parts['classIsArray']) {
            $parts['attribs']['class'] = \implode(' ', $parts['attribs']['class']);
        }
        if ($parts['aosIs'] == 'tag') {
            return self::buildTag($parts['tagname'], $parts['attribs'], $parts['innerhtml']);
        } elseif ($parts['aosIs'] == 'attribs') {
            return $parts['attribsIsArray']
                ? $parts['attribs']
                : self::buildAttribString($parts['attribs']);
        } elseif ($parts['aosIs'] == 'class') {
            return $parts['attribs']['class'];
        }
    }

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


Question:
// getDeviceSize calls lsblk in a subprocess to retrieve the size in bytes of
// a given device.

func getDeviceSize(dev string) (uint64, error) {
	cmd := exec.Command("lsblk", "-dbno", "SIZE", dev)
	out, err := cmd.Output()
	if err != nil {
		return 0, err
	}
	var size uint64
	if size, err = strconv.ParseUint(strings.TrimSpace(string(out)), 10, 64); err != nil {
		return 0, err
	}
	return size, nil
}

def sg_gpus():

    """
    global _gpus

    if _gpus is None:
        local_device_protos = device_lib.list_local_devices()
        _gpus = len([x.name for x in local_device_protos if x.device_type == 'GPU'])

    return max(_gpus, 1)

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


Question:
// ListenTLS sets up TLS listener for the http handler, starts listening
// on a TCP socket and returns the socket which is ready to be used
// for http.Serve

func ListenTLS(address string, certFile, keyFile string, cipherSuites []uint16) (net.Listener, error) {
	tlsConfig, err := CreateTLSConfiguration(certFile, keyFile, cipherSuites)
	if err != nil {
		return nil, trace.Wrap(err)
	}
	return tls.Listen("tcp", address, tlsConfig)
}

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:
@param string      $class
@param null|string $alias
@param bool        $checkClassExists Use FALSE when you want to use a namespace instead of a class

@return $this
@throws Exception\ClassUse  When the given class does not exists

public function addUse($class, $alias = null, $checkClassExists = true)
    {
        if (
            $checkClassExists === true &&
            $this->classFile->isClassDefined("\\{$class}") === false &&
            $this->classFile->isInterfaceDefined("\\{$class}") === false &&
            $this->classFile->isTraitDefined("\\{$class}") === false
        ) {
            throw Exception\ClassUse::classUseNotFound($class);
        }

        $use = new ClassUse($class, $alias);

        $this->append($use);

        return $this;
    }

public function getSelector()
	{
		$direct_settings = array(
			'className', 'css', 'id', 'linkText', 'name', 'partialLinkText', 'tagName', 'xpath', 'label',
		);

		foreach ( $direct_settings as $direct_setting ) {
			if ( $this->$direct_setting ) {
				return array($direct_setting => $this->$direct_setting);
			}
		}

		if ( $this->how && $this->using ) {
			if ( !in_array($this->how, $direct_settings) ) {
				throw new AnnotationException(
					"FindBy annotation expects 'how' to be one of \\QATools\\QATools\\PageObject\\How class constants",
					AnnotationException::TYPE_INCORRECT_USAGE
				);
			}

			return array($this->how => $this->using);
		}

		throw new AnnotationException(
			sprintf(
				"FindBy annotation requires one of '%s' or both 'how' and 'using' parameters specified",
				implode("', '", $direct_settings)
			),
			AnnotationException::TYPE_INCORRECT_USAGE
		);
	}

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


Question: Marshall the given parameter object.

public void marshall(GetCampaignActivitiesRequest getCampaignActivitiesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getCampaignActivitiesRequest.getApplicationId(), APPLICATIONID_BINDING);
            protocolMarshaller.marshall(getCampaignActivitiesRequest.getCampaignId(), CAMPAIGNID_BINDING);
            protocolMarshaller.marshall(getCampaignActivitiesRequest.getPageSize(), PAGESIZE_BINDING);
            protocolMarshaller.marshall(getCampaignActivitiesRequest.getToken(), TOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question: // SetStatus sets the Status field's value.

func (s *RouteData) SetStatus(v *RouteStatus) *RouteData {
	s.Status = v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
Remove all listeners for current event.

Event::removeAllListeners('event_name');

@access public
@param  string  $event Event name
@return void

public static function removeAllListeners(string $event) : void
    {
        if (Event::hasListeners($event)) {
            unset(Event::$listeners[$event]);
        }
    }

public function del($fd, $flag)
    {
        switch ($flag) {
            case static::EV_READ:
            case static::EV_WRITE:
                $fd_key    = (int)$fd;
                if(isset($this->fdEvents[$fd_key][$flag])){
                    $this->fdEvents[$fd_key][$flag]->del();
                    $this->fdEvents[$fd_key][$flag]->free();
                    unset($this->fdEvents[$fd_key][$flag]);
                }
            case static::EV_SIGNAL:
                if(isset($this->signalEvents[$fd])) {
                    $this->signalEvents[$fd]->del();
                    $this->signalEvents[$fd]->free();
                    unset($this->signalEvents[$fd]);
                }
                break;
            case static::EV_INTERVAL:
            case static::EV_TIMEOUT:
                if(isset($this->timerEvents[$fd])) {
                    static::unsetId($fd);
                    $this->timerEvents[$fd]->del();
                    $this->timerEvents[$fd]->free();
                    unset($this->timerEvents[$fd]);
                }

                break;

        }
    }

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


Question: // StopContainer stops a container. Timeout is given in seconds.

func (r *Runtime) StopContainer(ctx context.Context, c *Container, timeout int64) error {
	impl, err := r.RuntimeImpl(c)
	if err != nil {
		return err
	}

	return impl.StopContainer(ctx, c, timeout)
}

func (c *Client) ExpireAt(key string, unixTime uint64) (bool, error) {
	var ret bool
	err := c.command(
		&ret,
		[]byte("EXPIREAT"),
		[]byte(key),
		to.Bytes(unixTime),
	)
	return ret, err
}

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


Question:
Open a new content stream.

@param item the content item
@return the content stream

InputStream openContentStream(final ContentItem item) throws IOException {
        final File file = getFile(item);
        if (file == null) {
            throw new IllegalStateException();
        }
        return new FileInputStream(file);
    }

final public function startGetReviews($limit = null, $offset = null, array $uids = array(), $responseType = 'xml')
    {
        switch ($responseType) {
            default:
            case 'xml':
                $this->buffer->setFile($this->config->getReviewsXmlPath());
                break;

            case 'json':
                $this->buffer->setFile($this->config->getReviewsJsonPath());
                break;
        }

        $this->createReviews($limit, $offset, $uids);
        $this->buffer->finish();
    }

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


Question:
Use this API to fetch filtered set of jazz_license resources.
filter string should be in JSON format.eg: "vm_state:DOWN,name:[a-z]+"

public static jazz_license[] get_filtered(nitro_service service, String filter) throws Exception
	{
		jazz_license obj = new jazz_license();
		options option = new options();
		option.set_filter(filter);
		jazz_license[] response = (jazz_license[]) obj.getfiltered(service, option);
		return response;
	}

def reboot(id, recovery=false)
      response = request(:post, "/virtual_machines/#{id}/reboot.json", { query: recovery ? { mode: :recovery } : nil })
      response['virtual_machine']
    end

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


Question: // Printf formats and logs message at level="info".

func (l *Logger) Printf(format string, v ...interface{}) {
	l.Emit(0, fmt.Sprintf(format, v...), nil)
}

func (rl *RevelLogger) Errorf(msg string, param ...interface{}) {
	rl.Error(fmt.Sprintf(msg, param...))
}

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


Question:
Remove the specified resource from storage.

@param \TypiCMS\Modules\Currencies\Shells\Models\Currency $currency

@return \Illuminate\Http\JsonResponse

public function destroy(Currency $currency)
    {
        $deleted = $this->repository->delete($currency);

        return response()->json([
            'error' => !$deleted,
        ]);
    }

public function dumpEntry(): string
    {
        $output = $this->dumpEntryComments();

        $key = PoTokens::CONTEXT;
        if (!($this->entry[$key] === null)) {
            $output .= $key . $this->formatQuotedString($this->entry[$key]);
        }
        $key = PoTokens::MESSAGE;
        if (!($this->entry[$key] === null)) {
            $output .= $key . $this->formatQuotedString($this->entry[$key]);
            $key = PoTokens::PLURAL;
            if (!($this->entry[$key] === null)) {
                $output .= $key . $this->formatQuotedString($this->entry[$key]);
                $key = PoTokens::TRANSLATED;
                $plurals = $this->entry[$key];
                $plurals = is_array($plurals) ? $plurals : array('', '');
                foreach ($plurals as $i => $value) {
                    $output .= "{$key}[{$i}]" . $this->formatQuotedString($value);
                }
            } else {
                $key = PoTokens::TRANSLATED;
                $output .= $key . $this->formatQuotedString($this->entry[$key]);
            }
        }

        $output .= "\n";
        return $output;
    }

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


Question: Returns the correct cast from JSON to PostgreSQL type

function parse_predicate_pgcast_by_type(pgtype) {
	//debug.log('pgtype = ', pgtype);
	if(is.func(_pgcasts[pgtype])) {
		return _pgcasts[pgtype];
	}
	return function pgcast_default(x) { return '' + x + '::' + pgtype; };
}

public function mapToGoogle(Entity $obj_gds_entity, \google\appengine\datastore\v4\Entity $obj_entity)
    {
        // Key
        $this->configureGoogleKey($obj_entity->mutableKey(), $obj_gds_entity);

        // Properties
        $arr_field_defs = $this->obj_schema->getProperties();
        foreach($obj_gds_entity->getData() as $str_field_name => $mix_value) {
            $obj_prop = $obj_entity->addProperty();
            $obj_prop->setName($str_field_name);
            $obj_val = $obj_prop->mutableValue();
            if(isset($arr_field_defs[$str_field_name])) {
                $this->configureGooglePropertyValue($obj_val, $arr_field_defs[$str_field_name], $mix_value);
            } else {
                $arr_dynamic_data = $this->determineDynamicType($mix_value);
                $this->configureGooglePropertyValue($obj_val, ['type' => $arr_dynamic_data['type'], 'index' => TRUE], $arr_dynamic_data['value']);
            }
        }
    }

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


Question:
Load vi personal names.

@param filename the filename

public static void loadViPersonalNames(String filename) {
		try {
			FileInputStream in = new FileInputStream(filename);
			if (hsViFamilyNames == null) {

				hsViFamilyNames = new HashSet();
				hsViLastNames = new HashSet();
				hsViMiddleNames = new HashSet();

				BufferedReader reader = new BufferedReader(
						new InputStreamReader(in, "UTF-8"));
				String line;
				while ((line = reader.readLine()) != null) {
					line = line.trim();
					if (line.equals(""))
						continue;

					//line = line.toLowerCase();
					int idxSpace = line.indexOf(' ');
					int lastIdxSpace = line.lastIndexOf(' ');

					if (idxSpace != -1) {
						String strFamilyName = line.substring(0, idxSpace);
						hsViFamilyNames.add(strFamilyName);
					}

					if ((idxSpace != -1) && (lastIdxSpace > idxSpace + 1)) {
						String strMiddleName = line.substring(idxSpace + 1,
								lastIdxSpace - 1);
						hsViMiddleNames.add(strMiddleName);
					}

					if (lastIdxSpace != -1) {
						String strLastName = line.substring(lastIdxSpace + 1,
								line.length());
						hsViLastNames.add(strLastName);
					}
				}
				in.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.err.print(e.getMessage());
		}
	}

public function buildView(FormView $view, FormInterface $form, array $options)
    {
        if (array_key_exists('preview_base_path', $options)) {
            $parentData = $form->getParent()->getData();

            $previewUrl = null;
            if (null !== $parentData) {
                $accessor = PropertyAccess::createPropertyAccessor();
                $previewUrl = $accessor->getValue($parentData, $options['preview_base_path']);
            }

            if (!empty($previewUrl)) {
                $pathInfo = pathinfo($previewUrl);
                // define path to preview resource
                $view->vars['preview_url'] = $previewUrl;
                $view->vars['preview_basename'] = $pathInfo['basename'];
            }
        }
    }

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


Question:
Returns the initialized localization context.<p>
@param pc the current page context
@param basename the bas name of the bundle

@return the initialized localization context

public static LocalizationContext getLocalizationContext(PageContext pc, String basename) {

        LocalizationContext locCtxt = null;
        ResourceBundle bundle = null;

        if ((basename == null) || basename.equals("")) {
            return new LocalizationContext();
        }

        // Try preferred locales
        Locale pref = getLocale(pc, javax.servlet.jsp.jstl.core.Config.FMT_LOCALE);
        if (pref != null) {
            // Preferred locale is application-based
            bundle = findMatch(basename, pref);
            if (bundle != null) {
                locCtxt = new LocalizationContext(bundle, pref);
            }
        }

        if (locCtxt == null) {
            // No match found with preferred locales, try using fallback locale
            locCtxt = BundleSupport.getLocalizationContext(pc, basename);
        } else {
            // set response locale
            if (locCtxt.getLocale() != null) {
                setResponseLocale(pc, locCtxt.getLocale());
            }
        }

        return locCtxt;
    }

def _get_db_refs(term):
    """"""
    db_refs = {}
    # Here we extract the text name of the Agent
    # There are two relevant tags to consider here.
    # The <text> tag typically contains a larger phrase surrounding the
    # term but it contains the term in a raw, non-canonicalized form.
    # The <name> tag only contains the name of the entity but it is
    # canonicalized. For instance, MAP2K1 appears as MAP-2-K-1.
    agent_text_tag = term.find('name')
    if agent_text_tag is not None:
        db_refs['TEXT'] = agent_text_tag.text
        # If we have some drum-terms, the matched-name of the first
        # drum-term (e.g. "MAP2K1") is a better value for TEXT than
        # the name of the TERM (e.g. "MAP-2-K-1") so we put that in there
        drum_terms = term.findall('drum-terms/drum-term')
        if drum_terms:
            matched_name = drum_terms[0].attrib.get('matched-name')
            if matched_name:
                db_refs['TEXT'] = matched_name

    # We make a list of scored grounding terms from the DRUM terms
    grounding_terms = _get_grounding_terms(term)
    if not grounding_terms:
        # This is for backwards compatibility with EKBs without drum-term
        # scored entries. It is important to keep for Bioagents
        # compatibility.
        dbid = term.attrib.get('dbid')
        if dbid:
            dbids = dbid.split('|')
            for dbname, dbid in [d.split(':') for d in dbids]:
                if not db_refs.get(dbname):
                    db_refs[dbname] = dbid
        return db_refs, None, []

    # This is the INDRA prioritization of grounding name spaces. Lower score
    # takes precedence.
    ns_priority = {
        'HGNC': 1,
        'UP': 1,
        'FPLX': 2,
        'CHEBI': 3,
        'PC': 3,
        'GO': 4,
        'FA': 5,
        'XFAM': 5,
        'NCIT': 5
    }
    # We get the top priority entry from each score group
    score_groups = itertools.groupby(grounding_terms, lambda x: x['score'])
    top_per_score_group = []
    ambiguities = []
    for score, group in score_groups:
        entries = list(group)
        for entry in entries:
            priority = 100
            for ref_ns, ref_id in entry['refs'].items():
                # Skip etc UP entries
                if ref_ns == 'UP' and ref_id == 'etc':
                    continue
                try:
                    priority = min(priority, ns_priority[ref_ns])
                except KeyError:
                    pass
                if ref_ns == 'UP':
                    if not up_client.is_human(ref_id):
                        priority = 4
            entry['priority'] = priority
        if len(entries) > 1:
            top_entry = entries[0]
            top_idx = 0
            for i, entry in enumerate(entries):
                # We take the lowest priority entry within the score group
                # as the top entry
                if entry['priority'] < top_entry['priority']:
                    # This is a corner case in which a protein family
                    # should be prioritized over a specific protein,
                    # specifically when HGNC was mapped from NCIT but
                    # FPLX was not mapped from NCIT, the HGNC shouldn't
                    # take precedence.
                    if entry.get('comment') == 'HGNC_FROM_NCIT' and \
                        'FPLX' in top_entry['refs'] and \
                        top_entry.get('comment') != 'FPLX_FROM_NCIT':
                        continue
                    top_entry = entry
                    top_idx = i
            for i, entry in enumerate(entries):
                if i == top_idx:
                    continue
                if (entry['priority'] - top_entry['priority']) <= 1:
                    ambiguities.append((top_entry, entry))
        else:
            top_entry = entries[0]
        top_per_score_group.append(top_entry)
    # Get the top priority for each score group
    priorities = [entry['priority'] for entry in top_per_score_group]

    # By default, we coose the top priority entry from the highest score group
    top_grounding = top_per_score_group[0]
    # Sometimes the top grounding has much lower priority and not much higher
    # score than the second grounding. Typically 1.0 vs 0.82857 and 5 vs 2.
    # In this case we take the second entry. A special case is handled where
    # a FPLX entry was mapped from FA, in which case priority difference of < 2
    # is also accepted.
    if len(top_per_score_group) > 1:
        score_diff = top_per_score_group[0]['score'] - \
                     top_per_score_group[1]['score']
        priority_diff = top_per_score_group[0]['priority'] - \
                        top_per_score_group[1]['priority']
        if score_diff < 0.2 and (priority_diff >= 2 or \
            top_per_score_group[0].get('comment') == 'FPLX_FROM_FA'):
            top_grounding = top_per_score_group[1]
    relevant_ambiguities = []
    for amb in ambiguities:
        if top_grounding not in amb:
            continue
        if top_grounding == amb[0]:
            relevant_ambiguities.append({'preferred': amb[0],
                                         'alternative': amb[1]})
        else:
            relevant_ambiguities.append({'preferred': amb[1],
                                         'alternative': amb[0]})

    for k, v in top_grounding['refs'].items():
        db_refs[k] = v

    # Now standardize db_refs to the INDRA standards
    # We need to add a prefix for CHEBI
    chebi_id = db_refs.get('CHEBI')
    if chebi_id and not chebi_id.startswith('CHEBI:'):
        db_refs['CHEBI'] = 'CHEBI:%s' % chebi_id
    # We need to strip the trailing version number for XFAM and rename to PF
    pfam_id = db_refs.get('XFAM')
    if pfam_id:
        pfam_id = pfam_id.split('.')[0]
        db_refs.pop('XFAM', None)
        db_refs['PF'] = pfam_id
    # We need to add GO prefix if it is missing
    go_id = db_refs.get('GO')
    if go_id:
        if not go_id.startswith('GO:'):
            db_refs['GO'] = 'GO:%s' % go_id
    # We need to deal with Nextprot families
    nxp_id = db_refs.get('FA')
    if nxp_id:
        db_refs.pop('FA', None)
        db_refs['NXPFA'] = nxp_id
    # We need to rename PC to PUBCHEM
    pc_id = db_refs.get('PC')
    if pc_id:
        db_refs.pop('PC', None)
        db_refs['PUBCHEM'] = pc_id

    # Here we also get and return the type, which is a TRIPS
    # ontology type. This is to be used in the context of
    # Bioagents.
    ont_type = top_grounding['type']

    return db_refs, ont_type, relevant_ambiguities

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


Question:
Validates the password.
This method serves as the inline validation for password.

public function validatePassword()
    {
        /* @var $user User */
        $user = Yii::$app->user->identity;
        if (!$user || !$user->validatePassword($this->oldPassword)) {
            $this->addError('oldPassword', 'Incorrect old password.');
        }
    }

private boolean isValidCharacters(final String component, final char padding) {
		// Check the component is either all padding chars or all digit chars
		boolean paddingChars = false;
		boolean digitChars = false;
		for (int i = 0; i < component.length(); i++) {
			char chr = component.charAt(i);
			// Padding
			if (chr == padding) {
				if (digitChars) {
					return false;
				}
				paddingChars = true;
			} else if (chr >= '0' && chr <= '9') {  // Digit
				if (paddingChars) {
					return false;
				}
				digitChars = true;
			} else {
				return false;
			}
		}

		return true;
	}

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


Question: // SetGroupName sets the GroupName field's value.

func (s *ListGroupPoliciesInput) SetGroupName(v string) *ListGroupPoliciesInput {
	s.GroupName = &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:
shortcut method

@param object $object
@param object $parent

@return bool

public function grantInheritedAccess($object, $parent)
    {
        return $this->grantAccess($object, null, Permissions::PERMISSIONS_IGNORE, true, $parent);
    }

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

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

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

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

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

		return $this->filteredData;
	}

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


Question:
Return the completeness as a function of magnitude.

        ADW: Eventually want a completeness mask to set overall efficiency.

def completeness(self, delta, method='step'):

        delta = np.asarray(delta)
        if method == 'step':
            func = lambda delta: (delta > 0).astype(float)
        elif method == 'erf':
            # Trust the SDSS EDR???
            # 95% completeness:
            def func(delta):
                # Efficiency at bright end (assumed to be 100%)
                e = 1.0
                # EDR says full width is ~0.5 mag
                width = 0.2
                # This should be the halfway point in the curve
                return (e/2.0)*(1/np.sqrt(2*width))*(np.sqrt(2*width)-scipy.special.erf(-delta))
        elif method == 'flemming':
            # Functional form taken from Fleming et al. AJ 109, 1044 (1995)
            # http://adsabs.harvard.edu/abs/1995AJ....109.1044F
            # f = 1/2 [1 - alpha(V - Vlim)/sqrt(1 + alpha^2 (V - Vlim)^2)]
            # CAREFUL: This definition is for Vlim = 50% completeness
            def func(delta):
                alpha = 2.0
                return 0.5 * (1 - (alpha * delta)/np.sqrt(1+alpha**2 * delta**2))
        else:
            raise Exception('...')
        return func(delta)

def _read_body_by_chunk(self, response, file, raw=False):
        '''
        '''
        reader = ChunkedTransferReader(self._connection)

        file_is_async = hasattr(file, 'drain')

        while True:
            chunk_size, data = yield from reader.read_chunk_header()

            self._data_event_dispatcher.notify_read(data)
            if raw:
                file.write(data)

            if not chunk_size:
                break

            while True:
                content, data = yield from reader.read_chunk_body()

                self._data_event_dispatcher.notify_read(data)

                if not content:
                    if raw:
                        file.write(data)

                    break

                content = self._decompress_data(content)

                if file:
                    file.write(content)

                    if file_is_async:
                        yield from file.drain()

        content = self._flush_decompressor()

        if file:
            file.write(content)

            if file_is_async:
                yield from file.drain()

        trailer_data = yield from reader.read_trailer()

        self._data_event_dispatcher.notify_read(trailer_data)

        if file and raw:
            file.write(trailer_data)

            if file_is_async:
                yield from file.drain()

        response.fields.parse(trailer_data)

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


Question:
Normalize local disk-based path. Ex: ../../dir/./dir/file.txt
@param string $path
@return string

public static function diskPath($path)
    {
        // its full-based path? Lets return real path
        if (Str::startsWith(root, $path)) {
            // fix path collisions if is not exist
            if (file_exists($path)) {
                return realpath($path);
            } else {
                return $path;
            }
        }
        // else - sounds like relative path
        $path = Str::replace('\\', '/', $path);
        $splitPath = explode('/', $path);

        $outputPath = [];
        foreach ($splitPath as $index => $part) {
            if ($part === '.' || Str::length(trim($part)) < 1) {
                continue;
            }

            if ($part === '..') { // level-up (:
                array_pop($outputPath);
                continue;
            }

            $outputPath[] = trim($part);
        }
        return implode(DIRECTORY_SEPARATOR, $outputPath);
    }

func (p *parserMixin) ExistingFileOrDir() (target *string) {
	target = new(string)
	p.ExistingFileOrDirVar(target)
	return
}

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


Question:
/*
Perform an unescape operation based on String.

static String unescape(final String text) {

        if (text == null) {
            return null;
        }

        StringBuilder strBuilder = null;

        final int offset = 0;
        final int max = text.length();

        int readOffset = offset;
        int referenceOffset = offset;

        for (int i = offset; i < max; i++) {

            final char c = text.charAt(i);

            /*
             * Check the need for an unescape operation at this point
             */

            if (c != ESCAPE_PREFIX || (i + 1) >= max) {
                continue;
            }

            int codepoint = -1;

            if (c == ESCAPE_PREFIX) {

                final char c1 = text.charAt(i + 1);

                switch (c1) {
                        // line feed. When escaped, this is a line continuator
                    case '\n': codepoint = -2; referenceOffset = i + 1; break;
                    case ' ':
                    case '!':
                    case '"':
                    case '#':
                    case '$':
                    case '%':
                    case '&':
                    case '\'':
                    case '(':
                    case ')':
                    case '*':
                    case '+':
                    case ',':
                        // hyphen: will only be escaped when identifer starts with '--' or '-{digit}'
                    case '-':
                    case '.':
                    case '/':
                        // colon: will not be used for escaping: not recognized by IE < 8
                    case ':':
                    case ';':
                    case '<':
                    case '=':
                    case '>':
                    case '?':
                    case '@':
                    case '[':
                    case '\\':
                    case ']':
                    case '^':
                        // underscore: will only be escaped at the beginning of an identifier (in order to avoid issues in IE6)
                    case '_':
                    case '`':
                    case '{':
                    case '|':
                    case '}':
                    case '~': codepoint = (int)c1; referenceOffset = i + 1; break;
                }

                if (codepoint == -1) {

                    if ((c1 >= '0' && c1 <= '9') || (c1 >= 'A' && c1 <= 'F') || (c1 >= 'a' && c1 <= 'f')) {
                        // This is a hexa escape

                        int f = i + 2;
                        while (f < (i + 7) && f < max) {
                            final char cf = text.charAt(f);
                            if (!((cf >= '0' && cf <= '9') || (cf >= 'A' && cf <= 'F') || (cf >= 'a' && cf <= 'f'))) {
                                break;
                            }
                            f++;
                        }

                        codepoint = parseIntFromReference(text, i + 1, f, 16);

                        // Fast-forward to the first char after the parsed codepoint
                        referenceOffset = f - 1;

                        // If there is a whitespace after the escape, just ignore it.
                        if (f < max && text.charAt(f) == ' ') {
                            referenceOffset++;
                        }

                        // Don't continue here, just let the unescape code below do its job

                    } else if (c1 == '\r' || c1 == '\f') {

                        // The only characters that cannot be escaped by means of a backslash are
                        // carriage return and form feed (besides hexadecimal digits).
                        i++;
                        continue;

                    } else {

                        // We weren't able to consume any valid escape chars, just consider it a normal char,
                        // which is allowed by the CSS escape syntax.

                        codepoint = (int) c1;
                        referenceOffset = i + 1;

                    }

                }

            }

            /*
             * At this point we know for sure we will need some kind of unescape, so we
             * can increase the offset and initialize the string builder if needed, along with
             * copying to it all the contents pending up to this point.
             */

            if (strBuilder == null) {
                strBuilder = new StringBuilder(max + 5);
            }

            if (i - readOffset > 0) {
                strBuilder.append(text, readOffset, i);
            }

            i = referenceOffset;
            readOffset = i + 1;

            /*
             * --------------------------
             *
             * Perform the real unescape
             *
             * --------------------------
             */

            if (codepoint > '\uFFFF') {
                strBuilder.append(Character.toChars(codepoint));
            } else if (codepoint != -2){ // We use -2 to signal the line continuator, which should be ignored in output
                strBuilder.append((char)codepoint);
            }

        }

        /*
         * -----------------------------------------------------------------------------------------------
         * Final cleaning: return the original String object if no unescape was actually needed. Otherwise
         *                 append the remaining escaped text to the string builder and return.
         * -----------------------------------------------------------------------------------------------
         */

        if (strBuilder == null) {
            return text;
        }

        if (max - readOffset > 0) {
            strBuilder.append(text, readOffset, max);
        }

        return strBuilder.toString();

    }

def _construct_url(self, url, base, quote):

        if not base and not quote:
            return url
        else:
            url = url + base.lower() + quote.lower() + "/"
            return url

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


Question:
Updates the instance by adding a new position. This will cause all properties to be
re-calculated, depending on the new position.

@param position
The position, which should be added, as a {@link Float} value

public final void update(final float position) {
        if (reset) {
            reset = false;
            distance = 0;
            thresholdReachedPosition = -1;
            dragStartTime = -1;
            dragStartPosition = position;
            reachedThreshold = false;
            minDragDistance = 0;
            maxDragDistance = 0;
        }

        if (!reachedThreshold) {
            if (reachedThreshold(position - dragStartPosition)) {
                dragStartTime = System.currentTimeMillis();
                reachedThreshold = true;
                thresholdReachedPosition = position;
            }
        } else {
            float newDistance = position - thresholdReachedPosition;

            if (minDragDistance != 0 && minDragDistance > newDistance) {
                newDistance = minDragDistance;
                thresholdReachedPosition = position - minDragDistance;
            }

            if (maxDragDistance != 0 && maxDragDistance < newDistance) {
                newDistance = maxDragDistance;
                thresholdReachedPosition = position - maxDragDistance;
            }

            distance = newDistance;
        }
    }

public function set_model( $model )
    {
        // Check that the required arguments are provided.
        foreach( $this->required_arguments() as $key )
        {
            if ( !isset($model[$key]) )
            {
                throw new \RuntimeException('The required argument "'.$key.'" was not provided for '.get_called_class());
            }
        }

        // Assign the name of the component as the id if no id was specified
        if( !isset($model['id']) && isset($model['name']) )
        {
            $model['id'] = $model['name'];
        }

        // A name must be specified when a component has a visibility condition
        if( isset($model['show']) && !isset($model['name']) )
        {
            throw new \RuntimeException('Components with a visibility condition (a "show" argument) must have a name');
        }

        $this->model = array_merge( $this->default_model(), $model );
    }

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


Question:
// AllocateNext reserves one of the ports from the pool. ErrFull may
// be returned if there are no ports left.

func (r *Allocator) AllocateNext() (uid.Block, error) {
	offset, ok, err := r.alloc.AllocateNext()
	if err != nil {
		return uid.Block{}, err
	}
	if !ok {
		return uid.Block{}, ErrFull
	}
	block, ok := r.r.BlockAt(uint32(offset))
	if !ok {
		return uid.Block{}, ErrNotInRange
	}
	return block, nil
}

def _events_available_in_scheduled_slot(events, slots, X, **kwargs):

    slot_availability_array = lpu.slot_availability_array(slots=slots,
                                                          events=events)

    label = 'Event scheduled when not available'
    for row, event in enumerate(slot_availability_array):
        for col, availability in enumerate(event):
            if availability == 0:
                yield Constraint(
                    f'{label} - event: {row}, slot: {col}',
                    X[row, col] <= availability
                )

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


Question: Return the |small_phi| of a mechanism over a purview.

def phi(self, mechanism, purview):
        """"""
        return min(self.phi_cause_mip(mechanism, purview),
                   self.phi_effect_mip(mechanism, purview))

public function setMinPlays($minPlays)
    {
        if (is_int($minPlays) === true && $minPlays >= 0) {
            $this->minPlays = $minPlays;
        } else {
            $msg = "The 'minPlays' argument must be a positive (>= 0) integer, '" . gettype($minPlays) . "' given.";
            throw new InvalidArgumentException($msg);
        }
    }

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


Question:
You can modify the container here before it is dumped to PHP code.

@param ContainerBuilder $container

@api

public function process(ContainerBuilder $container)
    {
        $exporter = $container->getDefinition('chameleon_system_shop_product_export.exporter');
        $exportHandlerIds = $container->findTaggedServiceIds('chameleon_system_shop_product_export.export_handler');
        $aliasRegistered = array();
        foreach ($exportHandlerIds as $exportHandlerId => $tagAttributes) {
            foreach ($tagAttributes as $attributes) {
                $alias = (isset($attributes['alias'])) ? $attributes['alias'] : null;
                if (null === $alias) {
                    throw new \ErrorException("the service {$exportHandlerId} is tagged als an export_handler but the tag is missing the alias attribute.", 0, E_USER_ERROR, __FILE__, __LINE__);
                }

                if (in_array($alias, $aliasRegistered)) {
                    throw new \ErrorException("unable to register the export handler {$exportHandlerId} because there is already a handler registered with the alias {$alias}", 0, E_USER_ERROR, __FILE__, __LINE__);
                }
                $aliasRegistered[] = $alias;
                $exporter->addMethodCall('registerHandler', array($alias, $container->getDefinition($exportHandlerId)));
            }
        }

        if (0 === count($aliasRegistered)) {
            throw new \ErrorException('no export handlers found for the shop article list exporter! Please unregister the bundle or add export handler (by tagging them with chameleon_system_shop_product_export.export_handler)', 0, E_USER_ERROR, __FILE__, __LINE__);
        }
    }

protected function _buildAndExecuteProxyResponse()
    {
        if($this->_responseModifier)
        {
          $data = call_user_func_array($this->_responseModifier, array(&$this->_responseBody, &$this->_responseHeaders));
        }

        $this->_generateProxyResponseHeaders();

        $this->_output($this->_responseBody);
    }

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


Question: Ask reset password

async function askResetPassword(form) {
  await client.connect();

  try {
    await api.askResetPassword(
      {
        login: form.login.value
      },
      "user"
    );
    displayMessage(
      "Reset password",
      "A link was sent to reset your password",
      "is-success"
    );
    goTo("login");
  } catch (e) {
    displayMessage(
      "Reset password",
      `Failed to send the link to reset your password. Cause: ${e.message}`,
      "is-danger"
    );
  }
}

def set_auth_request(self, interface_id, address=None):

        self.interface.set_auth_request(interface_id, address)
        self._engine.update()

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


Question: // handle Write request. [Vol 3, Part F, 3.4.5.1 & 3.4.5.2]

func (s *Server) handleWriteRequest(r WriteRequest) []byte {
	// Validate the request.
	switch {
	case len(r) < 3:
		return newErrorResponse(r.AttributeOpcode(), 0x0000, ble.ErrInvalidPDU)
	}

	a, ok := s.db.at(r.AttributeHandle())
	if !ok {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), ble.ErrInvalidHandle)
	}

	// We don't support write to static value. Pass the request to upper layer.
	if a == nil {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), ble.ErrWriteNotPerm)
	}
	if e := handleATT(a, s.conn, r, ble.NewResponseWriter(nil)); e != ble.ErrSuccess {
		return newErrorResponse(r.AttributeOpcode(), r.AttributeHandle(), e)
	}
	return []byte{WriteResponseCode}
}

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

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

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

	return res, nil
}

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


Question: reset driver's properties.

public function reset()
    {
        $args = func_get_args();
        extract(self::parseArgs($args));
        if ($this->weight !== $weight) {
            $this->weight($weight);
        }
        if ($this->backup !== $backup) {
            $this->backup($backup);
        }
        if (is_callable($work) && $this->work !== $work) {
            $this->work($work);
        }

        return $this;
    }

public function addConfigurationSetting($name, $value)
    {
        $this->checkConnectionUp("Cannot set configuration once a connection is made with the server.")
            ->configurator->set($name, $value);

        return $this;
    }

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


Question:
// allInstances returns all of the instances in the given resource group,
// and optionally ensures that each instance's addresses are up-to-date.

func (env *azureEnviron) allInstances(
	ctx context.ProviderCallContext,
	resourceGroup string,
	refreshAddresses bool,
	controllerOnly bool,
) ([]instances.Instance, error) {
	deploymentsClient := resources.DeploymentsClient{env.resources}
	sdkCtx := stdcontext.Background()
	deploymentsResult, err := deploymentsClient.ListByResourceGroupComplete(sdkCtx, resourceGroup, "", nil)
	if err != nil {
		if isNotFoundResult(deploymentsResult.Response().Response) {
			// This will occur if the resource group does not
			// exist, e.g. in a fresh hosted environment.
			return nil, nil
		}
		return nil, errorutils.HandleCredentialError(errors.Trace(err), ctx)
	}
	if deploymentsResult.Response().IsEmpty() {
		return nil, nil
	}

	var azureInstances []*azureInstance
	for ; deploymentsResult.NotDone(); err = deploymentsResult.NextWithContext(sdkCtx) {
		if err != nil {
			return nil, errors.Annotate(err, "listing resources")
		}
		deployment := deploymentsResult.Value()
		name := to.String(deployment.Name)
		if _, err := names.ParseMachineTag(name); err != nil {
			// Deployments we create for Juju machines are named
			// with the machine tag. We also create a "common"
			// deployment, so this will exclude that VM and any
			// other stray deployment resources.
			continue
		}
		if deployment.Properties == nil || deployment.Properties.Dependencies == nil {
			continue
		}
		if controllerOnly && !isControllerDeployment(deployment) {
			continue
		}
		provisioningState := to.String(deployment.Properties.ProvisioningState)
		inst := &azureInstance{name, provisioningState, env, nil, nil}
		azureInstances = append(azureInstances, inst)
	}

	if len(azureInstances) > 0 && refreshAddresses {
		if err := setInstanceAddresses(
			ctx,
			resourceGroup,
			network.InterfacesClient{env.network},
			network.PublicIPAddressesClient{env.network},
			azureInstances,
		); err != nil {
			return nil, errors.Trace(err)
		}
	}

	instances := make([]instances.Instance, len(azureInstances))
	for i, inst := range azureInstances {
		instances[i] = inst
	}
	return instances, 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: Determine what type of element this is. It will either return the `type` attribute of an `<input>` element, or the `tagName` of the element when the element is not an `<input>`.

function(el) {
  var typeAttr;
  var $el = $(el);
  var tagName = $el[0].tagName;
  var type = tagName;

  if (tagName.toLowerCase() === 'input') {
    typeAttr = $el.attr('type');
    if (typeAttr) {
      type = typeAttr;
    } else {
      type = 'text';
    }
  }

  if (('' + $el.attr('contenteditable')).toLowerCase() === 'true') {
    type = 'contenteditable';
  }

  // Always return the type as lowercase
  // so it can be matched to lowercase
  // type registrations.
  return type.toLowerCase();
}

protected function setActionAttribute()
    {
        $Eresus = Eresus_CMS::getLegacyKernel();

        /** @var DOMElement $form */
        $form = $this->xml->getElementsByTagName('form')->item(0);
        $url = $Eresus->request['path'];

        /*
         * Если есть тег marker и нет тега redirect, то маркер надо добавить к адресу в атрибуте
         * action.
         */
        $markers = $this->xml->getElementsByTagNameNS(self::NS, 'marker');
        $redirects = $this->xml->getElementsByTagNameNS(self::NS, 'redirect');
        if ($markers->length > 0 && 0 == $redirects->length)
        {
            // На случай если указано несколько маркеров, берём только последний
            /** @var DOMElement $marker */
            $marker = $markers->item($markers->length - 1);
            $url .= '#' . $marker->getAttribute('value');
        }

        $form->setAttribute('action', $url);
    }

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


Question: DEPRECATED. use user.addToGroup()

@Deprecated
    public void addUserToGroup(User user, Group group) throws RedmineException {
        transport.addUserToGroup(user.getId(), group.getId());
    }

public function createUserAsync($writerId, $email, $password, $firstName, $lastName, $queue = 'primary')
    {
        return $this->getCommand('CreateUser', [
            'writerId' => $writerId,
            'email' => $email,
            'password' => $password,
            'firstName' => $firstName,
            'lastName' => $lastName,
            'queue' => $queue
        ])->execute();
    }

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


Question:
Transliterate to 8 bit using only single letter replacements.

    For example, \u2639 WHITE FROWNING FACE ``☹`` will be passed
    through unchanged.

def single_encode(input, errors='strict'):

    if not isinstance(input, text_type):
        input = text_type(input, sys.getdefaultencoding(), errors)
    length = len(input)
    input = unicodedata.normalize('NFKC', input)
    return input.translate(single_table), length

def smart_convert(original, colorkey, pixelalpha):

    tile_size = original.get_size()
    threshold = 127  # the default

    try:
        # count the number of pixels in the tile that are not transparent
        px = pygame.mask.from_surface(original, threshold).count()
    except:
        # pygame_sdl2 will fail because the mask module is not included
        # in this case, just convert_alpha and return it
        return original.convert_alpha()

    # there are no transparent pixels in the image
    if px == tile_size[0] * tile_size[1]:
        tile = original.convert()

    # there are transparent pixels, and tiled set a colorkey
    elif colorkey:
        tile = original.convert()
        tile.set_colorkey(colorkey, pygame.RLEACCEL)

    # there are transparent pixels, and set for perpixel alpha
    elif pixelalpha:
        tile = original.convert_alpha()

    # there are transparent pixels, and we won't handle them
    else:
        tile = original.convert()

    return tile

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


Question:
Returns the {@link ProcessInstance} currently associated or 'null'

@throws ProcessEngineCdiException
if no {@link Execution} is associated. Use
{@link #isAssociated()} to check whether an association exists.

public ProcessInstance getProcessInstance() {
    Execution execution = getExecution();
    if(execution != null && !(execution.getProcessInstanceId().equals(execution.getId()))){
      return processEngine
            .getRuntimeService()
            .createProcessInstanceQuery()
            .processInstanceId(execution.getProcessInstanceId())
            .singleResult();
    }
    return (ProcessInstance) execution;
  }

def _RunActions(self, rule, client_id):

    actions_count = 0

    for action in rule.actions:
      try:
        # Say this flow came from the foreman.
        token = self.token.Copy()
        token.username = "Foreman"

        if action.HasField("hunt_id"):
          if self._CheckIfHuntTaskWasAssigned(client_id, action.hunt_id):
            logging.info(
                "Foreman: ignoring hunt %s on client %s: was started "
                "here before", client_id, action.hunt_id)
          else:
            logging.info("Foreman: Starting hunt %s on client %s.",
                         action.hunt_id, client_id)

            flow_cls = registry.AFF4FlowRegistry.FlowClassByName(
                action.hunt_name)
            flow_cls.StartClients(action.hunt_id, [client_id])
            actions_count += 1
        else:
          flow.StartAFF4Flow(
              client_id=client_id,
              flow_name=action.flow_name,
              token=token,
              **action.argv.ToDict())
          actions_count += 1
      # There could be all kinds of errors we don't know about when starting the
      # flow/hunt so we catch everything here.
      except Exception as e:  # pylint: disable=broad-except
        logging.exception("Failure running foreman action on client %s: %s",
                          action.hunt_id, e)

    return actions_count

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


Question: Konfiguracja formularza

public function init()
    {

        //adres
        $this->addElement((new Element\Text('address'))
            ->setLabel('form.mail.server.address.label'));

        //ssl
        $this->addElement((new Element\Select('ssl'))
            ->setLabel('form.mail.server.ssl.label')
            ->setRequired()
            ->addValidator(new \Mmi\Validator\NotEmpty)
            ->setMultioptions(['plain' => 'plain', 'tls' => 'tls', 'ssl' => 'ssl']));

        //port
        $this->addElement((new Element\Text('port'))
            ->setLabel('form.mail.server.port.label')
            ->setRequired()
            ->addValidator(new \Mmi\Validator\Integer([true]))
            ->setValue(25)
            ->setDescription('Plain: 25, SSL: 465, TLS: 587'));

        //użytkownik
        $this->addElement((new Element\Text('username'))
            ->setLabel('form.mail.server.username.label'));

        //hasło
        $this->addElement((new Element\Text('password'))
            ->setLabel('form.mail.server.password.label'));

        //od
        $this->addElement((new Element\Text('from'))
            ->setLabel('form.mail.server.from.label'));

        //submit
        $this->addElement((new Element\Submit('submit'))
            ->setLabel('form.mail.server.submit.label'));
    }

def list_build_configurations(page_size=200, page_index=0, sort="", q=""):

    data = list_build_configurations_raw(page_size, page_index, sort, q)
    if data:
        return utils.format_json_list(data)

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


Question:
Returns the highest value from the collection of values

Key can be a string key or callable. Based on Laravel: Illuminate\Support\Collection.max

@param null|string $key

@return mixed

public function max($key = null)
    {
        $callback = $this->valueAccessor($key);

        return $this->filter(function ($value) {
            return !is_null($value);
        })->reduce(function ($result, $item) use ($callback) {
            $value = $callback($item);

            return is_null($result) || $value > $result ? $value : $result;
        });
    }

private function findAllRecords(Driver $driver, array $columns)
    {
        $columns = array_merge(array('id'), $columns);
        $output = array($columns);

        $this->managerFactory->setModelClass($this->modelClass);
        /** @var ModelInterface $record */
        foreach ($this->managerFactory->getManager($driver)->paginate(1, $this->maxRecords) as $record) {
            $temp = array();
            foreach ($columns as $column) {
                $temp[] = MethodInvoker::invokeGet($record, $column);
            }

            $output[] = $temp;
        }

        return $output;
    }

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


Question:
Build the whole WHERE SQL statement part for the given log entry filter.<p>

@param filter the filter

@return a pair containing both the SQL and the parameters for it

protected CmsPair<String, List<I_CmsPreparedStatementParameter>> prepareLogConditions(CmsLogFilter filter) {

        List<I_CmsPreparedStatementParameter> params = new ArrayList<I_CmsPreparedStatementParameter>();
        StringBuffer conditions = new StringBuffer();

        // user id filter
        if (filter.getUserId() != null) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_USER_ID"));
            params.add(new CmsPreparedStatementStringParameter(filter.getUserId().toString()));
            conditions.append(END_CONDITION);
        }

        // resource id filter
        if (filter.getStructureId() != null) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_RESOURCE_ID"));
            params.add(new CmsPreparedStatementStringParameter(filter.getStructureId().toString()));
            conditions.append(END_CONDITION);
        }

        // date from filter
        if (filter.getDateFrom() != CmsResource.DATE_RELEASED_DEFAULT) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_DATE_FROM"));
            params.add(new CmsPreparedStatementLongParameter(filter.getDateFrom()));
            conditions.append(END_CONDITION);
        }

        // date to filter
        if (filter.getDateTo() != CmsResource.DATE_RELEASED_DEFAULT) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_DATE_TO"));
            params.add(new CmsPreparedStatementLongParameter(filter.getDateTo()));
            conditions.append(END_CONDITION);
        }

        // include type filter
        Set<CmsLogEntryType> includeTypes = filter.getIncludeTypes();
        if (!includeTypes.isEmpty()) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_INCLUDE_TYPE"));
            conditions.append(BEGIN_CONDITION);
            Iterator<CmsLogEntryType> it = includeTypes.iterator();
            while (it.hasNext()) {
                CmsLogEntryType type = it.next();
                conditions.append("?");
                params.add(new CmsPreparedStatementIntParameter(type.getId()));
                if (it.hasNext()) {
                    conditions.append(", ");
                }
            }
            conditions.append(END_CONDITION);
            conditions.append(END_CONDITION);
        }

        // exclude type filter
        Set<CmsLogEntryType> excludeTypes = filter.getExcludeTypes();
        if (!excludeTypes.isEmpty()) {
            if (conditions.length() == 0) {
                conditions.append(BEGIN_CONDITION);
            } else {
                conditions.append(BEGIN_INCLUDE_CONDITION);
            }
            conditions.append(m_sqlManager.readQuery("C_LOG_FILTER_EXCLUDE_TYPE"));
            conditions.append(BEGIN_CONDITION);
            Iterator<CmsLogEntryType> it = excludeTypes.iterator();
            while (it.hasNext()) {
                CmsLogEntryType type = it.next();
                conditions.append("?");
                params.add(new CmsPreparedStatementIntParameter(type.getId()));
                if (it.hasNext()) {
                    conditions.append(", ");
                }
            }
            conditions.append(END_CONDITION);
            conditions.append(END_CONDITION);
        }
        return CmsPair.create(conditions.toString(), params);
    }

def sql_fingerprint(query, hide_columns=True):

    parsed_query = parse(query)[0]
    sql_recursively_simplify(parsed_query, hide_columns=hide_columns)
    return str(parsed_query)

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


Question:
Returns a custom date representation. A date can be detected or from metadata.
    It can be a range or a simple date in isoformat.

def get_date(layer):

    date = None
    sign = '+'
    date_type = 1
    layer_dates = layer.get_layer_dates()
    # we index the first date!
    if layer_dates:
        sign = layer_dates[0][0]
        date = layer_dates[0][1]
        date_type = layer_dates[0][2]
    if date is None:
        date = layer.created
    # layer date > 2300 is invalid for sure
    # TODO put this logic in date miner
    if date.year > 2300:
        date = None
    if date_type == 0:
        date_type = "Detected"
    if date_type == 1:
        date_type = "From Metadata"
    return get_solr_date(date, (sign == '-')), date_type

def reset (self):

        # self.url is constructed by self.build_url() out of base_url
        # and (base_ref or parent) as absolute and normed url.
        # This the real url we use when checking so it also referred to
        # as 'real url'
        self.url = None
        # a splitted version of url for convenience
        self.urlparts = None
        # the scheme, host, port and anchor part of url
        self.scheme = self.host = self.port = self.anchor = None
        # the result message string and flag
        self.result = u""
        self.has_result = False
        # valid or not
        self.valid = True
        # list of warnings (without duplicates)
        self.warnings = []
        # list of infos
        self.info = []
        # content size
        self.size = -1
        # last modification time of content in HTTP-date format as specified in RFC2616 chapter 3.3.1
        self.modified = None
        # download time
        self.dltime = -1
        # check time
        self.checktime = 0
        # connection object
        self.url_connection = None
        # data of url content,  (data == None) means no data is available
        self.data = None
        # cache url is set by build_url() calling set_cache_url()
        self.cache_url = None
        # extern flags (is_extern, is_strict)
        self.extern = None
        # flag if the result should be cached
        self.caching = True
        # title is either the URL or parsed from content
        self.title = None
        # flag if content should be checked or not
        self.do_check_content = True
        # MIME content type
        self.content_type = u""
        # URLs seen through redirections
        self.aliases = []

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


Question: // ContextFromString reconstructs the Context encoded in a string

func ContextFromString(value string) (SpanContext, error) {
	var context SpanContext
	if value == "" {
		return emptyContext, errEmptyTracerStateString
	}
	parts := strings.Split(value, ":")
	if len(parts) != 4 {
		return emptyContext, errMalformedTracerStateString
	}
	var err error
	if context.traceID, err = TraceIDFromString(parts[0]); err != nil {
		return emptyContext, err
	}
	if context.spanID, err = SpanIDFromString(parts[1]); err != nil {
		return emptyContext, err
	}
	if context.parentID, err = SpanIDFromString(parts[2]); err != nil {
		return emptyContext, err
	}
	flags, err := strconv.ParseUint(parts[3], 10, 8)
	if err != nil {
		return emptyContext, err
	}
	context.flags = byte(flags)
	return context, nil
}

def _config_to_text(self):
        """"""
        r = u'' # unicode('',"UTF-8")
        for k in self._config:
            # if k == 'creation_date':
            #     r +=  k + ": " + self._config[k][0] + '\n'
            # else:
            #uk = unicode(k,"UTF-8")
            cosa = '\n        '.join(self._config[k]) + '\n'
            r += k + ": " + cosa
            #r += k + ": " + '\n        '.join(self._config[k]) + '\n'
        r += '\n'
        return r

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


Question:
Box is available for the calling user.

		:param resort.engine.execution.Context context:
		   Current execution context.

def available(self, context):

		if self.__available is None:
			avail = False
			name = context.resolve(self.__name)
			for box in self.__box_list():
				if box["name"] == name and box["version"] == "0":
					avail = True
					break
			self.__available = avail
		return self.__available

def get(self, sid):

        return BindingContext(self._version, service_sid=self._solution['service_sid'], sid=sid, )

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


Question:
This was ported, rewritten a bit and greatly simplified from the
same method in the old Calendar object we used to use.
TODO - it is only here temporarily, and we should continue trying to
kill it.

function(str, fmt) {

            if ((!str) || (!str.indexOf) || (str.indexOf("mm")==0)) return null;

            var y = 0;
            var m = -1;
            var d = 0;
            var a = str.split(/\W+/);
            var b = fmt.match(/%./g);
            var i = 0, j = 0;
            var hr = 0;
            var min = 0;
            var sec = 0;

            for (i = 0; i < a.length; ++i) {
                if (!a[i])
                    continue;
                switch (b[i]) {
                    case "%d":
                        d = parseInt(a[i], 10);
                        break;

                    case "%m":
                        m = parseInt(a[i], 10) - 1;
                        break;

                    case "%Y":
                    case "%y":
                        y = parseInt(a[i], 10);
                        (y < 100) && (y += (y > 29) ? 1900 : 2000);
                        break;

                    case "%H":
                        hr = parseInt(a[i], 10);
                        break;

                    case "%M":
                        min = parseInt(a[i], 10);
                        break;

                    case "%S":
                        sec = parseInt(a[i], 10);
                        break;

                    default:
                        break;
                }
            }
            if (y != 0 && m != -1 && d != 0) {
                var ourDate = new Date(y, m, d, hr, min, sec);
                return ourDate;
            } else {
                //this.logger.warn('unable to parse date "' + str + '" into "' + fmt + '"');
                return false;
            }
        }

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: // Lists SSL certificates

func (s *LoadBalancerService) ListSslCerts(p *ListSslCertsParams) (*ListSslCertsResponse, error) {
	resp, err := s.cs.newRequest("listSslCerts", p.toURLValues())
	if err != nil {
		return nil, err
	}

	var r ListSslCertsResponse
	if err := json.Unmarshal(resp, &r); err != nil {
		return nil, err
	}

	return &r, nil
}

func (s *Server) WithCertPool(pool *x509.CertPool) *Server {
	s.certPool = pool
	return s
}

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


Question:
Get Access token for the API
Call this when being redirected from shopify page ( to the $redirectUrl) after authentication

@throws SdkException if SharedSecret or ApiKey is missing in SDK configuration or request is not valid

@return string

public static function getAccessToken()
    {
        $config = ShopifySDK::$config;

        if(!isset($config['SharedSecret']) || !isset($config['ApiKey'])) {
            throw new SdkException("SharedSecret and ApiKey are required for getting access token. Please check SDK configuration!");
        }

        if(self::verifyShopifyRequest()) {
            $data = array(
                'client_id' => $config['ApiKey'],
                'client_secret' => $config['SharedSecret'],
                'code' => $_GET['code'],
            );

            $response = HttpRequestJson::post($config['AdminUrl'] . 'oauth/access_token', $data);

            return isset($response['access_token']) ? $response['access_token'] : null;
        } else {
            throw new SdkException("This request is not initiated from a valid shopify shop!");
        }
    }

def response_cookies(self):

        try:
            ret = {}
            for cookie_base_uris in self.response.cookies._cookies.values():
                for cookies in cookie_base_uris.values():
                    for cookie in cookies.keys():
                        ret[cookie] = cookies[cookie].value
            return ret
        except Exception as e:
            self.error = ApiError(
                "Exception in making Request with:: %s\n%s" % (
                    e_, traceback.format_exc()))
            raise Exception(self.error)

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


Question:
Get GIF by ID Endpoint
 Returns a GIF given that GIF's unique ID
 @param api_key Giphy API Key.
 @param gif_id Filters results by specified GIF ID.
 @param [Hash] opts the optional parameters
 @return [InlineResponse2001]

def gifs_gif_id_get(api_key, gif_id, opts = {})
      data, _status_code, _headers = gifs_gif_id_get_with_http_info(api_key, gif_id, opts)
      return data
    end

func Identity(cfg *config.Config) fx.Option {
	// PeerID

	cid := cfg.Identity.PeerID
	if cid == "" {
		return fx.Error(errors.New("identity was not set in config (was 'ipfs init' run?)"))
	}
	if len(cid) == 0 {
		return fx.Error(errors.New("no peer ID in config! (was 'ipfs init' run?)"))
	}

	id, err := peer.IDB58Decode(cid)
	if err != nil {
		return fx.Error(fmt.Errorf("peer ID invalid: %s", err))
	}

	// Private Key

	if cfg.Identity.PrivKey == "" {
		return fx.Options( // No PK (usually in tests)
			fx.Provide(PeerID(id)),
			fx.Provide(pstoremem.NewPeerstore),
		)
	}

	sk, err := cfg.Identity.DecodePrivateKey("passphrase todo!")
	if err != nil {
		return fx.Error(err)
	}

	return fx.Options( // Full identity
		fx.Provide(PeerID(id)),
		fx.Provide(PrivateKey(sk)),
		fx.Provide(pstoremem.NewPeerstore),

		fx.Invoke(libp2p.PstoreAddSelfKeys),
	)
}

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


Question:
Retrieve gems which differ from
 rubygems.org/other upstream sources

def patched
      vendored.collect do |dep|
        # TODO: right now just handling git based alternate sources,
        # should be able to handle other types bundler supports
        # (path and alternate rubygems src)
        next unless dep.source.is_a?(Bundler::Source::Git)
        src = dep.source

        # retrieve gem
        gem = if src.version
                Polisher::Gem.new(:name => dep.name, :version => src.version)
              else
                Polisher::Gem.retrieve(dep.name)
              end

        # retrieve dep
        git = Polisher::Git::Repo.new :url => src.uri
        git.clone unless git.cloned?
        git.checkout src.ref if src.ref

        # diff gem against git
        gem.diff(git.path)
      end.compact!
    end

def dump_soap_request(service_url, request_xml)
      return unless @soap_dump
      %w{email password developerToken authToken clientEmail}.each do |tag|
        request_xml = request_xml.gsub(/<#{tag}([^>]*)>.*<\/#{tag}>/, "<#{tag}\\1>***censured***</#{tag}>")
      end
      str = ""
      str << "<!-- Post to '#{service_url}' -->\n"
      str << xml_to_s(request_xml) << "\n"
      dump(service_url, "req", str)
    end

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


Question:
// GetParentIDOf returns the ID (if any) of the parent for the child work item
// with respect to the link type in the given link list.

func (list WorkItemLinkList) GetParentIDOf(childID uuid.UUID, linkTypeID uuid.UUID) uuid.UUID {
	for _, l := range list {
		if l.TargetID == childID && l.LinkTypeID == linkTypeID {
			return l.SourceID
		}
	}
	return uuid.Nil
}

void findNodes(List<RBBINode> dest, int kind) {
        if (fType == kind) {
            dest.add(this);
        }
        if (fLeftChild != null) {
            fLeftChild.findNodes(dest, kind);
        }
        if (fRightChild != null) {
            fRightChild.findNodes(dest, kind);
        }
    }

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


Question: // SophieWriter interface

func (s String) WriteTo(w Writer) error {
	return ByteSlice(s).WriteTo(w)
}

public function run(InputInterface $input, OutputInterface $output)
    {
        $this->setInput($input);
        $this->setOutput($output);

        return parent::run($input, $output);
    }

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


Question:
Checks whether the parameter is a subset of this RoaringBitmap or not
@param subset the potential subset
@return true if the parameter is a subset of this RoaringBitmap

public boolean contains(ImmutableRoaringBitmap subset) {
    if(subset.getCardinality() > getCardinality()) {
      return false;
    }
    final int length1 = this.highLowContainer.size();
    final int length2 = subset.highLowContainer.size();
    int pos1 = 0, pos2 = 0;
    while (pos1 < length1 && pos2 < length2) {
      final short s1 = this.highLowContainer.getKeyAtIndex(pos1);
      final short s2 = subset.highLowContainer.getKeyAtIndex(pos2);
      if (s1 == s2) {
        MappeableContainer c1 = this.highLowContainer.getContainerAtIndex(pos1);
        MappeableContainer c2 = subset.highLowContainer.getContainerAtIndex(pos2);
        if(!c1.contains(c2)) {
          return false;
        }
        ++pos1;
        ++pos2;
      } else if (compareUnsigned(s1, s2) > 0) {
        return false;
      } else {
        pos1 = subset.highLowContainer.advanceUntil(s2, pos1);
      }
    }
    return pos2 == length2;
  }

def datalab(line, cell=None):

  parser = google.datalab.utils.commands.CommandParser(
      prog='%datalab',
      description="""
Execute operations that apply to multiple Datalab APIs.

Use "%datalab <command> -h" for help on a specific command.
""")

  config_parser = parser.subcommand(
      'config', help='List or set API-specific configurations.')
  config_sub_commands = config_parser.add_subparsers(dest='command')

  # %%datalab config list
  config_list_parser = config_sub_commands.add_parser(
      'list', help='List configurations')
  config_list_parser.set_defaults(func=_config_list_fn)

  # %%datalab config set -n <NAME> -v <VALUE>
  config_set_parser = config_sub_commands.add_parser(
      'set', help='Set configurations')
  config_set_parser.add_argument(
      '-n', '--name',
      help='The name of the configuration value', required=True)
  config_set_parser.add_argument(
      '-v', '--value', help='The value to set', required=True)
  config_set_parser.set_defaults(func=_config_set_fn)

  project_parser = parser.subcommand(
      'project', help='Get or set the default project ID')
  project_sub_commands = project_parser.add_subparsers(dest='command')

  # %%datalab project get
  project_get_parser = project_sub_commands.add_parser(
      'get', help='Get the default project ID')
  project_get_parser.set_defaults(func=_project_get_fn)

  # %%datalab project set -p <PROJECT_ID>
  project_set_parser = project_sub_commands.add_parser(
      'set', help='Set the default project ID')
  project_set_parser.add_argument(
      '-p', '--project', help='The default project ID', required=True)
  project_set_parser.set_defaults(func=_project_set_fn)

  return google.datalab.utils.commands.handle_magic_line(line, cell, parser)

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


Question:
Check whether file uploading is new.
@return bool

public function getIsNew ()
		{
			if ($this->_isNew == false)
				return false;

			for ($i = 1; $i <= $this->_params[ 'totalChunks' ]; $i++)
			{
				if ($this->chunkIsUploaded($i))
				{
					$this->_isNew = false;

					return false;
				}
			}

			$this->_isNew = true;

			return true;
		}

public function output($image_type = null, $quality = null)
    {
        $image_type = $image_type ?: $this->source_type;

        header('Content-Type: ' . image_type_to_mime_type($image_type));

        $this->save(null, $image_type, $quality);
    }

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


Question:
// Rate creates a new ugen at a specific rate.
// If rate is an unsupported value this method will cause a runtime panic.

func (f Formant) Rate(rate int8) Input {
	CheckRate(rate)
	(&f).defaults()
	return NewInput("Formant", rate, 0, 1, f.FundFreq, f.FormantFreq, f.BWFreq)
}

def chk_genes(self, study, pop, assoc=None):
        """"""
        if len(pop) < len(study):
            exit("\nERROR: The study file contains more elements than the population file. "
                 "Please check that the study file is a subset of the population file.\n")
        # check the fraction of genomic ids that overlap between study and population
        overlap = self.get_overlap(study, pop)
        if overlap < 0.95:
            sys.stderr.write("\nWARNING: only {} fraction of genes/proteins in study are found in "
                             "the population  background.\n\n".format(overlap))
        if overlap <= self.args.min_overlap:
            exit("\nERROR: only {} of genes/proteins in the study are found in the "
                 "background population. Please check.\n".format(overlap))
        # Population and associations
        if assoc is not None and pop.isdisjoint(assoc.keys()):
            if self.objanno.name == 'gene2go':
                err = ('**FATAL: NO POPULATION ITEMS SEEN IN THE NCBI gene2go ANNOTATIONS '
                       'FOR taxid({T}). TRY: --taxid=<taxid number>')
                exit(err.format(T=next(iter(self.objanno.taxid2asscs.keys()))))
            else:
                exit('**FATAL: NO POPULATION ITEMS SEEN IN THE ANNOTATIONS')

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


Question: Return default list of env variables with their assigned value, if any.

function _getFileContents(values) {
  const env = getDefaultSlateEnv();

  for (const key in values) {
    if (values.hasOwnProperty(key) && env.hasOwnProperty(key)) {
      env[key] = values[key];
    }
  }

  return Object.entries(env)
    .map((keyValues) => {
      return `${keyValues.join('=')}\r\n`;
    })
    .join('\r\n\r\n');
}

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

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


Question:
Register function.

@param ExpressionLanguage $expressionLanguage Expression language

public function registerFunction(ExpressionLanguage $expressionLanguage)
    {
        $expressionLanguage->register('m', function ($ids) {
            return sprintf('(purchasable.manufacturer.id in [%1$s])', $ids);
        }, function ($arguments, $ids) {
            $ids = explode(',', $ids);
            $purchasable = $arguments['purchasable'];
            $manufacturer = $purchasable->getManufacturer();

            if (!$manufacturer instanceof ManufacturerInterface) {
                return false;
            }

            return in_array(
                $manufacturer->getId(),
                $ids
            );
        });
    }

private void evaluateExpressions() throws JspException {
        if (valueEL != null) {
            value = (Date) ExpressionEvaluatorManager.evaluate(
                    "value", valueEL, Date.class, this, pageContext);
        }

        if (typeEL != null) {
            type = (String) ExpressionEvaluatorManager.evaluate(
                    "type", typeEL, String.class, this, pageContext);
        }
    }

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


Question: // GetTitle returns the Title field if it's non-nil, zero value otherwise.

func (i *IssueRequest) GetTitle() string {
	if i == nil || i.Title == nil {
		return ""
	}
	return *i.Title
}

public String toKey() {
        return (tag == null ? EMPTY_STRING : tag) + KEY_DELIMITER + (indicator == null ? EMPTY_STRING : indicator) +
                KEY_DELIMITER + subfieldIds;
    }

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