Question:
Rewind the Iterator to the first element
@link http://php.net/manual/en/iterator.rewind.php
@throws \Exception
@return void Any returned value is ignored.

public function rewind()
    {
        $uri = $this->xmlFileUri;

        if ($this->options["utf8Filter"]) {
            $uri = "php://filter/read=xmlutf8/resource=" . $uri;
        }

        if (!$this->reader
            ->open(
                $uri,
                $this->options["encoding"],
                $this->options["readerOptions"]
            )
        ) {
            throw new \Exception("$this->xmlFileUri cannot be opened");
        }

        // move to the first element
        while ($this->reader->read() && $this->reader->name !== $this->delimiterTagName) {
            // intentionally empty
        }
    }

protected function queue($key) {
        $queue_name=isset($this->options['queue_name'])?$this->options['queue_name']:'think_queue';
        $value  =  F($queue_name);
        if(!$value) {
            $value   =  array();
        }
        // 进列
        if(false===array_search($key, $value)) array_push($value,$key);
        if(count($value) > $this->options['length']) {
            // 出列
            $key =  array_shift($value);
            // 删除缓存
            $this->rm($key);
            if (APP_DEBUG) {
                    //调试模式下记录出队次数
                        $counter = Think::instance('SaeCounter');
                        if ($counter->exists($queue_name.'_out_times'))
                            $counter->incr($queue_name.'_out_times');
                        else
                            $counter->create($queue_name.'_out_times', 1);
           }
        }
        return F($queue_name,$value);
    }

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


Question: Returns useful information about the Down::ChunkedIO object.

def inspect
      string  = String.new
      string << "#<#{self.class.name}"
      string << " chunks=#{@chunks.inspect}"
      string << " size=#{size.inspect}"
      string << " encoding=#{encoding.inspect}"
      string << " data=#{data.inspect}"
      string << " on_close=#{@on_close.inspect}"
      string << " rewindable=#{@rewindable.inspect}"
      string << " (closed)" if closed?
      string << ">"
    end

def parameter(name, params = Hash.new, &block)
      # pupu :autocompleter, type: "request"
      # @pupu.params: { type: "request" }

      # pupu :mootools, more: true
      # @pupu.params: { more: true }
      if @pupu.params.key?(name)
        block.call(@pupu.params[name])
      end
    end

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


Question:
Constructs a random filename with the given prefix and
a random part generated from hex characters.

@param prefix
the prefix to the filename to be constructed
@return the generated random filename with the given prefix

public static String getRandomFilename(final String prefix) {
		final Random rnd = new Random();
		final StringBuilder stringBuilder = new StringBuilder(prefix);

		for (int i = 0; i < RANDOM_FILE_NAME_LENGTH; i++) {
			stringBuilder.append(ALPHABET[rnd.nextInt(ALPHABET.length)]);
		}

		return stringBuilder.toString();
	}

def download(self, uuid, url, forced_file_name=None,
                 progress_bar=True, chunk_size=256,
                 directory=None, overwrite=False):

        self.last_req_time = None
        url = self.get_full_url(url)
        self.log.debug("download url : " + url)
        # Building request
        request = urllib2.Request(url)
        # request.add_header('Content-Type', 'application/json; charset=UTF-8')
        request.add_header('Accept', 'application/json,*/*;charset=UTF-8')
        # request start
        starttime = datetime.datetime.now()
        # doRequest
        resultq = urllib2.urlopen(request)
        code = resultq.getcode()
        file_name = uuid
        self.log.debug("ret code : '" + str(code) + "'")
        if code == 200:
            content_lenth = resultq.info().getheader('Content-Length')
            if not content_lenth:
                msg = "No content lengh header found !"
                self.log.debug(msg)
                progress_bar = False
            else:
                file_size = int(content_lenth.strip())
            if forced_file_name:
                file_name = forced_file_name
            else:
                content_dispo = resultq.info().getheader('Content-disposition')
                if content_dispo:
                    content_dispo = content_dispo.strip()
                    file_name = extract_file_name(content_dispo)
            if directory:
                if os.path.isdir(directory):
                    file_name = directory + "/" + file_name
            if os.path.isfile(file_name):
                if not overwrite:
                    cpt = 1
                    while 1:
                        if not os.path.isfile(file_name + "." + str(cpt)):
                            file_name += "." + str(cpt)
                            break
                        cpt += 1
                else:
                    self.log.warn("'%s' already exists. It was overwriten.",
                                  file_name)
            stream = None
            pbar = None
            if progress_bar:
                widgets = [FileTransferSpeed(), ' <<<', Bar(), '>>> ',
                           Percentage(), ' ', ETA()]
                pbar = ProgressBar(widgets=widgets, maxval=file_size)
                stream = FileWithCallback(file_name, 'w', pbar.update,
                                          file_size, file_name)
                pbar.start()
            else:
                stream = file(file_name, 'w')
            while 1:
                chunk = resultq.read(chunk_size)
                if not chunk:
                    break
                stream.write(chunk)
            stream.flush()
            stream.close()
            if pbar:
                pbar.finish()
        # request end
        endtime = datetime.datetime.now()
        self.last_req_time = str(endtime - starttime)
        self.log.debug("download url : %(url)s : request time : %(time)s",
                       {"url": url,
                        "time": self.last_req_time})
        return (file_name, self.last_req_time)

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


Question: // Add adds other to s and updates s.

func (s *CursorStats) Add(other CursorStats) {
	s.ScannedValues += other.ScannedValues
	s.ScannedBytes += other.ScannedBytes
}

func (d *SerialDevice) merge(dev SerialDevice) bool {
	changed := false
	if d.Port != dev.Port {
		changed = true
		d.Port = dev.Port
	}
	if d.SerialNumber != dev.SerialNumber {
		changed = true
		d.SerialNumber = dev.SerialNumber
	}
	if d.ProductID != dev.ProductID {
		changed = true
		d.ProductID = dev.ProductID
	}
	if d.VendorID != dev.VendorID {
		changed = true
		d.VendorID = dev.VendorID
	}

	// if d.Serial != dev.Serial {
	// 	d.Serial = dev.Serial
	// }
	return changed
}

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


Question:
Reruns the workflow from a specific task

@param workflowId           the id of the workflow
@param rerunWorkflowRequest the request containing the task to rerun from
@return the id of the workflow

public String rerunWorkflow(String workflowId, RerunWorkflowRequest rerunWorkflowRequest) {
        Preconditions.checkArgument(StringUtils.isNotBlank(workflowId), "workflow id cannot be blank");
        Preconditions.checkNotNull(rerunWorkflowRequest, "RerunWorkflowRequest cannot be null");

        return postForEntity("workflow/{workflowId}/rerun", rerunWorkflowRequest, null, String.class, workflowId);
    }

public function callback()
    {
        //Salesforce sends us an authorization code as part of the Web Server OAuth Authentication Flow
        $code = $this->input->get('code');

        $stateOptions = json_decode(urldecode($this->input->get('state')), true);

        //Store instance URL
        $loginURL = $stateOptions['loginUrl'];

        // Store user options so they can be used later
        $this->stateRepo->put($stateOptions);

        $tokenURL = $loginURL.'/services/oauth2/token';

        $jsonResponse = $this->httpClient->request('post', $tokenURL, [
            'form_params' => [
                'code'          => $code,
                'grant_type'    => 'authorization_code',
                'client_id'     => $this->credentials['consumerKey'],
                'client_secret' => $this->credentials['consumerSecret'],
                'redirect_uri'  => $this->credentials['callbackURI'],
            ],
        ]);

        // Response returns an json of access_token, instance_url, id, issued_at, and signature.
        $response = json_decode($jsonResponse->getBody(), true);
        $this->handleAuthenticationErrors($response);

        // Encrypt token and store token in storage.
        $this->tokenRepo->put($response);

        if (isset($response['refresh_token'])) {
            $this->refreshTokenRepo->put($response['refresh_token']);
        }

        $this->storeVersion();
        $this->storeResources();

        // Return settings
        return $stateOptions;
    }

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


Question:
@param string[] $imageSrcs
@param bool $returnAll

@return LocallyStoredImage[]

private function getLocallyStoredImages($imageSrcs, bool $returnAll = false): array {
        return ImageUtils::storeImagesToLocalFile($imageSrcs, $returnAll, $this->config());
    }

protected function getAttributes()
    {
        $request = $this->hasLaravel() === true ? $this->laravel['request'] : Request::capture();
        $rows = [
            'ip' => $request->ip(),
            'ips' => $request->ips(),
            'query' => $request->query(),
            'request' => $request->all(),
            'file' => $request->file(),
            'cookies' => $request->cookie(),
            'format' => $request->format(),
            'path' => $request->path(),
            'server' => $request->server(),
            // 'headers' => $request->header(),
        ];

        return compact('rows');
    }

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


Question:
Copy all values of scope into the class SinonGlobals
    Args:
        scope (eg. locals() or globals())
    Return:
        SinonGlobals instance

def init(scope):

    class SinonGlobals(object): #pylint: disable=too-few-public-methods
        """
        A fully empty class
        External can push the whole `scope` into this class through global function init()
        """
        pass

    global CPSCOPE #pylint: disable=global-statement
    CPSCOPE = SinonGlobals()
    funcs = [obj for obj in scope.values() if isinstance(obj, FunctionType)]
    for func in funcs:
        setattr(CPSCOPE, func.__name__, func)
    return CPSCOPE

def __init(self):

        params = {
            "f" : "json",
        }
        json_dict = self._get(self._url, params,
                                 securityHandler=self._securityHandler,
                                 proxy_url=self._proxy_url,
                                 proxy_port=self._proxy_port)
        self._json_dict = json_dict
        self._json = json.dumps(self._json_dict)
        attributes = [attr for attr in dir(self)
                      if not attr.startswith('__') and \
                      not attr.startswith('_')]
        for k,v in json_dict.items():
            if k in attributes:
                if k == "versions" and json_dict[k]:
                    self._versions = []
                    for version in v:
                        self._versions.append(
                            Version(url=self._url + "/versions/%s" % version,
                                    securityHandler=self._securityHandler,
                                    proxy_url=self._proxy_url,
                                    proxy_port=self._proxy_port,
                                    initialize=False))
                elif k == "replicas" and json_dict[k]:
                    self._replicas = []
                    for version in v:
                        self._replicas.append(
                            Replica(url=self._url + "/replicas/%s" % version,
                                    securityHandler=self._securityHandler,
                                    proxy_url=self._proxy_url,
                                    proxy_port=self._proxy_port,
                                    initialize=False))
                else:
                    setattr(self, "_"+ k, v)
            else:
                print (k, " - attribute not implemented for GeoData Service")

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


Question:
/*
AssertEqual asserts if expected result is same as returned result.
*/

func AssertEqual(expected interface{}, result interface{}) {
	AssertType(expected, result)
	if expected == nil && result == nil {
		return
	}
	switch result.(type) {
	case string, int, error, bool:
		if expected != result {
			panic(fmt.Sprintf("Error: [] Mismatched Values\nExpected value: %v\nResult: %v", expected, result))
		}
	default:
		panic("Error: AssertEqual doesn't handles this type yet.")
	}

}

public static void main(String[] args) {
    System.out.println("Hello Stats World");
    System.out.println("Default Tags: " + tagger.empty());
    System.out.println("Current Tags: " + tagger.getCurrentTagContext());
    TagContext tags1 = tagger.emptyBuilder().put(K1, V1).put(K2, V2).build();
    try (Scope scopedTagCtx1 = tagger.withTagContext(tags1)) {
      System.out.println("  Current Tags: " + tagger.getCurrentTagContext());
      System.out.println(
          "  Current == Default + tags1: " + tagger.getCurrentTagContext().equals(tags1));
      TagContext tags2 = tagger.toBuilder(tags1).put(K3, V3).put(K4, V4).build();
      try (Scope scopedTagCtx2 = tagger.withTagContext(tags2)) {
        System.out.println("    Current Tags: " + tagger.getCurrentTagContext());
        System.out.println(
            "    Current == Default + tags1 + tags2: "
                + tagger.getCurrentTagContext().equals(tags2));
        statsRecorder.newMeasureMap().put(M1, 0.2).put(M2, 0.4).record();
      }
    }
    System.out.println(
        "Current == Default: " + tagger.getCurrentTagContext().equals(tagger.empty()));
  }

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


Question:
create a new radio input

@param array $options
@return Input

public function radio($options = []){
        if (is_string($options)) {
            $options = ['class' => $options];
        }elseif(is_bool($options)){
            $options = [
                'checked' => 'checked'
            ];
        }

        if (!Arr::has($options, 'type')) {
            Arr::set($options, 'type', 'radio');
        }

        return $this->input($options);
    }

protected function prepareWidgetOptions($arrIds, $objAttribute)
    {
        $arrOptions = $objAttribute->getFilterOptions(
            ($this->get('onlypossible') ? $arrIds : null),
            (bool) $this->get('onlyused')
        );

        // Remove empty values from list.
        foreach ($arrOptions as $mixKeyOption => $mixOption) {
            // Remove html/php tags.
            $mixOption = \strip_tags($mixOption);
            $mixOption = \trim($mixOption);

            if ($mixOption === '' || $mixOption === null) {
                unset($arrOptions[$mixKeyOption]);
            }
        }

        return $arrOptions;
    }

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


Question:
Creates a basic graph out of an incidence matrix.

    The matrix has to be a list of rows of values
    representing an incidence matrix.
    The values can be anything: bool, int, float, as long
    as they can evaluate to True or False.

def graph_from_incidence_matrix(matrix, node_prefix='', directed=False):

    if directed:
        graph = Dot(graph_type='digraph')
    else:
        graph = Dot(graph_type='graph')

    for row in matrix:
        nodes = []
        c = 1

        for node in row:
            if node:
                nodes.append(c * node)
            c += 1

        nodes.sort()

        if len(nodes) == 2:
            graph.add_edge(
                Edge(
                    node_prefix + abs(nodes[0]),
                    node_prefix + nodes[1]))

    if not directed:
        graph.set_simplify(True)

    return graph

private void visit(final ObjectGraphNode currentNode) {
		Object currentValue = currentNode.getValue();

		if (currentValue == null
				|| (currentValue instanceof java.lang.ref.SoftReference)
				|| currentNode.isPrimitive() || currentNode.isSimpleType()) {
			return;
		}

		if (isObjectVisited(currentNode)) {
			ObjectGraphNode ref = visitedNodes.get(currentValue);
			currentNode.setRefNode(ref);
			return;
		}

		markObjectVisited(currentNode);

		if (currentValue instanceof List) {
			// ArrayList's elementData is marked transient, and others may be as well, so we have to do this ourselves.
			visitList(currentNode);
		} else if (currentValue instanceof Map) {
			// HashMap's table is marked transient, and others may be as well, so we have to do this ourselves.
			visitMap(currentNode);
		} else if (currentValue instanceof ComponentModel) {
			// Special case for ComponentModel, so we can figure out if any fields are overridden
			visitComponentModel(currentNode);
		} else if (currentValue instanceof Field) {
			visitComplexType(currentNode);
			summariseNode(currentNode);
		} else if (currentValue.getClass().isArray()) {
			visitArray(currentNode);
		} else {
			visitComplexType(currentNode);
		}
	}

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


Question:
Establish the transient state of this ObjectStore.

@param objectManagerState with which the ObjectStore is registered.
@throws ObjectManagerException

public synchronized void open(ObjectManagerState objectManagerState)
                    throws ObjectManagerException {
        final String methodName = "open";
        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.entry(this, cclass, methodName, objectManagerState);

        super.open(objectManagerState);

        byteArrayOutputStream = new ObjectManagerByteArrayOutputStream(pageSize);

        // Now look at the file and initialise the ObjectStore.
        // Read the header, to find the directory and free space map.
        try {
            int versionRead = storeFile.readInt();

            // Read a known number of signature charaters.
            char[] signatureRead = new char[signature.length()];
            for (int i = 0; i < signature.length(); i++)
                signatureRead[i] = storeFile.readChar();
            if (!(new String(signatureRead).equals(signature))) {
                if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                    trace.exit(this,
                               cclass,
                               "open"
                               , new Object[] { signatureRead });
                throw new InvalidStoreSignatureException(this,
                                                         new String(signatureRead), signature);
            } // if(!(new String(signatureRead).equals(signature))).

            long objectStoreIdentifierRead = storeFile.readLong();
            if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
                trace.debug(this,
                            cclass,
                            methodName,
                            new Object[] { new Integer(versionRead),
                                          new String(signatureRead),
                                          new Long(objectStoreIdentifierRead)
                            }
                                );
            // Use the saved value if we are a new store.
            if (objectStoreIdentifier == IDENTIFIER_NOT_SET)
                objectStoreIdentifier = (int) objectStoreIdentifierRead;

            // The byte address of the directory root.
            long directoryRootByteAddress = storeFile.readLong();
            // The current number of bytes in the directory root.
            long directoryRootLength = storeFile.readLong();
            // The minimumNodeSize of the directory BTree.
            int directoryMinimumNodeSize = storeFile.readInt();
            long freeSpaceStoreAreaByteAddress = storeFile.readLong();
            long freeSpaceStoreAreaLength = storeFile.readLong();
            // The actual number of free space entries since we have to overestimate the space we need to store them.
            long freeSpaceCount = storeFile.readLong();

            sequenceNumber = storeFile.readLong();
            // This is the length we assume we have written.
            storeFileSizeUsed = storeFile.readLong();
            // Administered limits on store file size.
            minimumStoreFileSize = storeFile.readLong();
            maximumStoreFileSize = storeFile.readLong();
            cachedManagedObjectsSize = storeFile.readInt();

            storeFileSizeAllocated = storeFile.length();

            if (Tracing.isAnyTracingEnabled() && trace.isDebugEnabled())
                trace.debug(this,
                            cclass,
                            methodName,
                            new Object[] { new Long(directoryRootByteAddress)
                                          , new Long(directoryRootLength)
                                          , new Integer(directoryMinimumNodeSize)
                                          , new Long(freeSpaceStoreAreaByteAddress)
                                          , new Long(freeSpaceStoreAreaLength)
                                          , new Long(freeSpaceCount)
                                          , new Long(sequenceNumber)
                                          , new Long(storeFileSizeUsed)
                                          , new Long(minimumStoreFileSize)
                                          , new Long(maximumStoreFileSize)
                                          , new Integer(cachedManagedObjectsSize)
                                          , new Long(storeFileSizeAllocated)
                            }
                                );

            // Are we interested in what's already on the disk?
            if (storeStrategy == STRATEGY_KEEP_ALWAYS
                || storeStrategy == STRATEGY_SAVE_ONLY_ON_SHUTDOWN) {
                // Create the array that locks recently used ManagedObjects into memory.
                cachedManagedObjects = new java.lang.ref.SoftReference[cachedManagedObjectsSize];
                directory = new Directory(directoryMinimumNodeSize,
                                          directoryRootByteAddress,
                                          directoryRootLength);
                if (freeSpaceStoreAreaByteAddress != 0)
                    freeSpaceStoreArea = directory.makeStoreArea(freeSpaceIdentifier,
                                                                 freeSpaceStoreAreaByteAddress,
                                                                 freeSpaceStoreAreaLength);
                readFreeSpaceMap(freeSpaceCount);

            } else if (storeStrategy == STRATEGY_KEEP_UNTIL_NEXT_OPEN) {
                if (Runtime.getRuntime().totalMemory() < Integer.MAX_VALUE)
                    reservedSize = new Atomic32BitLong(0);
                else
                    reservedSize = new Atomic64BitLong(0);
                clear();
            } // if (storeStrategy...

        } catch (java.io.EOFException exception) {
            // The file is empty or did not exist.
            // No FFDC Code Needed, this may be first use of a store.
            if (Tracing.isAnyTracingEnabled() && trace.isEventEnabled())
                trace.event(this,
                            cclass,
                            methodName,
                            exception);

            if (objectManagerState.getObjectManagerStateState() == ObjectManagerState.stateReplayingLog) {
                ObjectManager.ffdc.processException(this, cclass, methodName, exception, "1:241:1.35");

                if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                    trace.exit(this, cclass, methodName, new Object[] { "EndOfFile:244" });
                throw new PermanentIOException(this,
                                               exception);
            } // if.

            // Set initial values.
            minimumStoreFileSize = 0;
            maximumStoreFileSize = Long.MAX_VALUE;
            cachedManagedObjectsSize = initialCachedManagedObjectsSize;
            cachedManagedObjects = new java.lang.ref.SoftReference[cachedManagedObjectsSize];

            directory = new Directory(initialDirectoryMinimumNodeSize, 0, 0);
            freeSpaceByAddressHead = null;
            freeSpaceByLength = new java.util.TreeSet(new AbstractSingleFileObjectStore.LengthComparator());
            freeSpaceStoreArea = null;

            // Sequence numbers 0-200 are reserved.
            sequenceNumber = initialSequenceNumber;

            // Allow for two headers to be written at the front of the file.
            storeFileSizeUsed = pageSize * 2;
            storeFileSizeAllocated = storeFileSizeUsed;
            // allocateSpace() is now initialized,

            // Make sure there is a valid header on the disk, in case we fail after this.
            // It is fatal for the ObjectManager to fail after we extend the file system
            // in setAllocationAllowed() without writing a header as the header will contain zeros.
            writeHeader();
            force();

        } catch (java.io.IOException exception) {
            // No FFDC Code Needed.
            ObjectManager.ffdc.processException(this, cclass, methodName, exception, "1:276:1.35");

            if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
                trace.exit(this,
                           cclass,
                           methodName);
            throw new PermanentIOException(this,
                                           exception);
        } //  catch (java.io.IOException exception).

        directoryReservedSize = directory.spaceRequired();
        if (Runtime.getRuntime().totalMemory() < Integer.MAX_VALUE)
            reservedSize = new Atomic32BitLong(0);
        else
            reservedSize = new Atomic64BitLong(0);

        // Assume we have already reserved enough space to completely rewrite the directory so any number of
        // node splits or deletions are already accounted for. We now need to say how much space is needed
        // each time an object is added or replaced in the store. This will include enough space to also
        // complete its removal.
        addSpaceOverhead = 4 + 1 // Space for a new Node, numberOfKeys + flagIsLeaf/flagIsNotLeaf.
                           + 5 * 8 // Space for a new Entry, Identifier,address,length,childAddress,childLength.
                           + 2 * 8 // An entry in the free space map for the node when it is rewritten.
                           + 2 * 8; // An entry in the free space map when the ManagedObject is removed.
        // For debugging add guardBytes before and after the Node metadata and  before and after the payload.
        if (useGuardBytes)
            addSpaceOverhead = addSpaceOverhead + 2 * 2 * guardBytesLength;

        setAllocationAllowed();

        if (Tracing.isAnyTracingEnabled() && trace.isEntryEnabled())
            trace.exit(this,
                       cclass,
                       methodName);
    }

func (c *BootstrapConfig) ConfigureArgs(args *BootstrapTplArgs) error {

	// Attempt to setup sink(s) from high-level config. Note the args are passed
	// by ref and modified in place.
	if err := c.generateStatsSinks(args); err != nil {
		return err
	}

	if c.StatsConfigJSON != "" {
		// StatsConfig overridden explicitly
		args.StatsConfigJSON = c.StatsConfigJSON
	} else {
		// Attempt to setup tags from high-level config. Note the args are passed by
		// ref and modified in place.
		if err := c.generateStatsConfig(args); err != nil {
			return err
		}
	}

	if c.StaticClustersJSON != "" {
		args.StaticClustersJSON = c.StaticClustersJSON
	}
	if c.StaticListenersJSON != "" {
		args.StaticListenersJSON = c.StaticListenersJSON
	}
	// Setup prometheus if needed. This MUST happen after the Static*JSON is set above
	if c.PrometheusBindAddr != "" {
		if err := c.generatePrometheusConfig(args); err != nil {
			return err
		}
	}

	if c.TracingConfigJSON != "" {
		args.TracingConfigJSON = c.TracingConfigJSON
	}

	if c.StatsFlushInterval != "" {
		args.StatsFlushInterval = c.StatsFlushInterval
	}

	return nil
}

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


Question:
Declares an association between this object and a Customer object.

@param                  Customer $v
@return UserCustomerRelation The current object (for fluent API support)
@throws PropelException

public function setCustomer(Customer $v = null)
    {
        if ($v === null) {
            $this->setCustomerId(NULL);
        } else {
            $this->setCustomerId($v->getId());
        }

        $this->aCustomer = $v;

        // Add binding for other direction of this n:n relationship.
        // If this object has already been added to the Customer object, it will not be re-added.
        if ($v !== null) {
            $v->addUserCustomerRelation($this);
        }

        return $this;
    }

protected function parseSinglePrimaryData(array $data)
    {
        $result = null;

        list ($type, $idx) = $this->parseTypeAndId($data);
        if (empty($type) === true || is_string($type) === false) {
            $this->errors->addDataTypeError('Element should be non empty string.');
        }

        if ($idx !== null && is_string($idx) === false) {
            $this->errors->addDataIdError('Optional element should be non empty string.');
        }

        $attributes = $this->getArrayValue($data, DocumentInterface::KEYWORD_ATTRIBUTES, []);

        $relationshipsData = $this->getArrayValue($data, DocumentInterface::KEYWORD_RELATIONSHIPS, []);
        $relationships     = $this->parseRelationships($relationshipsData);

        if ($this->errors->count() <= 0) {
            $result = new ResourceObject($type, $idx, $attributes, $relationships);
        }

        return $result;
    }

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


Question:
缓存命中率计算

@param string $name  计算KEY
@param int    $hit   命中数
@param int    $total 总数

public function counting($name, $hit, $total = null)
    {
        if (! \is_string($name) || empty($name)) {
            return;
        }

        $cid = Coroutine::tid();
        if (! isset($this->countings[$cid][$name])) {
            $this->countings[$cid][$name] = ['hit' => 0, 'total' => 0];
        }
        $this->countings[$cid][$name]['hit'] += (int)$hit;
        if ($total !== null) {
            $this->countings[$cid][$name]['total'] += (int)$total;
        }
    }

protected function request($method, $command, $data = null)
    {
        if (!$this->isAttached()) {
            throw new NotAttachedException('No token');
        }
        $url = $this->getRequestUrl($command, !$data || $method === 'POST' ? [] : $data);

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Accept: application/json', 'Authorization: Bearer '. $this->getSessionID()]);

        if ($method === 'POST' && !empty($data)) {
            $post = is_string($data) ? $data : http_build_query($data);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
        }
        $response = curl_exec($ch);

        if (curl_errno($ch) != 0) {
            $message = 'Server request failed: ' . curl_error($ch);
            throw new Exception($message);
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        list($contentType) = explode(';', curl_getinfo($ch, CURLINFO_CONTENT_TYPE));

        if ($contentType != 'application/json') {
            $message = 'Expected application/json response, got ' . $contentType;
            throw new Exception($message);
        }
        $data = json_decode($response, true);

        if ($httpCode == 403) {
            $this->clearToken();
            throw new NotAttachedException($data['error'] ?: $response, $httpCode);
        }

        if ($httpCode >= 400) {
            throw new Exception($data['error'] ?: $response, $httpCode);
        }

        return $data;
    }

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


Question:
Store a hit in the rate limit cache

@return $this

public function hit()
    {
        if (!$this->getCache()->has($this->getIdentifier())) {
            $ttl = $this->getDecay() * 60;
            $expiry = DBDatetime::now()->getTimestamp() + $ttl;
            $this->getCache()->set($this->getIdentifier() . '-timer', $expiry, $ttl);
        } else {
            $expiry = $this->getCache()->get($this->getIdentifier() . '-timer');
            $ttl = $expiry - DBDatetime::now()->getTimestamp();
        }
        $this->getCache()->set($this->getIdentifier(), $this->getNumAttempts() + 1, $ttl);
        return $this;
    }

public static function cleanCache(String $fileName = NULL, Bool $real = false)
    {
        $fileName = Info::rpath($fileName);

        if( ! file_exists($fileName) )
        {
            clearstatcache($real);
        }
        else
        {
            clearstatcache($real, $fileName);
        }
    }

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


Question:
Fills the buffer with more bytes. The default implementation reads from the {@link #getInputStream() InputStream}, if set.
Can be overridden to fill the bytes from another source.
@return -1 if there are no more bytes.

protected int fill (byte[] buffer, int offset, int count) throws KryoException {
		if (inputStream == null) return -1;
		try {
			return inputStream.read(buffer, offset, count);
		} catch (IOException ex) {
			throw new KryoException(ex);
		}
	}

public byte[] getFileBytes(String filePath)
		throws IOException {

		byte[] out = null;
		String path = (String) Utils.intern(filePath);
		RandomAccessFile raf = null;
		synchronized (path) {
			File file = null;
			try {
				file = new File(path);
				boolean exists = file.exists();
				if (exists) {
					byte[] fileBytes = new byte[(int)file.length()];
					raf = new RandomAccessFile(file,"r");
					raf.readFully(fileBytes);
					out = fileBytes;
				} else {
				    String msg =
				        "File does not exist. (" + filePath + ")";
					mLog.error(msg);
					throw new IOException(msg);
				}
			} catch (IOException e) {
				mLog.error("Error writing: " + filePath);
				mLog.error(e);
				throw e;
			} finally {
				if (raf != null) {
					raf.close();
				}
			}
		}
		return out;
    }

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


Question:
@param string $secret

@throws ProcessorException

public function validateSign($secret)
	{

		$inputData = $this->input->all();
		Secure::sign($inputData, $this->sid(), $secret);
		if ($inputData['sign'] !== $this->input->sign) {
			throw new ProcessorException(ProcessorException::INVALID_SIGN);
		}

	}

public function addExpression(
            O\Expression $expression,
            IParameterHasher $hasher,
            IFunction $context = null,
            $data = null
    ) {
        $this->parameters[] = new ExpressionParameter($expression, $hasher, $context, $data);
    }

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


Question:
Export gallery images
@param string $content
@return array

public function exportFiles($content)
    {
        $images = [];
        if ($galleryData = $this->_defaultData($content)) {
            foreach ($galleryData as $image => $imageData) {
                $images[] = '/uploads/system/gallery/' . $this->_block->name . $imageData->path . $image;
            }
        }
        return $images;
    }

def getAlbumsForArtistInCollection(artist,user=nil,extras=nil)
      method = 'getAlbumsForArtistInCollection'
      type = Album
      args = {:artist=>artist}
      args[:user] = user if user
      args[:extras] = extras if extras
      auth = !!user
      return_object type,method,args,auth
    end

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


Question: // SetMaxRecords sets the MaxRecords field's value.

func (s *DescribeDBEngineVersionsInput) SetMaxRecords(v int64) *DescribeDBEngineVersionsInput {
	s.MaxRecords = &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: Retrieves stats for a certain load balancer pool.

def retrieve_pool_stats(self, pool, **_params):
        """"""
        return self.get(self.pool_path_stats % (pool), params=_params)

@Description("apoc.index.relationships('TYPE','prop:value*') YIELD rel - lucene query on relationship index with the given type name")
    @Procedure(mode = Mode.READ)
    public Stream<WeightedRelationshipResult> relationships(@Name("type") String type, @Name("query") String query) throws Exception {
        if (!db.index().existsForRelationships(type)) return Stream.empty();
        return toWeightedRelationshipResult(db.index().forRelationships(type).query(query,null,null));
    }

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


Question:
/*
This function is exported when we are used as a module, but not
when we load ourself as a child process.

function setupRk8Pki (target, settings) {
    settings = settings || {};

    var forge = initForge(settings.useNativeCode? {} : {disableNativeCode:true}),
        pki = forge.pki;

    var toPem = initToPem({
        cache: settings.cache,
        forge: forge
    });

    var generateKeyPair = initGenerateKeyPair({
        cacheLength: settings.pregenerateKeyPairs >=0 ? settings.pregenerateKeyPairs : 10,
        forge: forge,
        toPem: toPem
    });

    function encrypt ( msg, pemPublicKey, done ) {
        setImmediate( function() {
            // convert a PEM-formatted public key to a Forge public key
            var publicKey = toPem.publicKeyFromPem(pemPublicKey);

            // Use RSA-KEM to encrypt the msg with a randomly
            // generated one time password and AES-256
            var kdf1 = new forge.kem.kdf1(forge.md.sha256.create()),
                kem = forge.kem.rsa.create(kdf1),
                otp = kem.encrypt(publicKey, 32),
                iv = forge.random.getBytesSync(12),
                cipher = forge.cipher.createCipher('AES-GCM', otp.key),
                aesCipherText,
                encryptedOTP;

            cipher.start({iv: iv});
            cipher.update( forge.util.createBuffer(msg) );
            cipher.finish();
            aesCipherText = cipher.output;

            return done( null, {
              k: otp.encapsulation,
              iv: iv,
              m: aesCipherText,
              t: cipher.mode.tag
            });
        });
    }

    function decrypt ( cipherObj, pemPrivateKey, done ) {
        setImmediate( function() {
            // convert a PEM-formatted private key to a Forge private key
            var privateKey = toPem.privateKeyFromPem(pemPrivateKey);

            var kdf1 = new forge.kem.kdf1(forge.md.sha256.create()),
                kem = forge.kem.rsa.create(kdf1),
                key = kem.decrypt(privateKey, cipherObj.k, 32),
                decipher,
                success;

            decipher = forge.cipher.createDecipher('AES-GCM', key);
            decipher.start({
              iv: cipherObj.iv,
              tag: cipherObj.t
            });
            decipher.update(forge.util.createBuffer(cipherObj.m));
            success = decipher.finish();
            if(success){
              return done( null, decipher.output.getBytes() );
            }
            return done( new Error('Unable to decrypt cipher with provided key.') );
        });
    }

    var actions = {
      keypair: generateKeyPair,
      encrypt: encrypt,
      decrypt: decrypt
    };

    // the user does not want to use a background process,
    if (settings.fork === false) {
        // just export a direct interface.
        return Object.keys(actions).reduce( function (exported, action) {
            exported[ action ] = actions[ action ];
            return exported;
        }, target);
    }

    // We are going to uref() our child process, so we create an object to
    // track pending callbacks and use a Timer to keep the process running
    // until those callbacks are resolved.
    function checkPending () {
        if(Object.keys(pending).length === 0) {
            return keepAlive.unref();
        }
        return keepAlive.ref();
    }
    var pending = {},
        // the interval length is arbitrary and mostly irelevant, so long as
        // it is long enough not to trigger frequently. It really just gives
        // us a persistent Timer object we can use to keep the process running
        // by calling ref() whenever we need to.
        keepAlive = setInterval(checkPending, 1000);
    // start off with keepAlive timer unref()'ed
    checkPending();

    // prepare and unref() the child process that does the work as well
    // as the IPC channel we use to communicate with it.
    var child = fork(__filename, ['child', envPrefix], {
        env: Object.keys(settings).reduce( function(env, k) {
            env[ envPrefix+k ] = JSON.stringify( settings[k] );
            return env;
        }, {}),
        stdio: ['ignore', 'ignore', 'ignore', 'ipc']
    });
    // https://github.com/nodejs/node/issues/9313 means child.channel is coming
    // but child._channel already exists.
    (child.channel ? child.channel : child._channel).unref();
    child.unref();

    function childResponseListener (id, cb, response) {
        // if this isn't our message, set the listener again
        if (id != response.id) {
            // we use child.once with listeners bound to id's and callbacks
            // so that the process can exit if we don't have any
            // pending actions.
            console.log('Resetting listener for', id);
            return child.once('message', childResponseListener.bind(id, cb));
        }
        console.log('Resolving listener for', id);
        return cb(response.error, response.result);
    }

    return Object.keys(actions).reduce( function (exported, action) {
        exported[action] = function () {
            var fn = actions[ action ], // we won't call it, but we need it's length
                timeout = -1, // our default timeout is unlimited
                msg = {};

            // gather the args
            msg.args = [].slice.call(arguments, 0, -1);

            var cb = arguments[ msg.args.length ];
            if ('function' !== typeof cb) {
                // you don't want a result; we won't do anything
                throw new Error(action + '() requires a callback');
            }

            if (msg.args.length >= fn.length) {
                // the argument just before the callback must be a timeout
                timeout = msg.args.pop();
            }

            // if it's still as long or longer than fn.length we have too
            // many arguments
            if (msg.args.length >= fn.length) {
                throw new Error('Too many arguments passed to ' + action + '()');
            }

            // assign the action
            msg.action = action;

            // generate the callback id
            msg.id = [action].concat(process.hrtime(), Math.ceil(Math.random()*100000) ).join('|');

            // save the callback on our queue
            console.log('Setting listener for', msg.id);

            function resolveCb () {
                // call the actual callback at the end of this trn of the event loop
                var args = [].slice.call(arguments);
                args.unshift(cb);
                setImmediate.apply(null, args);

                // clean up the pending key and possibly unref() the keepAlive timer
                delete pending[msg.id];
                checkPending();
            }

            // make sure we have a pending key and are ref()'ed
            pending[msg.id] = true;
            checkPending();

            // listen for the response
            child.once(
                'message',
                childResponseListener.bind(
                    null,
                    msg.id,
                    (timeout >= 0?
                        timeoutOrCallback(
                            timeout,
                            action + '() timed out in '+ timeout + 'ms',
                            resolveCb
                        ) :
                        resolveCb
                    )
                )
            );

            // send a message to our child process
            child.send(msg);

        };
        return exported;
    }, target);

}

def flush_main(self):
        """"""

        if self.has_main:
            return

        self.in_main = True

        self.write('task main()')
        self.INDENT()

        if self.debug:
            print 'Flushing main:', self.fv.main
        for node in self.fv.main:
            self.v(node)
            self.NEWLINE()

        self.DEDENT()

        self.in_main = False

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


Question:
//
// Validate - checks for missing required fields, etc
//

func (self *ResourceOutput) Validate() error {
	if self.Name == "" {
		return fmt.Errorf("ResourceOutput.name is missing but is a required field")
	} else {
		val := Validate(RdlSchema(), "Identifier", self.Name)
		if !val.Valid {
			return fmt.Errorf("ResourceOutput.name does not contain a valid Identifier (%v)", val.Error)
		}
	}
	if self.Type == "" {
		return fmt.Errorf("ResourceOutput.type is missing but is a required field")
	} else {
		val := Validate(RdlSchema(), "TypeRef", self.Type)
		if !val.Valid {
			return fmt.Errorf("ResourceOutput.type does not contain a valid TypeRef (%v)", val.Error)
		}
	}
	if self.Header == "" {
		return fmt.Errorf("ResourceOutput.header is missing but is a required field")
	} else {
		val := Validate(RdlSchema(), "String", self.Header)
		if !val.Valid {
			return fmt.Errorf("ResourceOutput.header does not contain a valid String (%v)", val.Error)
		}
	}
	return nil
}

public static function makeAndValidate(array $data, array $rules = [], array $translates = [], string $scene = '')
    {
        return new static($data, $rules, $translates, $scene, true);
    }

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


Question: Vel factory function

def create(backbone: ModelFactory, vmin: float, vmax: float, atoms: int, initial_std_dev: float = 0.4,
           factorized_noise: bool = True, input_block: typing.Optional[ModelFactory] = None):

    if input_block is None:
        input_block = IdentityFactory()

    return QDistributionalModelFactory(
        input_block=input_block, backbone=backbone,
        vmin=vmin,
        vmax=vmax,
        atoms=atoms,
        initial_std_dev=initial_std_dev,
        factorized_noise=factorized_noise
    )

public JBBPDslBuilder VarArray(final String name, final String sizeExpression) {
    return this.VarArray(name, sizeExpression, null);
  }

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


Question:
{@inheritDoc}

@see \HiPay\Fullservice\HTTP\Client::request()

public function request($method, $endpoint, array $params = array(), $isVault = false)
    {
        return $this->doRequest($method, $endpoint, $params, $isVault);
    }

public function registerPaymentMethodMapper(PaymentMethodMapperInterface $paymentMethodMapper)
    {
        $paymentMethodMapper->setStandardParameter($this->standardParameter);
        $paymentMethodMapper->setSequenceNumberProvider($this->sequenceNumberProvider);
        $paymentMethodMapper->setUrlHmacGenerator($this->urlHmacGenerator);
        $this->registeredMethodMappers[$paymentMethodMapper->getName()] = $paymentMethodMapper;
    }

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


Question: Generate the tag files and add them to the zip.

def _add_tag_files(
    zip_file, dir_name, payload_info_list, payload_byte_count, payload_file_count
):
    """"""
    tag_info_list = []
    _add_tag_file(zip_file, dir_name, tag_info_list, _gen_bagit_text_file_tup())
    _add_tag_file(
        zip_file,
        dir_name,
        tag_info_list,
        _gen_bag_info_file_tup(payload_byte_count, payload_file_count),
    )
    _add_tag_file(
        zip_file, dir_name, tag_info_list, _gen_pid_mapping_file_tup(payload_info_list)
    )
    return tag_info_list

public java.lang.String getTagsOrDefault(
      java.lang.String key,
      java.lang.String defaultValue) {
    if (key == null) { throw new java.lang.NullPointerException(); }
    java.util.Map<java.lang.String, java.lang.String> map =
        internalGetTags().getMap();
    return map.containsKey(key) ? map.get(key) : defaultValue;
  }

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


Question:
Check header from stream.

@param {object} file - current file from stream.
@param {object} ctx - context.

@returns {string[]} file in string[] format.

function checkHeaderFromStream(file, ctx) {
		file.contents.pipe(es.wait(function (err, data) {
			if (err) {
				throw err;
			}

			var bufferFile = new File({
				path: file.path,
				contents: data
			});

			checkHeaderFromBuffer(bufferFile, ctx);
		}));
	}

private String[] readXMLDeclaration(Reader r) throws KNXMLException
	{
		final StringBuffer buf = new StringBuffer(100);
		try {
			for (int c = 0; (c = r.read()) != -1 && c != '?';)
				buf.append((char) c);
		}
		catch (final IOException e) {
			throw new KNXMLException("reading XML declaration, " + e.getMessage(), buf
				.toString(), 0);
		}
		String s = buf.toString().trim();

		String version = null;
		String encoding = null;
		String standalone = null;

		for (int state = 0; state < 3; ++state)
			if (state == 0 && s.startsWith("version")) {
				version = getAttValue(s = s.substring(7));
				s = s.substring(s.indexOf(version) + version.length() + 1).trim();
			}
			else if (state == 1 && s.startsWith("encoding")) {
				encoding = getAttValue(s = s.substring(8));
				s = s.substring(s.indexOf(encoding) + encoding.length() + 1).trim();
			}
			else if (state == 1 || state == 2) {
				if (s.startsWith("standalone")) {
					standalone = getAttValue(s);
					if (!standalone.equals("yes") && !standalone.equals("no"))
						throw new KNXMLException("invalid standalone pseudo-attribute",
							standalone, 0);
					break;
				}
			}
			else
				throw new KNXMLException("unknown XML declaration pseudo-attribute", s, 0);
		return new String[] { version, encoding, standalone };
	}

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


Question:
Returns all income accounts for this security.
        Income accounts are accounts not under Trading, expressed in currency, and
        having the same name as the mnemonic.
        They should be under Assets but this requires a recursive SQL query.

def get_income_accounts(self) -> List[Account]:

        # trading = self.book.trading_account(self.security)
        # log(DEBUG, "trading account = %s, %s", trading.fullname, trading.guid)

        # Example on how to self-link, i.e. parent account, using alias.
        # parent_alias = aliased(Account)
            # .join(parent_alias, Account.parent)
        # parent_alias.parent_guid != trading.guid

        query = (
            self.book.session.query(Account)
            .join(Commodity)
            .filter(Account.name == self.security.mnemonic)
            .filter(Commodity.namespace == "CURRENCY")
            # .filter(Account.type != "TRADING")
            .filter(Account.type == AccountType.income.value)
        )
        # generic.print_sql(query)
        return query.all()

def sec_overview(self):

        """ Data sources overview: table with metric summaries"""
        metrics = self.config['overview']['activity_metrics']
        file_name = self.config['overview']['activity_file_csv']

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, file_name)

        logger.debug("CSV file %s generation in progress", file_name)

        csv = 'metricsnames,netvalues,relativevalues,datasource\n'
        for metric in metrics:
            # comparing current metric month count with previous month
            es_index = self.get_metric_index(metric)
            ds = metric.ds.name
            m = metric(self.es_url, es_index, start=self.start, end=self.end)
            (last, percentage) = m.get_trend()
            csv += "%s,%i,%i,%s" % (metric.name, last, percentage, ds)
            csv += "\n"
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            # Hack, we need to fix LaTeX escaping in a central place
            csv = csv.replace("_", r"\_")
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

        """
        Git Authors:

        description: average number of developers per month by quarters
        (so we have the average number of developers per month during
        those three months). If the approach is to work at the level of month,
        then just the number of developers per month.
        """

        author = self.config['overview']['author_metrics'][0]
        csv_labels = 'labels,' + author.id
        file_label = author.ds.name + "_" + author.id
        title_label = author.name + " per " + self.interval
        self.__create_csv_eps(author, None, csv_labels, file_label, title_label)

        logger.debug("CSV file %s generation in progress", file_name)

        bmi = []
        ttc = []  # time to close

        csv_labels = ''
        for m in self.config['overview']['bmi_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            bmi.append(metric.get_agg())

        for m in self.config['overview']['time_to_close_metrics']:
            metric = m(self.es_url, self.get_metric_index(m),
                       start=self.end_prev_month, end=self.end)
            csv_labels += m.id + ","
            ttc.append(metric.get_agg())

        csv = csv_labels[:-1] + "\n"  # remove last comma
        csv = csv.replace("_", "")
        for val in bmi:
            csv += "%s," % (self.str_val(val))
        for val in ttc:
            csv += "%s," % (self.str_val(val))
        if csv[-1] == ',':
            csv = csv[:-1]

        data_path = os.path.join(self.data_dir, "data")
        file_name = os.path.join(data_path, 'efficiency.csv')
        os.makedirs(os.path.dirname(file_name), exist_ok=True)
        with open(file_name, "w") as f:
            f.write(csv)

        logger.debug("CSV file: %s was generated", file_name)

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


Question:
Distance between two vectors/points.

@param Vector $value1
@param Vector $value2
@return float

public static function distance(Vector $value1, Vector $value2) : float {
        return sqrt(self::distance2($value1, $value2));
    }

function diff( x, y, scale ) {
	var f;
	var s;
	if ( x !== x || y !== y ) {
		return NaN;
	}
	if (
		x === PINF ||
		x === NINF ||
		y === PINF ||
		y === NINF
	) {
		if ( x === y ) {
			return NaN;
		}
		return PINF;
	}
	// If the absolute difference is `0`, then so is the relative difference:
	if ( x === y ) {
		return 0.0;
	}
	if ( isFunction( scale ) ) {
		f = scale;
	} else {
		if ( scale === void 0 ) {
			scale = 'max-abs';
		}
		f = SCALE[ scale ];
		if ( f === void 0 ) {
			throw new Error( 'invalid input argument. Unrecognized/unsupported scale function. Value: `' + scale + '`.' );
		}
	}
	s = f( x, y );
	if ( s === 0 ) {
		// Bail. No possible return value which works for all possible scale functions...
		return NaN;
	}
	return abs( (x - y) / s );
}

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


Question:
Opens up filename.title and
        filename.description, updates on flickr

def _update_meta(self,directory,filename):
        """"""

        if not self._connectToFlickr():
            print("%s - Couldn't connect to flickr"%(directory))
            return False

        db = self._loadDB(directory)

        # Look up photo id for this photo
        pid=db[filename]['photoid']

        # =========== LOAD TITLE ========
        fullfile=os.path.join(directory,filename+'.title')
        try:
            logger.debug('trying to open [%s]'%(fullfile))
            _title=(open(fullfile).readline().strip())
            logger.debug("_updatemeta: %s - title is %s",filename,_title)
        except:
            _title=''

        # =========== LOAD DESCRIPTION ========
        fullfile=os.path.join(directory,filename+'.description')
        try:
            _description=(open(fullfile).readline().strip())
            logger.debug("_updatemeta: %s - description is %s",filename,_description)
        except:
            _description=''

        logger.info('%s - updating metadata (title=%s) (description=%s)'\
                %(filename,_title,_description))
        resp=self.flickr.photos_setMeta(photo_id=pid,title=_title,\
                description=_description)
        if resp.attrib['stat']!='ok':
            logger.error("%s - flickr: photos_setTags failed with status: %s",\
                    resp.attrib['stat']);
            return False
        else:
            return True

public function getCaption()
    {
        if ($this->_caption === null) {
            if ($this->getKey('caption', false)) {
                $this->_caption = $this->getKey('caption');
            } else {
                $this->_caption = $this->file->caption;
            }
        }

        return $this->_caption;
    }

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


Question:
Handle whitespace around and inside parens for control structures.

@param IfNode|ElseIfNode|ForNode|ForeachNode|SwitchNode|DoWhileNode|WhileNode $node

protected function handleParens($node) {
    $open_paren = $node->getOpenParen();
    $this->removeSpaceAfter($open_paren);
    $this->spaceBefore($open_paren);
    $close_paren = $node->getCloseParen();
    $this->removeSpaceBefore($close_paren);
  }

def parse_case(self, node):

        try:
            condition = node.lattrib['condition']
        except:
            condition = None

        try:
            value = node.lattrib['value']
        except:
            self.raise_error('<Case> must specify a value')

        self.current_conditional_derived_variable.add_case(Case(condition, value))

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


Question:
Checks the coverage of sequence by source features' locations.

@param entry an entry to be checked (expected type is Entry)
@return a validation result

public ValidationResult check(Entry entry) {
        result = new ValidationResult();

        if (entry == null) {
            return result;
        }

        //collect all gene features
        Collection<Feature> geneFeatures =
                SequenceEntryUtils.getFeatures(Feature.GENE_FEATURE_NAME, entry);

        if (geneFeatures.isEmpty()) {
            return result;
        }

        /**
         * which locus tag qualifiers are mapped to which gene features - should be an exclusive association
         */
        HashMap<String, Feature> locusTag2GeneFeature = new HashMap<String, Feature>();

        for (Feature geneFeature : geneFeatures) {

            List<Qualifier> locusQualifiers = geneFeature.getQualifiers(Qualifier.LOCUS_TAG_QUALIFIER_NAME);
            if (locusQualifiers.size() > 0) {

                String locus_tag_name = locusQualifiers.get(0).getValue();//got other checks for multiple locus_tags

                if (locusTag2GeneFeature.containsKey(locus_tag_name)) {
                    ValidationMessage<Origin> message =
                            reportError(result, geneFeature.getOrigin(), MESSAGE_ID, locus_tag_name);
                    message.append(locusTag2GeneFeature.get(locus_tag_name).getOrigin());
                } else {
                    locusTag2GeneFeature.put(locus_tag_name, geneFeature);
                }

            }
        }

        return result;
    }

public function validate($data) {
    if ($data === NULL) throw $this->emptyException();
    if (!is_array($data)) throw $this->invalidArgument(1, $data, 'Array', __FUNCTION__);

    foreach ($this->languages as $lang) {
      if (!array_key_exists($lang, $data)) {
        throw $this->emptyException();
      }

      try {
        $data[$lang] = $this->wrappedRule->validate($data[$lang]);
      } catch (EmptyDataException $e) {
        throw $this->emptyException($e);
      }
    }

    return $data;
  }

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


Question:
SPL autoload function, loads a class file based on the class name.

@param string

public function loadClass($className)
	{
		if (class_exists($className, false) || interface_exists($className, false))
		{
			return false;
		}

		if($classFile = $this->classFile($className))
		{
			require $classFile;
			return true;
		}

		return false;
	}

public function getFullName()
    {
        $args = $this->getParameters();
        $argstr = '';

        foreach ((array) $args as $arg) {
            if ($argstr != '') {
                $argstr .= ', ';
            }
            $argstr .= $arg->type.' $'.$arg->name;
        }

        return $this->return.' '.$this->name.'('.$argstr.')';
    }

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


Question: Activates the comfort temperature.

def activate_eco(self):
        """"""
        value = struct.pack('B', PROP_ECO)
        self._conn.make_request(PROP_WRITE_HANDLE, value)

protected function init()
    {
        $this->addCommand(new SyncCommand());
        $this->addCommand(new MakesumCommand());

        $this->addGlobalOption('e')
            ->alias('env')
            ->description('The environment application name or class.')
            ->defaultValue('dev');
    }

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


Question:
Filter a list of versions to those that allow the current PHP version.

@param string[] $versions

@return string[]

private function filterByPhpVersion(array $versions)
    {
        $versionInfo = $this->getAvailableVersions();

        return array_filter($versions, function ($version) use ($versionInfo) {
            if (isset($versionInfo[$version]['php']['min'])
                && version_compare(PHP_VERSION, $versionInfo[$version]['php']['min'], '<')) {
                return false;
            } elseif (isset($versionInfo[$version]['php']['max'])
                && version_compare(PHP_VERSION, $versionInfo[$version]['php']['max'], '>')) {
                return false;
            }

            return true;
        });
    }

func IsAllowedVersion(v unversioned.GroupVersion) bool {
	if len(envRequestedVersions) == 0 {
		return true
	}
	_, found := envRequestedVersions[v]
	return found
}

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


Question:
Mu-law compress a block of audio samples, and convert them into a
    categorical distribution

def categorical(x, mu=255, normalize=True):

    if normalize:
        # normalize the signal
        mx = x.max()
        x = np.divide(x, mx, where=mx != 0)

    # mu law compression
    x = mu_law(x)

    # translate and scale to [0, 1]
    x = (x - x.min()) * 0.5

    # convert to the range [0, 255]
    x = (x * mu).astype(np.uint8)

    # create the array to house the categorical representation
    c = np.zeros((np.product(x.shape), mu + 1), dtype=np.uint8)
    c[np.arange(len(c)), x.flatten()] = 1

    return ArrayWithUnits(
        c.reshape(x.shape + (mu + 1,)),
        x.dimensions + (IdentityDimension(),))

def check_arg_compatibility(args: argparse.Namespace):

    if args.lhuc is not None:
        # Actually this check is a bit too strict
        check_condition(args.encoder != C.CONVOLUTION_TYPE or args.decoder != C.CONVOLUTION_TYPE,
                        "LHUC is not supported for convolutional models yet.")
        check_condition(args.decoder != C.TRANSFORMER_TYPE or C.LHUC_STATE_INIT not in args.lhuc,
                        "The %s options only applies to RNN models" % C.LHUC_STATE_INIT)

    if args.decoder_only:
        check_condition(args.decoder != C.TRANSFORMER_TYPE and args.decoder != C.CONVOLUTION_TYPE,
                        "Decoder pre-training currently supports RNN decoders only.")

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


Question: Prepare SAML request

def prepare_request(settings):

    # Set the ACS url and binding method
    settings["sp"]["assertionConsumerService"] = {
        "url": web.ctx.homedomain + web.ctx.homepath + "/auth/callback/" + settings["id"],
        "binding": "urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"
    }

    # If server is behind proxys or balancers use the HTTP_X_FORWARDED fields
    data = web.input()
    return {
        'https': 'on' if web.ctx.protocol == 'https' else 'off',
        'http_host': web.ctx.environ["SERVER_NAME"],
        'server_port': web.ctx.environ["SERVER_PORT"],
        'script_name': web.ctx.homepath,
        'get_data': data.copy(),
        'post_data': data.copy(),
        # Uncomment if using ADFS as IdP, https://github.com/onelogin/python-saml/pull/144
        # 'lowercase_urlencoding': True,
        'query_string': web.ctx.query
    }

def create_api_v4_ipv4(self):
        """"""

        return ApiV4IPv4(
            self.networkapi_url,
            self.user,
            self.password,
            self.user_ldap)

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


Question:
Restores group members from the snapshot. Both {@link #committedGroupMembers}
and {@link #lastGroupMembers} are overwritten and they become the same.

public void restoreGroupMembers(long logIndex, Collection<Endpoint> members) {
        assert lastGroupMembers.index() <= logIndex
                : "Cannot restore group members to: " + members + " at log index: " + logIndex + " because last group members: "
                + lastGroupMembers + " has a bigger log index.";

        // there is no leader state to clean up

        RaftGroupMembers groupMembers = new RaftGroupMembers(logIndex, members, localEndpoint);
        this.committedGroupMembers = groupMembers;
        this.lastGroupMembers = groupMembers;
    }

func (p *Path) SaveOptionalReverse(via interface{}, tag string) *Path {
	np := p.clone()
	np.stack = append(np.stack, saveOptionalReverseMorphism(via, tag))
	return np
}

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


Question:
Returns the parent of this path or null if this path is the root path.

@return the parent of this path or null if this path is the root path.

public Path getParent() {
		if (!isAbsolute())
			throw new IllegalStateException("path is not absolute: " + toString());
		if (segments.isEmpty())
			return null;
		return new Path(segments.subList(0, segments.size()-1), true);
	}

func RepoInfo() (repoRoot string, repoRevision string, repoTag string) {
	var vcsCmd *vcs.Cmd

	// Walk up the call stack until we find main.main
	for i := 1; ; i++ {
		caller, file, _, ok := runtime.Caller(i)
		if !ok {
			break
		}

		f := runtime.FuncForPC(caller)
		if f == nil {
			continue
		}
		if path.Base(f.Name()) == "main.main" {
			repoRoot = path.Dir(file)
			break
		}

		// see if we're in testing
		if path.Base(f.Name()) == "testing.tRunner" {
			// go back up one level
			_, file, _, _ := runtime.Caller(i - 1)
			repoRoot = path.Dir(file)
			break
		}
	}

	// Try and find the root of the VCS repo using repoRoot as a starting point.
	if repoRoot != "" {
		// walk up the dir until we get to the first directory in root.
		// This is an unfortunately necessity to use vcs.FromDir()
		topDir := repoRoot
		for dir := path.Dir(topDir); dir != "." && dir[len(dir)-1] != '/' && dir != topDir; dir = path.Dir(topDir) {
			topDir = dir
		}

		var vcsRoot string
		vcsCmd, vcsRoot, _ = vcs.FromDir(path.Dir(repoRoot), topDir)
		if len(vcsRoot) > 0 {
			if vcsRoot[0] != '/' {
				vcsRoot = topDir + "/" + vcsRoot
			}
			repoRoot = vcsRoot
		}
	}

	if vcsCmd != nil && vcsCmd.Name == "Git" {
		execCmd := exec.Command("git", "describe", "--dirty", "--match", "", "--always")
		execCmd.Dir = repoRoot
		output, err := execCmd.Output()
		if err == nil {
			repoRevision = string(bytes.TrimRight(output, "\n"))
		}

		execCmd = exec.Command("git", "describe", "--dirty", "--tags", "--always")
		execCmd.Dir = repoRoot
		output, err = execCmd.Output()
		if err == nil {
			repoTag = string(bytes.TrimRight(output, "\n"))
		}
	}

	return
}

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


Question: // RegisterFunc adds the HandlerFunc based on type.

func (d *dispatcher) RegisterFunc(c StreamType, h HandlerFunc) {
	d.handlers[c] = &basicHandler{h}
}

public function dispatchCommentUpdateEvent(Post $post, Comment $comment, $changeSet)
    {
        $event = new LogCommentUpdateEvent($post, $comment, $changeSet, $this->translator);

        return $this->dispatch($event);
    }

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


Question: Get the slot for the given symbol.

@Override
  public StaticTypedSlot getSlot(String name) {
    OverlayScope scope = getOverlayScopeForVar(name, false);
    return scope != null ? scope.getSlot(name) : syntacticScope.getSlot(name);
  }

func (s *CreateSlotTypeVersionOutput) SetVersion(v string) *CreateSlotTypeVersionOutput {
	s.Version = &v
	return s
}

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


Question:
Creates a new interceptor chain to handle the given request.

@param request the request to handle
@return a new interceptor chain for the request.

public static InterceptorComponent createInterceptorChain(final HttpServletRequest request) {

		// Allow for multi part parameters
		Map<String, String[]> parameters = getRequestParameters(request);

		InterceptorComponent[] chain;

		if (parameters.get(WServlet.DATA_LIST_PARAM_NAME) != null) { // Datalist
			chain = new InterceptorComponent[]{
				new TransformXMLInterceptor(),
				new DataListInterceptor()};

		} else if (parameters.get(WServlet.AJAX_TRIGGER_PARAM_NAME) != null) { // AJAX
			chain = new InterceptorComponent[]{
				new TemplateRenderInterceptor(),
				new TransformXMLInterceptor(),
				new ValidateXMLInterceptor(),
				new AjaxErrorInterceptor(),
				new SessionTokenAjaxInterceptor(),
				new ResponseCacheInterceptor(CacheType.NO_CACHE),
				new UIContextDumpInterceptor(),
				new AjaxSetupInterceptor(),
				new WWindowInterceptor(true),
				new WrongStepAjaxInterceptor(),
				new ContextCleanupInterceptor(),
				new WhitespaceFilterInterceptor(),
				new SubordinateControlInterceptor(),
				new AjaxPageShellInterceptor(),
				new AjaxDebugStructureInterceptor(),
				new AjaxInterceptor()};

		} else if (parameters.get(WServlet.TARGET_ID_PARAM_NAME) != null) { // Targetted Content
			chain = new InterceptorComponent[]{
				new TargetableErrorInterceptor(),
				new SessionTokenContentInterceptor(),
				new UIContextDumpInterceptor(),
				new TargetableInterceptor(),
				new WWindowInterceptor(false),
				new WrongStepContentInterceptor()};

		} else {
			chain = new InterceptorComponent[]{ // Page submit
				new TemplateRenderInterceptor(),
				new TransformXMLInterceptor(),
				new ValidateXMLInterceptor(),
				new SessionTokenInterceptor(),
				new ResponseCacheInterceptor(CacheType.NO_CACHE),
				new UIContextDumpInterceptor(),
				new WWindowInterceptor(true),
				new WrongStepServerInterceptor(),
				new AjaxCleanupInterceptor(),
				new ContextCleanupInterceptor(),
				new WhitespaceFilterInterceptor(),
				new SubordinateControlInterceptor(),
				new PageShellInterceptor(),
				new FormInterceptor(),
				new DebugStructureInterceptor()};
		}

		// Link the interceptors together in a chain.
		for (int i = 0; i < chain.length - 1; i++) {
			chain[i].setBackingComponent(chain[i + 1]);
		}

		// Return the top of the chain.
		return chain[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:
Return a dictionary mapping the names of all actions for this
        ModelAdmin to a tuple of (callable, name, description) for each action.

def get_actions(self, request):

        # If self.actions is explicitly set to None that means that we don't
        # want *any* actions enabled on this page.
        if self.actions is None:
            return OrderedDict()

        actions = []

        # Gather actions from the admin site first
        for (name, func) in self.admin_site.actions:
            description = getattr(
                func, 'short_description', name.replace('_', ' '))
            actions.append((func, name, description))

        # Then gather them from the model admin and all parent classes,
        # starting with self and working back up.
        for klass in self.__class__.mro()[::-1]:
            class_actions = getattr(klass, 'actions', [])
            # Avoid trying to iterate over None
            if not class_actions:
                continue
            actions.extend(self.get_action(action) for action in class_actions)

        # get_action might have returned None, so filter any of those out.
        actions = filter(None, actions)

        # Convert the actions into an OrderedDict keyed by name.
        actions = OrderedDict(
            (name, (func, name, desc))
            for func, name, desc in actions
        )

        if 'delete_selected' in actions:
            del actions['delete_selected']
        return actions

def kitchen_config(backend, kitchen, add, get, unset, listall):

    err_str, use_kitchen = Backend.get_kitchen_from_user(kitchen)
    if use_kitchen is None:
        raise click.ClickException(err_str)
    check_and_print(DKCloudCommandRunner.config_kitchen(backend.dki, use_kitchen, add, get, unset, listall))

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


Question: Filters the document AST.

def main():
    """"""

    # pylint: disable=global-statement
    global PANDOCVERSION
    global AttrMath

    # Get the output format and document
    fmt = args.fmt
    doc = json.loads(STDIN.read())

    # Initialize pandocxnos
    # pylint: disable=too-many-function-args
    PANDOCVERSION = pandocxnos.init(args.pandocversion, doc)

    # Element primitives
    AttrMath = elt('Math', 3)

    # Chop up the doc
    meta = doc['meta'] if PANDOCVERSION >= '1.18' else doc[0]['unMeta']
    blocks = doc['blocks'] if PANDOCVERSION >= '1.18' else doc[1:]

    # Process the metadata variables
    process(meta)

    # First pass
    attach_attrs_math = attach_attrs_factory(Math, allow_space=True)
    detach_attrs_math = detach_attrs_factory(Math)
    insert_secnos = insert_secnos_factory(Math)
    delete_secnos = delete_secnos_factory(Math)
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [attach_attrs_math, insert_secnos,
                                process_equations, delete_secnos,
                                detach_attrs_math], blocks)

    # Second pass
    process_refs = process_refs_factory(references.keys())
    replace_refs = replace_refs_factory(references,
                                        use_cleveref_default, use_eqref,
                                        plusname if not capitalize else
                                        [name.title() for name in plusname],
                                        starname, 'equation')
    altered = functools.reduce(lambda x, action: walk(x, action, fmt, meta),
                               [repair_refs, process_refs, replace_refs],
                               altered)

    # Update the doc
    if PANDOCVERSION >= '1.18':
        doc['blocks'] = altered
    else:
        doc = doc[:1] + altered

    # Dump the results
    json.dump(doc, STDOUT)

    # Flush stdout
    STDOUT.flush()

public static boolean arrayFilter(String type) {

        int lastIndex = type.lastIndexOf(ARRAY_PREFIX);
        if (lastIndex == -1) {
            return false;
        }

        String arrayType = type.substring(lastIndex + 1);

        return nameFilter(arrayType);
    }

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


Question:
// AddOrganizationRegistryEntry is the handler for POST /organizations/{globalid}/registry
// Adds a RegistryEntry to the organization's registry, if the key is already used, it is overwritten.

func (api OrganizationsAPI) AddOrganizationRegistryEntry(w http.ResponseWriter, r *http.Request) {
	globalid := mux.Vars(r)["globalid"]

	registryEntry := registry.RegistryEntry{}

	if err := json.NewDecoder(r.Body).Decode(&registryEntry); err != nil {
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}
	if err := registryEntry.Validate(); err != nil {
		log.Debug("Invalid registry entry: ", registryEntry)
		http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
		return
	}

	mgr := registry.NewManager(r)
	err := mgr.UpsertRegistryEntry("", globalid, registryEntry)

	if err != nil {
		log.Error(err.Error())
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}

	w.Header().Set("Content-Type", "application/json")
	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(registryEntry)
}

func (c oauthClient) CreateFolder(
	title string,
	listIDs []uint,
) (wl.Folder, error) {
	if title == "" {
		return wl.Folder{}, errors.New("title must be non-empty")
	}

	if listIDs == nil || len(listIDs) == 0 {
		return wl.Folder{}, errors.New("listIDs must be non-nil and non-empty")
	}

	fcc := folderCreateConfig{
		Title:   title,
		ListIDs: listIDs,
	}

	body, err := json.Marshal(fcc)
	if err != nil {
		return wl.Folder{}, err
	}

	reqURL := fmt.Sprintf("%s/folders", c.apiURL)

	req, err := c.newPostRequest(reqURL, body)
	if err != nil {
		return wl.Folder{}, err
	}

	resp, err := c.do(req)
	if err != nil {
		return wl.Folder{}, err
	}

	if resp.StatusCode != http.StatusCreated {
		return wl.Folder{}, fmt.Errorf("Unexpected response code %d - expected %d", resp.StatusCode, http.StatusCreated)
	}

	folder := wl.Folder{}
	err = json.NewDecoder(resp.Body).Decode(&folder)
	if err != nil {
		return wl.Folder{}, err
	}
	return folder, nil
}

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


Question:
Ends a section. If a name is provided checks that the name provided is the right one.

@param string|void Section to close
@return \Foil\Contracts\SectionInterface
@throws InvalidArgumentException         If provided name is not the section to be closed.

private function end($name)
    {
        $this->last = $this->names->pop();
        if (! is_null($name) && $this->last !== $name) {
            $n = is_string($name) ? $name : 'a bad';
            $msg = 'You tried to close %s section where you should have closed %s.';
            throw new InvalidArgumentException(sprintf($msg, $n, $this->last));
        }

        return $this->stack->pop();
    }

func (p *parser) parseSection(inverse bool) (node, error) {
	t := p.read()
	if t.typ != tokenIdentifier {
		return nil, p.errorf(t, "unexpected token %s", t)
	}
	if next := p.read(); next.typ != tokenRightDelim {
		return nil, p.errorf(t, "unexpected token %s", t)
	}
	var (
		tokens []token
		stack  = 1
	)
	for {
		read, err := p.readv(t)
		if err != nil {
			return nil, err
		}
		tokens = append(tokens, read...)
		if len(read) > 1 {
			// Check the token that preceeded the matching identifier. For
			// section start and inverse tokens we increase the stack, otherwise
			// decrease.
			tt := read[len(read)-2]
			switch {
			case tt.typ == tokenSectionStart || tt.typ == tokenSectionInverse:
				stack++
			case tt.typ == tokenSectionEnd:
				stack--
			}
		}
		if stack == 0 {
			break
		}
	}
	nodes, err := subParser(tokens[:len(tokens)-3]).parse()
	if err != nil {
		return nil, err
	}
	section := &sectionNode{
		name:     t.val,
		inverted: inverse,
		elems:    nodes,
	}
	return section, nil
}

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


Question:
A thin wrapper layer over {@link KeyedStream#countWindow(long, long)}.

@param size The size of the windows in number of elements.
@param slide The slide interval in number of elements.
@return The python windowed stream {@link PythonWindowedStream}

public PythonWindowedStream count_window(long size, long slide) {
		return new PythonWindowedStream<GlobalWindow>(this.stream.countWindow(size, slide));
	}

func (p *PartitionedBloomFilter) WriteTo(stream io.Writer) (int64, error) {
	err := binary.Write(stream, binary.BigEndian, uint64(p.m))
	if err != nil {
		return 0, err
	}
	err = binary.Write(stream, binary.BigEndian, uint64(p.k))
	if err != nil {
		return 0, err
	}
	err = binary.Write(stream, binary.BigEndian, uint64(p.s))
	if err != nil {
		return 0, err
	}
	err = binary.Write(stream, binary.BigEndian, uint64(p.count))
	if err != nil {
		return 0, err
	}
	err = binary.Write(stream, binary.BigEndian, uint64(len(p.partitions)))
	if err != nil {
		return 0, err
	}
	var numBytes int64
	for _, partition := range p.partitions {
		num, err := partition.WriteTo(stream)
		if err != nil {
			return 0, err
		}
		numBytes += num
	}
	return numBytes + int64(5*binary.Size(uint64(0))), err
}

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


Question:
Get checkpoints for the month.

@param int                     $vehicleId
@param int                     $year
@param int                     $month
@param \Katsana\Sdk\Query|null $query

@return \Laravie\Codex\Contracts\Response

public function month(int $vehicleId, int $year, int $month = 1, ?Query $query = null): Response
    {
        $this->requiresAccessToken();

        return $this->send(
            'GET',
            "vehicles/{$vehicleId}/checkpoints/{$year}/{$month}",
            $this->getApiHeaders(),
            $this->buildHttpQuery($query)
        );
    }

def _detect(self):

        results = []

        self.results = []
        self.visited_all_paths = {}

        for contract in self.slither.contracts:
            for function in contract.functions:
                if function.is_implemented:
                    uninitialized_storage_variables = [v for v in function.local_variables if v.is_storage and v.uninitialized]
                    function.entry_point.context[self.key] = uninitialized_storage_variables
                    self._detect_uninitialized(function, function.entry_point, [])

        for(function, uninitialized_storage_variable) in self.results:
            var_name = uninitialized_storage_variable.name

            info = "{} in {}.{} ({}) is a storage variable never initialiazed\n"
            info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str)

            json = self.generate_json_result(info)
            self.add_variable_to_json(uninitialized_storage_variable, json)
            self.add_function_to_json(function, json)
            results.append(json)

        return results

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


Question:
Creates the CMS_HISTORY_PRINCIPALS table if it does not exist yet.<p>

@param dbCon the db connection interface

@throws SQLException if something goes wrong

@Override
    protected void createHistPrincipalsTable(CmsSetupDb dbCon) throws SQLException {

        System.out.println(new Exception().getStackTrace()[0].toString());
        if (!dbCon.hasTableOrColumn(TABLE_CMS_HISTORY_PRINCIPALS, null)) {
            String createStatement = readQuery(QUERY_HISTORY_PRINCIPALS_CREATE_TABLE_MYSQL);
            Map<String, String> replacer = Collections.singletonMap("${tableEngine}", m_poolData.get("engine"));
            dbCon.updateSqlStatement(createStatement, replacer, null);
        } else {
            System.out.println("table " + TABLE_CMS_HISTORY_PRINCIPALS + " already exists");
        }
    }

public function connect()
  {
    try {
      $this->cnx = new \PDO($this->dns, $this->user, $this->pass);
      $this->cnx->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
      return true;
    } catch (\Exception $e) {
      return false;
    }
  }

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


Question:
Validator class

@public
@constructor
@class Validator

function Validator(config) {

  // Instance properties
  this.rules = {};
  this.rulesCount = 0;
  this.messages = {};
  this.optional = [];
  this.filters = {};
  this.postFilters = {};
  this.postValidations = [];

  // Options
  this.config = protos.extend({
    cleanup: true
  }, config || {});

  // Set context
  Object.defineProperty(this, '__context', {
    value: {},
    writable: true,
    enumerable: false,
    configurable: false
  });

  // App property
  Object.defineProperty(this, 'app', {
    value: protos.app,
    writable: true,
    enumerable: false,
    configurable: false
  });

}

protected function createMarshallerFactory()
    {
        $version = $this->getVersion();
        if ($version === '2.0.0') {
            return new Qti20MarshallerFactory();
        } elseif ($version === '2.1.0') {
            return new Qti21MarshallerFactory();
        } elseif ($version === '2.1.1') {
            return new Qti211MarshallerFactory();
        } elseif ($version === '2.2.0') {
            return new Qti22MarshallerFactory();
        } elseif ($version === '2.2.1') {
            return new Qti221MarshallerFactory();
        } elseif ($version === '3.0.0') {
            return new Qti30MarshallerFactory();
        } else {
            $msg = "No MarshallerFactory implementation found for QTI version '${version}'.";
            throw new RuntimeException($msg);
        }
    }

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


Question:
Perform the analysis and return the results. Always check {@link Analysis#getError()}
to see if there was an error generating the results.

@return analysis
@throws Exception unrecoverable errors

public Analysis     analyze() throws Exception
    {
        AtomicReference<String>     error = new AtomicReference<String>(null);
        Map<String, PathComplete>   loadedPaths = loadedPaths(paths, error);
        if ( error.get() != null )
        {
            return new Analysis(error.get(), Lists.<PathComplete>newArrayList(), Lists.<Set<String>>newArrayList());
        }

        List<Node>        resourceAllocationGraph = buildResourceAllocationGraph(loadedPaths);
        List<Set<String>> possibleCycles = checkForCycles(resourceAllocationGraph, loadedPaths);

        return new Analysis(null, loadedPaths.values(), possibleCycles);
    }

private String expandLHS(final String lhs,
                             int lineOffset) {
        substitutions = new ArrayList<Map<String, String>>();

        //        logger.info( "*** LHS>" + lhs + "<" );
        final StringBuilder buf = new StringBuilder();

        final String[] lines = lhs.split( (lhs.indexOf("\r\n") >= 0 ? "\r\n":"\n"),
                                          -1 ); // since we assembled the string, we know line breaks are \n
        final String[] expanded = new String[lines.length]; // buffer for expanded lines
        int lastExpanded = -1;
        int lastPattern = -1;
        for ( int i = 0; i < lines.length - 1; i++ ) {
            final String trimmed = lines[i].trim();
            expanded[++lastExpanded] = lines[i];

            if ( trimmed.length() == 0 || trimmed.startsWith( "#" ) || trimmed.startsWith( "//" ) ) {
                // comments - do nothing
            } else if ( trimmed.startsWith( ">" ) ) {
                // passthrough code - simply remove the passthrough mark character
                expanded[lastExpanded] = lines[i].replaceFirst( ">",
                                                                " " );
                lastPattern = lastExpanded;
            } else {
                // regular expansion - expand the expression
                expanded[lastExpanded] =
                        substitute( expanded[lastExpanded],
                                    this.condition,
                                    i + lineOffset,
                                    useWhen,
                                    showSteps );

                // do we need to report errors for that?
                if ( lines[i].equals( expanded[lastExpanded] ) ) {
                    // report error
                    this.addError( new ExpanderException( "Unable to expand: " + lines[i].replaceAll( "[\n\r]",
                                                                                "" ).trim(),
                                                          i + lineOffset ) );
                }
                // but if the original starts with a "-", it means we need to add it
                // as a constraint to the previous pattern
                if ( trimmed.startsWith( "-" ) && (!lines[i].equals( expanded[lastExpanded] )) ) {
                    if ( lastPattern >= 0 ) {
                        ConstraintInformation c = ConstraintInformation.findConstraintInformationInPattern( expanded[lastPattern] );
                        if ( c.start > -1 ) {
                            // rebuilding previous pattern structure
                            expanded[lastPattern] = expanded[lastPattern].substring( 0,
                                                                                c.start ) + c.constraints + ((c.constraints.trim().length() == 0) ? "" : ", ") + expanded[lastExpanded].trim() + expanded[lastPattern].substring( c.end );
                        } else {
                            // error, pattern not found to add constraint to
                            this.addError( new ExpanderException( "No pattern was found to add the constraint to: " + lines[i].trim(),
                                                                  i + lineOffset ) );
                        }
                    }
                    lastExpanded--;
                } else {
                    lastPattern = lastExpanded;
                }
            }
        }
        for ( int i = 0; i <= lastExpanded; i++ ) {
            buf.append( expanded[i] );
            buf.append( nl );
        }

        return buf.toString();
    }

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


Question:
FUNCTION insertfontSmiley
@description
Coverts the text into font emoticons

@param  {string} str

@return {string}

function insertfontSmiley(str) {

                    var a = str.split(' ');
                    angular.forEach(icons, function (icon) {
                        for (var i = 0; i < a.length; i++) {
                            if (a[i] === icon.text) {
                                a[i] = '<i class="icon-emoticon" title="' + icon.text + '">' + '&#x' + icon.code + '</i>';
                            }
                        }
                    });
                    return a.join(' ');
                }

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

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


Question:
validate from-to
        :param start: Start Day(YYYYMMDD)
        :param end: End Day(YYYYMMDD)
        :return: None or MlbAmException

def _validate_datetime_from_to(cls, start, end):

        if not start <= end:
            raise MlbAmBadParameter("not Start Day({start}) <= End Day({end})".format(start=start, end=end))

function createDateTimeFormatter( type, inputFormat ) {
   return ( options, value ) => {
      if( value == null ) {
         return '';
      }

      if( value instanceof Date ) {
         return format( moment( value ) );
      }

      if( typeof value !== 'string' ) {
         throw argumentError( value );
      }

      const useInputFormat = value.length < ISO_FULL_FORMAT_MIN_LENGTH;
      const momentTime = value.toLowerCase() === 'now' ?
         moment() :
         moment( value, useInputFormat ? inputFormat : undefined, useInputFormat || undefined );

      if( !momentTime.isValid() ) {
         throw argumentError( value );
      }

      return format( momentTime );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      function format( momentTime ) {
         return momentTime.format( options[ `${type}Format` ] );
      }

      function argumentError( value ) {
         return new TypeError(
            'Expected argument to be a Date object, the string "NOW", or an ISO-8601 string ' +
            `(full, or ${type} as ${inputFormat}), but got "${typeof value}". Value: ${value}`
         );
      }
   };
}

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


Question: // NewDefaultConfig returns a default configuration for the DNSProvider

func NewDefaultConfig() *Config {
	return &Config{
		TTL:                env.GetOrDefaultInt("ALICLOUD_TTL", 600),
		PropagationTimeout: env.GetOrDefaultSecond("ALICLOUD_PROPAGATION_TIMEOUT", dns01.DefaultPropagationTimeout),
		PollingInterval:    env.GetOrDefaultSecond("ALICLOUD_POLLING_INTERVAL", dns01.DefaultPollingInterval),
		HTTPTimeout:        env.GetOrDefaultSecond("ALICLOUD_HTTP_TIMEOUT", 10*time.Second),
	}
}

public function setOption($name, $value) {
		$this->validateName($name);
		$this->config[$name] = $value;
	}

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