Question: // RegisterCommands registers all CLI commands

func (c *CLI) RegisterCommands() {
	// backup
	c.Command("backup", "see most recent backups", func(cmd *cli.Cmd) {
		cmd.Command("list", "lists backups", backupsList)
	})

	// dns
	c.Command("dns", "modify DNS", func(cmd *cli.Cmd) {
		cmd.Command("domain", "show and change DNS domains", func(cmd *cli.Cmd) {
			cmd.Command("create", "create a DNS domain", dnsDomainCreate)
			cmd.Command("delete", "delete a DNS domain", dnsDomainDelete)
			cmd.Command("list", "list all DNS domains", dnsDomainList)
		})
		cmd.Command("record", "show and change DNS records", func(cmd *cli.Cmd) {
			cmd.Command("create", "create a DNS record", dnsRecordCreate)
			cmd.Command("update", "update a DNS record", dnsRecordUpdate)
			cmd.Command("delete", "delete a DNS record", dnsRecordDelete)
			cmd.Command("list", "list all DNS records", dnsRecordList)
		})
	})

	// firewall
	c.Command("firewall", "modify firewall groups and rules", func(cmd *cli.Cmd) {
		cmd.Command("group", "show and change firewall groups", func(cmd *cli.Cmd) {
			cmd.Command("create", "create a firewall group", firewallGroupCreate)
			cmd.Command("delete", "delete a firewall group", firewallGroupDelete)
			cmd.Command("set-description", "set firewall group description", firewallGroupSetDescription)
			cmd.Command("list", "list all firewall groups", firewallGroupList)
		})
		cmd.Command("rule", "show and change firewall rules", func(cmd *cli.Cmd) {
			cmd.Command("create", "create a firewall rule", firewallRuleCreate)
			cmd.Command("delete", "delete a firewall rule", firewallRuleDelete)
			cmd.Command("list", "list all firewall rules in a group", firewallRuleList)
		})
	})

	// info
	c.Command("info", "display account information", accountInfo)

	// iso
	c.Command("iso", "list all ISOs currently available on account", isoList)

	// os
	c.Command("os", "list all available operating systems", osList)

	// applications
	c.Command("apps", "list all available applications", appList)

	// plans
	c.Command("plans", "list all active plans", planList)

	// regions
	c.Command("regions", "list all active regions", regionList)

	// sshkeys
	c.Command("sshkey", "modify SSH public keys", func(cmd *cli.Cmd) {
		cmd.Command("create", "upload and add new SSH public key", sshKeysCreate)
		cmd.Command("update", "update an existing SSH public key", sshKeysUpdate)
		cmd.Command("delete", "remove an existing SSH public key", sshKeysDelete)
		cmd.Command("list", "list all existing SSH public keys", sshKeysList)
	})
	c.Command("sshkeys", "list all existing SSH public keys", sshKeysList)

	// ssh
	c.Command("ssh", "ssh into a virtual machine", sshServer)

	// servers
	c.Command("server", "modify virtual machines", func(cmd *cli.Cmd) {
		cmd.Command("backup", "get and set backup schedules", func(cmd *cli.Cmd) {
			cmd.Command("get", "get a backup schedule", serversBackupGetSchedule)
			cmd.Command("set", "set a backup schedule", serversBackupSetSchedule)
		})
		cmd.Command("create", "create a new virtual machine", serversCreate)
		cmd.Command("rename", "rename a virtual machine", serversRename)
		cmd.Command("tag", "tag a virtual machine", serversTag)
		cmd.Command("start", "start a virtual machine (restart if already running)", serversStart)
		cmd.Command("halt", "halt a virtual machine (hard power off)", serversHalt)
		cmd.Command("reboot", "reboot a virtual machine (hard reboot)", serversReboot)
		cmd.Command("reinstall", "reinstall OS on a virtual machine (all data will be lost)", serversReinstall)
		cmd.Command("os", "show and change OS on a virtual machine", func(cmd *cli.Cmd) {
			cmd.Command("change", "change operating system of virtual machine (all data will be lost)", serversChangeOS)
			cmd.Command("list", "show a list of operating systems to which can be changed to", serversListOS)
		})
		cmd.Command("app", "show and change application on a virtual machine", func(cmd *cli.Cmd) {
			cmd.Command("change", "change application of virtual machine (all data will be lost)", serversChangeApplication)
			cmd.Command("list", "show a list of available applications to which can be changed to", serversListApplications)
			cmd.Command("info", "retrieves application information of virtual machine", serversAppInfo)
		})
		cmd.Command("iso", "attach/detach ISO of a virtual machine", func(cmd *cli.Cmd) {
			cmd.Command("attach", "attach ISO to a virtual machine (server will hard reboot)", serversAttachISO)
			cmd.Command("detach", "detach ISO from a virtual machine (server will hard reboot)", serversDetachISO)
			cmd.Command("status", "show status of ISO attached to a virtual machine", serversStatusISO)
		})
		cmd.Command("restore", "restore from backup/snapshot", func(cmd *cli.Cmd) {
			cmd.Command("backup", "restore from backup (any data already on the server will be lost)", serversRestoreBackup)
			cmd.Command("snapshot", "restore from snapshot (any data already on the server will be lost)", serversRestoreSnapshot)
		})
		cmd.Command("delete", "delete a virtual machine", serversDelete)
		cmd.Command("bandwidth", "list bandwidth used by a virtual machine", serversBandwidth)
		cmd.Command("list", "list all active or pending virtual machines on current account", serversList)
		cmd.Command("show", "show detailed information of a virtual machine", serversShow)
		// ip information
		cmd.Command("list-ipv4", "list IPv4 information of a virtual machine", ipv4List)
		cmd.Command("create-ipv4", "add a new IPv4 address to a virtual machine", ipv4Create)
		cmd.Command("delete-ipv4", "remove IPv4 address from a virtual machine", ipv4Delete)
		cmd.Command("list-ipv6", "list IPv6 information of a virtual machine", ipv6List)
		// reverse dns
		cmd.Command("reverse-dns", "modify reverse DNS entries", func(cmd *cli.Cmd) {
			cmd.Command("default-ipv4", "reset IPv4 reverse DNS entry back to original setting", reverseIpv4Default)
			cmd.Command("set-ipv4", "set IPv4 reverse DNS entry", reverseIpv4Set)
			cmd.Command("set-ipv6", "set IPv6 reverse DNS entry", reverseIpv6Set)
			cmd.Command("delete-ipv6", "delete IPv6 reverse DNS entry", reverseIpv6Delete)
			cmd.Command("list-ipv6", "list IPv6 reverse DNS entries of a virtual machine", reverseIpv6List)
		})
		// firewall groups
		cmd.Command("set-firewall-group", "set firewall group of a virtual machine", serversSetFirewallGroup)
		cmd.Command("unset-firewall-group", "remove virtual machine from firewall group", serversUnsetFirewallGroup)
		// upgrade plans
		cmd.Command("upgrade-plan", "upgrade plan of a virtual machine", func(cmd *cli.Cmd) {
			cmd.Command("change", "upgrade plan of virtual machine (Note: Downgrading is currently not supported. Shrinking the hard disk is not possible without risking data loss.)", serversChangePlan)
			cmd.Command("list", "show a list of VPSPLANIDs to which a virtual machine can be upgraded to", serversListUpgradePlans)
		})
	})
	c.Command("servers", "list all active or pending virtual machines on current account", serversList)

	// block storage
	c.Command("storage", "modify block storage", func(cmd *cli.Cmd) {
		cmd.Command("create", "create new block storage", blockStorageCreate)
		cmd.Command("resize", "resize existing block storage", blockStorageResize)
		cmd.Command("label", "rename existing block storage", blockStorageLabel)
		cmd.Command("attach", "attach block storage to virtual machine", blockStorageAttach)
		cmd.Command("detach", "detach block storage from virtual machine", blockStorageDetach)
		cmd.Command("delete", "remove block storage", blockStorageDelete)
		cmd.Command("list", "list all block storage", blockStorageList)
	})
	c.Command("storages", "list all block storage", blockStorageList)

	// snapshots
	c.Command("snapshot", "modify snapshots", func(cmd *cli.Cmd) {
		cmd.Command("create", "create a snapshot from an existing virtual machine", snapshotsCreate)
		cmd.Command("delete", "delete a snapshot", snapshotsDelete)
		cmd.Command("list", "list all snapshots on current account", snapshotsList)
	})
	c.Command("snapshots", "list all snapshots on current account", snapshotsList)

	// startup scripts
	c.Command("script", "modify startup scripts", func(cmd *cli.Cmd) {
		cmd.Command("create", "create a new startup script", scriptsCreate)
		cmd.Command("update", "update an existing startup script", scriptsUpdate)
		cmd.Command("delete", "remove an existing startup script", scriptsDelete)
		cmd.Command("list", "list all startup scripts on current account", scriptsList)
		cmd.Command("show", "show complete startup script", scriptsShow)
	})
	c.Command("scripts", "list all startup scripts on current account", scriptsList)

	// reserved ips
	c.Command("reservedip", "modify reserved IPs", func(cmd *cli.Cmd) {
		cmd.Command("attach", "attach reserved IP to an existing virtual machine", reservedIPAttach)
		cmd.Command("convert", "convert existing IP on a virtual machine to a reserved IP", reservedIPConvert)
		cmd.Command("create", "create new reserved IP", reservedIPCreate)
		cmd.Command("delete", "delete reserved IP from your account", reservedIPDestroy)
		cmd.Command("detach", "detach reserved IP from an existing virtual machine", reservedIPDetach)
		cmd.Command("list", "list all active reserved IPs on current account", reservedIPList)
	})
	c.Command("reservedips", "list all active reserved IPs on current account", reservedIPList)

	// version
	c.Command("version", "vultr CLI version", func(cmd *cli.Cmd) {
		cmd.Action = func() {
			lengths := []int{24, 48}
			tabsPrint(columns{"Client version:", vultr.Version}, lengths)
			tabsPrint(columns{"Vultr API endpoint:", vultr.DefaultEndpoint}, lengths)
			tabsPrint(columns{"Vultr API version:", vultr.APIVersion}, lengths)
			tabsPrint(columns{"OS/Arch (client):", fmt.Sprintf("%v/%v", runtime.GOOS, runtime.GOARCH)}, lengths)
			tabsPrint(columns{"Go version:", runtime.Version()}, lengths)
			tabsFlush()
		}
	})
}

def match_config(regex):
    '''

    '''
    if _TRAFFICCTL:
        cmd = _traffic_ctl('config', 'match', regex)
    else:
        cmd = _traffic_line('-m', regex)

    return _subprocess(cmd)

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


Question:
Add an binary resource path to the binary map

@param binRsHandler
the image resources handler
@param resourcePath
the image path

private void addBinaryResourcePath(BinaryResourcesHandler binRsHandler, String resourcePath) {

		try {
			String resultPath = CheckSumUtils.getCacheBustedUrl(resourcePath, rsReaderHandler, jawrConfig);
			binRsHandler.addMapping(resourcePath, resultPath);
			bundleMapping.put(resourcePath, resultPath);
		} catch (IOException e) {
			LOGGER.error("An exception occurs while defining the mapping for the file : " + resourcePath, e);
		} catch (ResourceNotFoundException e) {
			LOGGER.error("Impossible to define the checksum for the resource '" + resourcePath
					+ "'. Unable to retrieve the content of the file.");
		}
	}

public InternalTile paint(InternalTile tile) throws RenderException {
		if (tile.getContentType().equals(VectorTileContentType.URL_CONTENT)) {
			if (urlBuilder != null) {
				if (paintGeometries) {
					urlBuilder.paintGeometries(paintGeometries);
					urlBuilder.paintLabels(false);
					tile.setFeatureContent(urlBuilder.getImageUrl());
				}
				if (paintLabels) {
					urlBuilder.paintGeometries(false);
					urlBuilder.paintLabels(paintLabels);
					tile.setLabelContent(urlBuilder.getImageUrl());
				}
				return tile;
			}
		}
		return tile;
	}

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


Question:
Get the CoRE Link Format if attribute of the resource.

        :return: the CoRE Link Format if attribute

def interface_type(self):

        value = "if="
        lst = self._attributes.get("if")
        if lst is None:
            value = ""
        else:
            value += "\"" + str(lst) + "\""
        return value

private DisplayTypeEvaluator readConfiguration(A_CmsXmlContentValue schemaType, String path) {

        String widgetName = null;
        String widgetConfig = null;
        CmsObject cms = getCmsObject();
        String label = getLabel(schemaType);
        // set the default display type
        DisplayType configuredType = DisplayType.none;
        DisplayType defaultType = DisplayType.none;
        EvaluationRule rule = EvaluationRule.none;
        try {
            WidgetInfo widgetInfo = CmsWidgetUtil.collectWidgetInfo(m_rootContentDefinition, path);
            I_CmsWidget widget = widgetInfo.getWidget();
            I_CmsComplexWidget complexWidget = widgetInfo.getComplexWidget();
            configuredType = widgetInfo.getDisplayType();
            if (configuredType.equals(DisplayType.none) && schemaType.isSimpleType()) {
                // check the type is on the root level of the document, those will be displayed 'wide'
                // the path will always have a leading '/'
                // also in case the label has more than 15 characters, we display 'wide'
                if (isTabRootLevel(path)) {
                    rule = EvaluationRule.rootLevel;
                } else if (label.length() > 15) {
                    rule = EvaluationRule.labelLength;
                } else if ((schemaType.getMinOccurs() == 0)) {
                    rule = EvaluationRule.optional;
                }
            }
            if (widget != null) {
                widgetName = widget.getClass().getName();
                if ((configuredType == DisplayType.column)
                    && !(schemaType.isSimpleType()
                        && (schemaType.getMaxOccurs() == 1)
                        && widget.isCompactViewEnabled())) {
                    // column view is not allowed for this widget
                    configuredType = DisplayType.singleline;
                }
                long timer = 0;
                if (widget instanceof I_CmsADEWidget) {
                    if (CmsContentService.LOG.isDebugEnabled()) {
                        timer = System.currentTimeMillis();
                    }
                    I_CmsADEWidget adeWidget = (I_CmsADEWidget)widget;
                    defaultType = adeWidget.getDefaultDisplayType();
                    widgetName = adeWidget.getWidgetName();
                    widgetConfig = adeWidget.getConfiguration(cms, schemaType, m_messages, m_file, m_locale);
                    if (!adeWidget.isInternal() && !m_widgetConfigurations.containsKey(widgetName)) {
                        CmsExternalWidgetConfiguration externalConfiguration = new CmsExternalWidgetConfiguration(
                            widgetName,
                            adeWidget.getInitCall(),
                            adeWidget.getJavaScriptResourceLinks(cms),
                            adeWidget.getCssResourceLinks(cms));
                        m_widgetConfigurations.put(widgetName, externalConfiguration);
                    }
                    if (CmsContentService.LOG.isDebugEnabled()) {
                        CmsContentService.LOG.debug(
                            Messages.get().getBundle().key(
                                Messages.LOG_TAKE_READING_WIDGET_CONFIGURATION_TIME_2,
                                widgetName,
                                "" + (System.currentTimeMillis() - timer)));
                    }

                }
                m_widgets.add(widget);
            }
            if (complexWidget != null) {
                CmsComplexWidgetData widgetData = complexWidget.getWidgetData(m_cms);
                CmsExternalWidgetConfiguration externalConfig = widgetData.getExternalWidgetConfiguration();
                if (externalConfig != null) {
                    m_widgetConfigurations.put(complexWidget.getName(), externalConfig);
                }
                m_complexWidgets.put(CmsContentService.getAttributeName(schemaType), widgetData);
            }
        } catch (CmsWidgetConfigurationException e) {
            LOG.error(e.getLocalizedMessage(), e);
        } catch (Exception e) {
            // may happen if no widget was set for the value
            CmsContentService.LOG.debug(e.getMessage(), e);
        }

        // remove the leading slash from element path to check visibility
        boolean visible = !m_contentHandler.hasVisibilityHandlers()
            || m_contentHandler.isVisible(cms, schemaType, path.substring(1), m_file, m_locale);
        if (!visible) {
            // set the has invisible flag
            m_hasInvisible = true;
        }
        boolean localeSynchronized = (m_contentHandler.hasSynchronizedElements()
            && m_contentHandler.getSynchronizations().contains(path.substring(1)))
            || schemaType.getTypeName().equals(CmsXmlDynamicCategoryValue.TYPE_NAME);

        boolean dynamicallyLoaded = schemaType instanceof CmsXmlDynamicCategoryValue;

        CmsAttributeConfiguration result = new CmsAttributeConfiguration(
            label,
            getHelp(schemaType),
            widgetName,
            widgetConfig,
            readDefaultValue(schemaType, path),
            configuredType.name(),
            visible,
            localeSynchronized,
            dynamicallyLoaded);
        return new DisplayTypeEvaluator(result, configuredType, defaultType, rule);
    }

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


Question: Check authentication and perform actual API request and relogin if needed

def call(self, method, params=None):
        """"""
        start_time = time()
        self.check_auth()
        self.log(INFO, '[%s-%05d] Calling Zabbix API method "%s"', start_time, self.id, method)
        self.log(DEBUG, '\twith parameters: %s', params)

        try:
            return self.do_request(self.json_obj(method, params=params))
        except ZabbixAPIError as ex:
            if self.relogin_interval and any(i in ex.error['data'] for i in self.LOGIN_ERRORS):
                self.log(WARNING, 'Zabbix API not logged in (%s). Performing Zabbix API relogin', ex)
                self.relogin()  # Will raise exception in case of login error
                return self.do_request(self.json_obj(method, params=params))
            raise  # Re-raise the exception
        finally:
            self.log(INFO, '[%s-%05d] Zabbix API method "%s" finished in %g seconds',
                     start_time, self.id, method, (time() - start_time))

function() {
		try {
			var homeConfig = tsapiService.getHomeConfig();
			return _.some(homeConfig.environments, function(environment) {
			    return environment.oauth.token && environment.oauth.tokenSecret;
			});
		} catch(e) {
			return false;
		}
	}

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


Question:
Render an exception as an HTTP response and send it.

@param  \Exception $e
@return void

protected function renderHttpResponse($e)
    {
        $error = '';
        $errorArray = [];

        if ($this->container['env'] != 'prod') {
            $error = $e;
            if (!is_array($error)) {
                $trace = debug_backtrace();
                $errorArray['message'] = $e;
                $errorArray['file'] = $trace[0]['file'];
                $errorArray['line'] = $trace[0]['line'];
                ob_start();
                debug_print_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
                $e['trace'] = ob_get_clean();
                $error = $errorArray;
            }

            $this->container['eventDispatcher']->dispatch(AppEvent::EXCEPTION, new ExceptionEvent($error, $this->container));
        }

        if ($this->container['env'] == 'prod') {
            $this->container['eventDispatcher']->dispatch(AppEvent::EXCEPTION, new ExceptionEvent($e, $this->container));
        }
    }

public function register() {
		if ( ! $this->vendor ) {
			throw new VendorNotSetException;
		}

		if ( ! $this->version ) {
			throw new VersionNotSetException;
		}

		foreach ( $this->endpoints as $endpoint ) {
			register_rest_route(
				$this->get_namespace(),
				$endpoint->get_route(),
				$endpoint->get_options()
			);
		}
	}

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


Question:
@param string|null $href
@param string|null $text

@return \Spatie\Html\Elements\A

public function a($href = null, $contents = null)
    {
        return A::create()
            ->attributeIf($href, 'href', $href)
            ->html($contents);
    }

def link_to_page(page, key, link_options = {})
      css_class = "#{link_options[:class]} #{page == current_page ? 'current' : ''}"
      if key.nil?
        content_tag :span, "..", :class => "spacer"
      elsif page.nil?
        content_tag :span, t(key), :class => "#{css_class} unavailable"
      else
        link_to t(key, :page => page), url_for_page(page), :class => css_class, :alt => view.strip_tags(t(key, :page => page)), :remote => options[:remote], :method => options[:method]
      end
    end

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


Question:
Execute the runnable in the main thread of the underlying RPC endpoint, with
a delay of the given number of milliseconds.

@param runnable Runnable to be executed
@param delay    The delay after which the runnable will be executed

protected void scheduleRunAsync(Runnable runnable, long delay, TimeUnit unit) {
		rpcServer.scheduleRunAsync(runnable, unit.toMillis(delay));
	}

def __send_ready_cb(self, last_send_failure_time):
        """"""
        logger.debug('Readiness notification (last failed=%s)', last_send_failure_time)
        # It is possible for multiple timers to be scheduled (if multiple transport failures happen in a fairly short
        # amount of time. See logic for __send_retry_requests
        if last_send_failure_time is not None:
            self.__send_retry_requests_timer.cancel()
            # allow 10s for responses to come in before attempting to resend
            self.__send_retry_requests_timer = Timer(10, self.__send_retry_requests, args=(last_send_failure_time,))
            self.__send_retry_requests_timer.start()

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


Question:
Removes all the commerce price lists where groupId = ? from the database.

@param groupId the group ID

@Override
	public void removeByGroupId(long groupId) {
		for (CommercePriceList commercePriceList : findByGroupId(groupId,
				QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(commercePriceList);
		}
	}

public function normalizeCmsDatabaseString($string, $spaceSubstitute = '_')
    {
        $string = html_entity_decode($string);

        $string = mb_convert_encoding($string, "ISO-8859-1", 'UTF-8');

        $string = preg_replace('#\s+#', $spaceSubstitute, $string);

        $string = $this->normalizeCmsAccents($string);

        $string = preg_replace('#[^0-9a-z' . preg_quote($spaceSubstitute) . ']#i', '', $string);
        $string = preg_replace('#[' . preg_quote($spaceSubstitute) . ']+#', $spaceSubstitute, $string);

        $string = preg_replace('#\s+#', $spaceSubstitute, $string);

        $string = trim($string, $spaceSubstitute);

        return $string;
    }

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


Question:
Deleta informações extendidas multiplas de uma entidade

@param string $entity
@param array $data

private static function deleteLinkedContent(string $entity, array $data)
    {
        $info = Metadados::getInfo($entity);
        $dic = Metadados::getDicionario($entity);
        if ($info && isset($data['id'])) {

            /*   REMOVE EXTEND MULT  */
            if ($info['extend_mult']) {
                foreach ($info['extend_mult'] as $item) {
                    $read = new Read();
                    $read->exeRead(PRE . $entity . "_" . $dic[$item]['relation'] . "_" . $dic[$item]['column'], "WHERE {$entity}_id = :id", "id={$data['id']}");
                    if ($read->getResult()) {
                        foreach ($read->getResult() as $i)
                            self::deleteExtend($dic[$item]['relation'], $i[$dic[$item]['relation'] . "_id"]);
                    }
                }
            }

            /*   REMOVE EXTEND   */
            if ($info['extend']) {
                foreach ($info['extend'] as $item)
                    self::deleteExtend($dic[$item]['relation'], $data[$dic[$item]['column']]);
            }

            /*   REMOVE SOURCES   */
            foreach ($dic as $id => $c) {
                if ($c['key'] === "source" && !empty($data[$c['column']])) {
                    $read = new Read();
                    $read->exeRead(PRE . $entity, "WHERE id != :id && " . $c['column'] . " = :s", "id={$data['id']}&s={$data[$c['column']]}");
                    if (!$read->getResult() && file_exists(PATH_HOME . $data[$c['column']]))
                        unlink(PATH_HOME . $data[$c['column']]);
                }
            }
        }
    }

public function curlDELETE($curlUrl)
  {

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $curlUrl);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
      'Accept: application/json',
      'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    $jsonResult = curl_exec($ch);
    $results[0] = json_decode($jsonResult);
    $results[1] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);

    $this->statHat->ezCount('MB_Toolbox: MB_Toolbox_cURL: curlDELETE', 1);

    return $results;
  }

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


Question: // ClientWithDownloadServiceToken facilitates creating a client and setting service auth

func ClientWithDownloadServiceToken(c common.RCHTTPClienter, token string) common.RCHTTPClienter {
	if c == nil {
		c = NewClient()
	}
	c.SetDownloadServiceToken(token)
	return c
}

public function download($media_id)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?'.$this->access_token.'&media_id='.$media_id;

        return $this->curl->get($url);
    }

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


Question:
Set the subject of the message
@param string $subject

public function setSubject($subject)
    {
        $node = $this->getSubject(false);
        if(!$node){
            $node = $this->createElement('subject');
            $this->doc->appendChild($node);
        }
        $node->nodeValue = htmlspecialchars($subject);
    }

protected void setEmailBox() {

        m_sendEmail.setEnabled(
            !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword1())
                | !CmsStringUtil.isEmptyOrWhitespaceOnly(m_pw.getPassword2()));
    }

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


Question: collect all split/concatenation nodes and group them by target interface

def mergeSplitsOnInterfaces(root: LNode):

    for ch in root.children:
        if ch.children:
            mergeSplitsOnInterfaces(ch)

    ctx = MergeSplitsOnInterfacesCtx()
    for ch in root.children:
        srcPorts = None
        try:
            if ch.name == "CONCAT":
                p = single(ch.east, lambda x: True)
                e = single(p.outgoingEdges, lambda x: True)
                srcPorts = e.dsts
            elif ch.name == "SLICE":
                p = single(ch.west, lambda x: True)
                e = single(p.incomingEdges, lambda x: True)
                srcPorts = e.srcs
        except (DuplicitValueExc, NoValueExc):
            continue

        if srcPorts is not None:
            for srcPort in srcPorts:
                if isinstance(srcPort.parent, LPort):
                    # only for non primitive ports
                    rootPort = getRootIntfPort(srcPort)
                    ctx.register(rootPort, ch, e)

    # join them if it is possible
    for srcPort, splitsAndConcats in ctx.iterPortSplits():
        if len(splitsAndConcats) <= 1:
            continue

        name = "SPLIT" if srcPort.direction == PortType.OUTPUT else "CONCAT"
        newSplitNode = root.addNode(name)
        copyPort(srcPort, newSplitNode, True, "")
        n = splitsAndConcats[0][0]
        for i in range(max(len(n.west),
                           len(n.east))):
            copyPort(
                srcPort, newSplitNode,
                False, "[%d]" % i)

        reconnectPorts(root, srcPort, splitsAndConcats,
                       newSplitNode)

func (s *Server) verifyNICsWithConfigFile(nics map[string]device, reader func(string) ([]byte, error)) error {
	netName, err := checkBridgeConfigFile(reader)
	if err != nil {
		return errors.Trace(err)
	}

	checked := make([]string, 0, len(nics))
	for name, nic := range nics {
		checked = append(checked, name)

		if nic["parent"] != netName {
			continue
		}
		if !isValidNICType(nic) {
			continue
		}

		logger.Tracef("found usable network device %q with parent %q", name, netName)
		s.localBridgeName = netName
		return nil
	}

	return errors.Errorf("no network device found with nictype %q or %q that uses the configured bridge in %s"+
		"\n\tthe following devices were checked: %v", nicTypeBridged, nicTypeMACVLAN, BridgeConfigFile, checked)
}

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


Question: Apply attribute 4 as argument to a function and return a new tuple with the substituted argument.

public final <U4> Tuple4<T1, T2, T3, U4> map4(Function<? super T4, ? extends U4> function) {
        return Tuple.tuple(v1, v2, v3, function.apply(v4));
    }

def parse_record(self, node):

        if self.current_simulation == None:
            self.raise_error('<Record> must be only be used inside a ' +
                             'simulation specification')

        if 'quantity' in node.lattrib:
            quantity = node.lattrib['quantity']
        else:
            self.raise_error('<Record> must specify a quantity.')

        scale = node.lattrib.get('scale', None)
        color  = node.lattrib.get('color', None)
        id  = node.lattrib.get('id', None)

        self.current_simulation.add_record(Record(quantity, scale, color, id))

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


Question:
Construct a CLI boolean parameter from a {@link BooleanParamDef}.

@param def BooleanParamDef to construct a CLI boolean parameter from.
@return A CLI boolean parameter constructed from the BooleanParamDef.

public static BooleanCliParam fromDef(BooleanParamDef def) {
        return new BooleanCliParam(def.getIdentifier(), def.getDefaultValueSupplier(), def.isNullable());
    }

def parse_args():
    """"""
    parser = argparse.ArgumentParser(
        description='Check kafka current status',
    )
    parser.add_argument(
        "--cluster-type",
        "-t",
        dest='cluster_type',
        required=True,
        help='Type of cluster',
        default=None,
    )
    parser.add_argument(
        "--cluster-name",
        "-c",
        dest='cluster_name',
        help='Name of the cluster',
    )
    parser.add_argument(
        '--discovery-base-path',
        dest='discovery_base_path',
        type=str,
        help='Path of the directory containing the <cluster_type>.yaml config',
    )
    parser.add_argument(
        "--broker-id",
        help='The broker id where the check is running. Set to -1 if you use automatic '
        'broker ids, and it will read the id from data-path instead. This parameter is '
        'required only in case controller-only or first-broker-only are used.',
        type=convert_to_broker_id,
    )
    parser.add_argument(
        "--data-path",
        help='Path to the Kafka data folder.',
    )
    parser.add_argument(
        '--controller-only',
        action="store_true",
        help='If this parameter is specified, it will do nothing and succeed on '
        'non-controller brokers. Default: %(default)s',
    )
    parser.add_argument(
        '--first-broker-only',
        action='store_true',
        help='If specified, the command will only perform the check if '
        'broker_id is the lowest broker id in the cluster. If it is not the lowest, '
        'it will not perform any check and succeed immediately. '
        'Default: %(default)s',
    )
    parser.add_argument(
        '-v',
        '--verbose',
        help='print verbose execution information. Default: %(default)s',
        action="store_true",
        default=False,
    )
    parser.add_argument(
        '-j',
        '--json',
        help='Print output in json format. Default: %(default)s',
        action="store_true",
        default=False,
    )

    subparsers = parser.add_subparsers()
    MinIsrCmd().add_subparser(subparsers)
    ReplicaUnavailabilityCmd().add_subparser(subparsers)
    ReplicationFactorCmd().add_subparser(subparsers)
    OfflineCmd().add_subparser(subparsers)

    return parser.parse_args()

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


Question:
Get all nodes matching an XPath query.

@param string $path
@return QuiteSimpleXMLElement[]

public function xpath($path)
    {
        return array_map(function ($el) {
            return new QuiteSimpleXMLElement($el, $this);
        }, $this->el->xpath($path));
    }

protected function loadSettings() {
		$folder = realpath(__DIR__);
		$segments = explode('/', $folder);
		$file = NULL;
		while (NULL === $file && 0 < count($segments) && ($segment = array_pop($segments))) {
			$base = '/' . implode('/', $segments) . '/' . $segment . '/';
			$expectedFile = $base . $this->settingsFile;
			$expectedFile = FALSE === file_exists($expectedFile) ? $base . 'Settings.yml' : $expectedFile;
			$file = TRUE === file_exists($expectedFile) ? $expectedFile : NULL;
		}
		return (array) (TRUE === file_exists($file) ? Yaml::parse(file_get_contents($file)) : array());
	}

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


Question: Note: There is an assumption here...and it is that the argument's length >= 4

function _singularize($table)
	{

		if (!ADODB_Active_Record::$_changeNames) {
		return $table;
	}
		$ut = strtoupper($table);
		if(isset(self::$WeIsI[$ut])) {
			return $table;
		}
		if(isset(self::$IrregularS[$ut])) {
			return self::$IrregularS[$ut];
		}
		$len = strlen($table);
		if($ut[$len-1] != 'S') {
			return $table; // I know...forget oxen
		}
		if($ut[$len-2] != 'E') {
			return substr($table, 0, $len-1);
		}
		switch($ut[$len-3]) {
			case 'S':
			case 'X':
				return substr($table, 0, $len-2);
			case 'I':
				return substr($table, 0, $len-3) . 'y';
			case 'H';
				if($ut[$len-4] == 'C' || $ut[$len-4] == 'S') {
					return substr($table, 0, $len-2);
				}
			default:
				return substr($table, 0, $len-1); // ?
		}
	}

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: Parse package code.

def parse_package(self, inputstring, addhash=True):
        """"""
        if addhash:
            use_hash = self.genhash(True, inputstring)
        else:
            use_hash = None
        return self.parse(inputstring, self.file_parser, {"nl_at_eof_check": True}, {"header": "package", "use_hash": use_hash})

@Override
	public EClass getIfcGeometricSet() {
		if (ifcGeometricSetEClass == null) {
			ifcGeometricSetEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI)
					.getEClassifiers().get(306);
		}
		return ifcGeometricSetEClass;
	}

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


Question:
Get all of the assets of the type $assetTypes that are used in the Entry
that matches the $url

@param string   $url
@param array    $assetTypes
@param int|null $siteId

@return array

public function getUrlAssetUrls($url, array $assetTypes = ['image'], $siteId = null): array
    {
        $devMode = Craft::$app->getConfig()->getGeneral()->devMode;
        $cache = Craft::$app->getCache();

        // Extract a URI from the URL
        $uri = parse_url($url, PHP_URL_PATH);
        $uri = ltrim($uri, '/');
        // Set up our cache criteria
        $cacheKey = $this->getCacheKey($this::ROUTEMAP_ASSET_URLS, [$uri, $assetTypes, $siteId]);
        $duration = $devMode ? $this::DEVMODE_ROUTEMAP_CACHE_DURATION : $this::ROUTEMAP_CACHE_DURATION;
        $dependency = new TagDependency([
            'tags' => [
                $this::ROUTEMAP_CACHE_TAG,
            ],
        ]);

        // Just return the data if it's already cached
        $assetUrls = $cache->getOrSet($cacheKey, function () use ($uri, $assetTypes, $siteId) {
            Craft::info(
                'Route Map cache miss: '.$uri,
                __METHOD__
            );
            $resultingAssetUrls = [];

            // Find the element that matches this URI
            $element = Craft::$app->getElements()->getElementByUri($uri, $siteId, true);
            /** @var  $element Entry */
            if ($element) {
                // Iterate any Assets fields for this entry
                $assetFields = FieldHelper::fieldsOfType($element, AssetsField::class);
                foreach ($assetFields as $assetField) {
                    $assets = $element[$assetField]->all();
                    /** @var Asset[] $assets */
                    foreach ($assets as $asset) {
                        /** @var $asset Asset */
                        if (\in_array($asset->kind, $assetTypes, true)
                            && !\in_array($asset->getUrl(), $resultingAssetUrls, true)) {
                            $resultingAssetUrls[] = $asset->getUrl();
                        }
                    }
                }
                // Iterate through any Assets embedded in Matrix fields
                $matrixFields = FieldHelper::fieldsOfType($element, MatrixField::class);
                foreach ($matrixFields as $matrixField) {
                    $matrixBlocks = $element[$matrixField]->all();
                    /** @var MatrixBlock[] $matrixBlocks */
                    foreach ($matrixBlocks as $matrixBlock) {
                        $assetFields = FieldHelper::matrixFieldsOfType($matrixBlock, AssetsField::class);
                        foreach ($assetFields as $assetField) {
                            foreach ($matrixBlock[$assetField] as $asset) {
                                /** @var $asset Asset */
                                if (\in_array($asset->kind, $assetTypes, true)
                                    && !\in_array($asset->getUrl(), $resultingAssetUrls, true)) {
                                    $resultingAssetUrls[] = $asset->getUrl();
                                }
                            }
                        }
                    }
                }
            }

            return $resultingAssetUrls;
        }, $duration, $dependency);

        return $assetUrls;
    }

public function parseRoute($routeSpec)
    {
        $path           = isset($routeSpec['path']) ? $routeSpec['path'] : null;
        $methods        = isset($routeSpec['methods']) ? $routeSpec['methods'] : array();
        $controller     = isset($routeSpec['controller']) ? $routeSpec['controller'] : null;
        $calls          = isset($routeSpec['calls']) ? $routeSpec['calls'] : null;
        $requirements   = isset($routeSpec['requirements']) ? $routeSpec['requirements'] : array();
        $regex          = isset($routeSpec['path']) ? $routeSpec['path'] : null;

        $route = new Route($path, $methods, $controller, $calls, $requirements, $regex);

        return $route;
    }

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


Question:
An LRU cache, used for caching {@link ChainEntry}s.
@alias module:utils.LRU
@constructor
@param {Number} capacity
@param {Function?} getSize

function LRU(capacity, getSize) {
  if (!(this instanceof LRU))
    return new LRU(capacity, getSize);

  this.map = new Map();
  this.size = 0;
  this.items = 0;
  this.head = null;
  this.tail = null;
  this.pending = null;

  assert(typeof capacity === 'number', 'Capacity must be a number.');
  assert(capacity >= 0, 'Capacity cannot be negative.');
  assert(!getSize || typeof getSize === 'function', 'Bad size callback.');

  this.capacity = capacity;
  this.getSize = getSize;
}

def transformer_moe_8k():
  """"""
  hparams = transformer_moe_base()

  hparams.batch_size = 8192
  hparams.max_length = 0  # max_length == batch_size
  hparams.eval_drop_long_sequences = True
  hparams.min_length_bucket = 256  # Avoid cyclic problems for big batches

  hparams.default_ff = "sep"
  hparams.hidden_size = 1024

  return hparams

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


Question: Creates service info with the given service name.

@VisibleForTesting
  static ServiceInfo getServiceInfo(String serviceName) {
    return ServiceInfo.newBuilder().setName(serviceName).build();
  }

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

        return $this->trashService;
    }

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


Question: load the rules from file

def load_rules(self):

        self.maps = []
        with open(self.map_file, 'r') as f:
            for line in f:
                if line.strip(' ')[0:1] != '#':
                    rule = MapRule(line)
                    #print('rule = ', rule)
                    self.maps.append(rule)

func (s *CreateAppInput) SetCustomRules(v []*CustomRule) *CreateAppInput {
	s.CustomRules = v
	return s
}

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


Question: // SetLanguageCode sets the LanguageCode field's value.

func (s *SynthesisTask) SetLanguageCode(v string) *SynthesisTask {
	s.LanguageCode = &v
	return s
}

def _find_lang(langdict, lang, script, region):
    """"""
    # Check if we should map this to a different locale.
    full_locale = _full_locale(lang, script, region)
    if (full_locale in _LOCALE_NORMALIZATION_MAP and
        _LOCALE_NORMALIZATION_MAP[full_locale] in langdict):
        return langdict[_LOCALE_NORMALIZATION_MAP[full_locale]]
    # First look for the full locale
    if full_locale in langdict:
        return langdict[full_locale]
    # Then look for lang, script as a combination
    if script is not None:
        lang_script = "%s_%s" % (lang, script)
        if lang_script in langdict:
            return langdict[lang_script]
    # Next look for lang, region as a combination
    if region is not None:
        lang_region = "%s_%s" % (lang, region)
        if lang_region in langdict:
            return langdict[lang_region]
    # Fall back to bare language code lookup
    if lang in langdict:
        return langdict[lang]
    # Possibly fall back to english
    if _may_fall_back_to_english(lang):
        return langdict.get("en", None)
    else:
        return None

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


Question:
Delete current Entity
@return \Orion\Utils\HttpRequest

public function delete() {
        $url = "entities";

        if ($this->_id) {
            $url .= "/{$this->_id}";
        }

        if ($this->_type) {
            $url .= "?type={$this->_type}";
        }

        return $this->_orion->delete($url);
    }

public function terminate(Request $request, Response $response)
    {
        $event = new PostResponseEvent($this, $request, $response);
        $this->getDispatcher()->dispatch(KernelEvents::TERMINATE, $event);
    }

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


Question: // XXX_OneofFuncs is for the internal use of the proto package.

func (*SchemaItem) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _SchemaItem_OneofMarshaler, _SchemaItem_OneofUnmarshaler, _SchemaItem_OneofSizer, []interface{}{
		(*SchemaItem_Schema)(nil),
		(*SchemaItem_FileSchema)(nil),
	}
}

private void createFunction(String name, GeometryFunction function) {
		try {
			Function.create(getGeoPackage().getConnection().getConnection(),
					name, function);
		} catch (SQLException e) {
			log.log(Level.SEVERE, "Failed to create function: " + name, e);
		}
	}

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


Question:
Retrieves grid columns configuration using the modelClass.
@param Model $model
@param array $fields
@return array grid columns

public static function getGridColumns($model, $fields)
    {
        if (!$model instanceof ActiveRecord) {
            return $model->attributes();
        }

        /** @var ActiveRecord $model */
        list($behaviorAttributes, $blameableAttributes) = self::getModelBehaviorAttributes($model);
        /** @var LabelsBehavior $labelsBehavior */
        $labelsBehavior = $model->getBehavior('labels');
        $versionAttribute = $model->optimisticLock();
        $formats = $model->attributeFormats();
        $keys    = self::getModelKeys($model);

        $columns = [];
        foreach ($fields as $key => $field) {
            // for arrays and callables, don't generate the column, use the one provided
            if (is_array($field)) {
                $columns[$key] = $field;
                continue;
            } elseif (!is_string($field) && is_callable($field)) {
                $columns[$key] = call_user_func($field, $model);
                continue;
            }
            // if the field is from a relation (eg. client.firstname) treat it as an attribute
            $format = isset($formats[$field]) ? $formats[$field] : $model->getAttributeFormat($field);
            if ($format === 'paragraphs') {
                $format = 'shortText';
            }
            if ($format !== null) {
                if ((in_array($field, $keys)
                        && ($labelsBehavior === null || !in_array($field, $labelsBehavior->attributes)))
                    || in_array($field, $behaviorAttributes)
                    || $field === $versionAttribute
                ) {
                    continue;
                }
                if (in_array($field, $labelsBehavior->attributes)) {
                    $columns[] = static::getLinkedColumn($model, $field);
                    continue;
                }
                $columns[] = static::getAttributeColumn($model, $field, $format);
                continue;
            }

            $relation = $model->getRelation($field);
            foreach ($relation->link as $left => $right) {
                if (in_array($right, $blameableAttributes)) {
                    continue 2;
                }
            }

            if (!Yii::$app->user->can($relation->modelClass . '.read')) {
                continue;
            }
            $columns[] = static::getRelationColumn($model, $field, $relation);
        }

        return $columns;
    }

public function render(FormInterface $form, $isHorizontal = false, $labelColumns = 2)
    {
        $this->isHorizontal = (bool) $isHorizontal;
        $this->labelColumns = (int) $labelColumns;

        $this->setHorizontal($form, $this->isHorizontal);

        if (method_exists($form, 'prepare')) {
            $form->prepare();
        }

        $formContent = '';

        $buttons = [];

        foreach ($form as $element) {
            if ($element instanceof Button || $element instanceof Submit) {
                $buttons[] = $element;
                continue;
            } elseif ($element instanceof FieldsetInterface) {
                $formContent .= $this->view->plugin('losFormCollection')->render($element);
            } else {
                $formContent .= $this->view->plugin('losFormRow')->render(
                    $element,
                    $this->isHorizontal,
                    $this->labelColumns
                );
            }
        }

        if (count($buttons) > 0) {
            $formContent .= $this->view->plugin('losFormRow')->renderButtons(
                $buttons,
                $this->isHorizontal,
                $this->labelColumns
            );
        }

        return $this->openTag($form).$formContent.$this->closeTag();
    }

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


Question:
// SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands.
// The user should not have a cyclic dependency on commands.

func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName) {
	c.Flags().SetNormalizeFunc(n)
	c.PersistentFlags().SetNormalizeFunc(n)
	c.globNormFunc = n

	for _, command := range c.commands {
		command.SetGlobalNormalizationFunc(n)
	}
}

func NewCmdRolloutRestart(f cmdutil.Factory, streams genericclioptions.IOStreams) *cobra.Command {
	o := NewRolloutRestartOptions(streams)

	validArgs := []string{"deployment"}

	cmd := &cobra.Command{
		Use:                   "restart RESOURCE",
		DisableFlagsInUseLine: true,
		Short:                 i18n.T("Restart a resource"),
		Long:                  restartLong,
		Example:               restartExample,
		Run: func(cmd *cobra.Command, args []string) {
			cmdutil.CheckErr(o.Complete(f, cmd, args))
			cmdutil.CheckErr(o.Validate())
			cmdutil.CheckErr(o.RunRestart())
		},
		ValidArgs: validArgs,
	}

	usage := "identifying the resource to get from a server."
	cmdutil.AddFilenameOptionFlags(cmd, &o.FilenameOptions, usage)
	o.PrintFlags.AddFlags(cmd)
	return cmd
}

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


Question:
Take care of those loop headers/tails where we manually broke their
        connection to the next BBL

def _pd_post_process(self, cfg):

        loop_back_edges = self._cfg.get_loop_back_edges()

        for b1, b2 in loop_back_edges:
            # The edge between b1 and b2 is manually broken
            # The post dominator of b1 should be b2 (or not?)

            successors = list(self._pd_graph_successors(cfg, b1))

            if len(successors) == 0:
                if b2 in self._post_dom:
                    self._post_dom.add_edge(b1, b2)
                else:
                    _l.debug("%s is not in post dominator dict.", b2)

func (o *Enterprise) SyslogDestinations(info *bambou.FetchingInfo) (SyslogDestinationsList, *bambou.Error) {

	var list SyslogDestinationsList
	err := bambou.CurrentSession().FetchChildren(o, SyslogDestinationIdentity, &list, info)
	return list, err
}

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


Question:
Getting user data on POST call

@return mixed

protected function getInputData()
    {
        (new HCCountriesValidator())->validateForm();

        $_data = request()->all();

        array_set($data, 'languages', array_get($_data, 'languages'));

        return $data;
    }

public function hasGetPostParamValue($name, $ignoreCase = false)
    {
        $param = $this->hasGetParamValue($name, $ignoreCase);
        if ($param !== null)
        {
            return $param;
        }
        else
        {
            return $this->hasPostParamValue($name, $ignoreCase);
        }
    }

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


Question: Returns either a custom timeout for the given service, or a default

def get_timeout(service):

    custom_timeout_key = "RESTCLIENTS_%s_TIMEOUT" % service.upper()
    if hasattr(settings, custom_timeout_key):
        return getattr(settings, custom_timeout_key)

    default_key = "RESTCLIENTS_DEFAULT_TIMEOUT"
    if hasattr(settings, default_key):
        return getattr(settings, default_key)

    return OLD_DEFAULT_TIMEOUT

protected void createDefaultDecisionStates(final Flow flow) {
        createServiceUnauthorizedCheckDecisionState(flow);
        createServiceCheckDecisionState(flow);
        createWarnDecisionState(flow);
        createGatewayRequestCheckDecisionState(flow);
        createHasServiceCheckDecisionState(flow);
        createRenewCheckActionState(flow);
    }

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


Question:
Parses error pages out of web.xml.

@param errorPageType errorPageType element from web.xml
@param webApp        model for web.xml

private static void parseErrorPages(final ErrorPageType errorPageType, final WebApp webApp) {
		final WebAppErrorPage errorPage = new WebAppErrorPage();
		if (errorPageType.getErrorCode() != null) {
			errorPage.setErrorCode(errorPageType.getErrorCode().getValue().toString());
		}
		if (errorPageType.getExceptionType() != null) {
			errorPage.setExceptionType(errorPageType.getExceptionType().getValue());
		}
		if (errorPageType.getLocation() != null) {
			errorPage.setLocation(errorPageType.getLocation().getValue());
		}
		if (errorPage.getErrorCode() == null && errorPage.getExceptionType() == null) {
			errorPage.setExceptionType(ErrorPageModel.ERROR_PAGE);
		}
		webApp.addErrorPage(errorPage);
	}

def load_from_file(swag_path, swag_type='yml', root_path=None):

    if swag_type not in ('yaml', 'yml'):
        raise AttributeError("Currently only yaml or yml supported")
        # TODO: support JSON

    try:
        enc = detect_by_bom(swag_path)
        with codecs.open(swag_path, encoding=enc) as yaml_file:
            return yaml_file.read()
    except IOError:
        # not in the same dir, add dirname
        swag_path = os.path.join(
            root_path or os.path.dirname(__file__), swag_path
        )
        try:
            enc = detect_by_bom(swag_path)
            with codecs.open(swag_path, encoding=enc) as yaml_file:
                return yaml_file.read()
        except IOError:  # pragma: no cover
            # if package dir
            # see https://github.com/rochacbruno/flasgger/pull/104
            # Still not able to reproduce this case
            # test are in examples/package_example
            # need more detail on how to reproduce IOError here
            swag_path = swag_path.replace("/", os.sep).replace("\\", os.sep)
            path = swag_path.replace(
                (root_path or os.path.dirname(__file__)), ''
            ).split(os.sep)[1:]
            site_package = imp.find_module(path[0])[1]
            swag_path = os.path.join(site_package, os.sep.join(path[1:]))
            with open(swag_path) as yaml_file:
                return yaml_file.read()

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


Question: // generates ListPartsResponse from ListPartsInfo.

func generateListPartsResponse(partsInfo ListPartsInfo, encodingType string) ListPartsResponse {
	listPartsResponse := ListPartsResponse{}
	listPartsResponse.Bucket = partsInfo.Bucket
	listPartsResponse.Key = s3EncodeName(partsInfo.Object, encodingType)
	listPartsResponse.UploadID = partsInfo.UploadID
	listPartsResponse.StorageClass = globalMinioDefaultStorageClass
	listPartsResponse.Initiator.ID = globalMinioDefaultOwnerID
	listPartsResponse.Owner.ID = globalMinioDefaultOwnerID

	listPartsResponse.MaxParts = partsInfo.MaxParts
	listPartsResponse.PartNumberMarker = partsInfo.PartNumberMarker
	listPartsResponse.IsTruncated = partsInfo.IsTruncated
	listPartsResponse.NextPartNumberMarker = partsInfo.NextPartNumberMarker

	listPartsResponse.Parts = make([]Part, len(partsInfo.Parts))
	for index, part := range partsInfo.Parts {
		newPart := Part{}
		newPart.PartNumber = part.PartNumber
		newPart.ETag = "\"" + part.ETag + "\""
		newPart.Size = part.Size
		newPart.LastModified = part.LastModified.UTC().Format(timeFormatAMZLong)
		listPartsResponse.Parts[index] = newPart
	}
	return listPartsResponse
}

def get_result_children(self, result_data):

        specimens, samples, sites, locations = "", "", "", ""
        children = {'specimen': specimens, 'sample': samples,
                    'site': sites, 'location': locations}
        for dtype in children:
            header_name = 'er_' + dtype + '_names'
            if result_data[header_name]:
                children[dtype] = result_data[header_name].split(":")
                # make sure there are no extra spaces in names
                children[dtype] = [child.strip() for child in children[dtype]]

        return children['specimen'], children['sample'], children['site'], children['location']

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


Question: Start a service.

def app_start_service(self, *args) -> None:
        ''''''
        _, error = self._execute('-s', self.device_sn,
                                 'shell', 'am', 'startservice', *args)
        if error and error.startswith('Error'):
            raise ApplicationsException(error.split(':', 1)[-1].strip())

@SuppressWarnings("unchecked")
	public void addBeanContextServicesListener(BeanContextServicesListener listener)
	{
		if (listener == null)
		{
			throw new NullPointerException();
		}
		synchronized (bcsListeners)
		{
			bcsListeners.add(listener);
		}
	}

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


Question:
Unserialize session data
http://www.php.net/manual/en/function.session-decode.php#56106

protected function unserialize($str)
    {
        $str    = (string)$str;
        $endptr = strlen($str);
        $p      = 0;

        $serialized = '';
        $items      = 0;
        $level      = 0;

        while ($p < $endptr) {
            $q = $p;
            while ($str[$q] != '|')
                if (++$q >= $endptr)
                    break 2;

            if ($str[$p] == '!') {
                $p++;
                $has_value = false;
            }
            else {
                $has_value = true;
            }

            $name = substr($str, $p, $q - $p);
            $q++;

            $serialized .= 's:' . strlen($name) . ':"' . $name . '";';

            if ($has_value) {
                for (;;) {
                    $p = $q;
                    switch (strtolower($str[$q])) {
                    case 'n': // null
                    case 'b': // boolean
                    case 'i': // integer
                    case 'd': // decimal
                        do $q++;
                        while ( ($q < $endptr) && ($str[$q] != ';') );
                        $q++;
                        $serialized .= substr($str, $p, $q - $p);
                        if ($level == 0)
                            break 2;
                        break;
                    case 'r': // reference
                        $q+= 2;
                        for ($id = ''; ($q < $endptr) && ($str[$q] != ';'); $q++)
                            $id .= $str[$q];
                        $q++;
                        // increment pointer because of outer array
                        $serialized .= 'R:' . ($id + 1) . ';';
                        if ($level == 0)
                            break 2;
                        break;
                    case 's': // string
                        $q+=2;
                        for ($length=''; ($q < $endptr) && ($str[$q] != ':'); $q++)
                            $length .= $str[$q];
                        $q+=2;
                        $q+= (int)$length + 2;
                        $serialized .= substr($str, $p, $q - $p);
                        if ($level == 0)
                            break 2;
                        break;
                    case 'a': // array
                    case 'o': // object
                        do $q++;
                        while ($q < $endptr && $str[$q] != '{');
                        $q++;
                        $level++;
                        $serialized .= substr($str, $p, $q - $p);
                        break;
                    case '}': // end of array|object
                        $q++;
                        $serialized .= substr($str, $p, $q - $p);
                        if (--$level == 0)
                            break 2;
                        break;
                    default:
                        return false;
                    }
                }
            }
            else {
                $serialized .= 'N;';
                $q += 2;
            }
            $items++;
            $p = $q;
        }

        return unserialize( 'a:' . $items . ':{' . $serialized . '}' );
    }

private function saveToCache($original, $translations)
    {
        $cacheKey = $this->getCacheKey($original);
        $cacheContent = $this->cache->fetch($cacheKey);
        if (is_array($cacheContent)) {
            $cacheContent[$original] = $translations;
        } else {
            $cacheContent = [$original => $translations];
        }

        $this->cache->save($cacheKey, $cacheContent);
    }

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


Question:
jarファイルから対象パッケージ以下のEnumクラスを取得

@param packageName ルートパッケージ名
@param jarFile jarファイル
@return クラスリスト
@throws ClassNotFoundException エラー
@throws IOException

private static Collection<? extends Class<?>> findEnumClassesWithJar(final String packageName, final JarFile jarFile) {
		String resourceName = packageName.replace('.', '/');
		Set<Class<?>> classes = new HashSet<>();
		Collections.list(jarFile.entries()).stream().map(JarEntry::getName)
				.filter(name -> name.startsWith(resourceName)).filter(name -> name.endsWith(".class"))
				.map(name -> name.replace('/', '.').replaceAll(".class$", ""))
				.forEach(className -> loadEnum(className).ifPresent(classes::add));

		return classes;
	}

def shade_jar(self, shading_rules, jar_path):

    self.context.log.debug('Shading {}.'.format(jar_path))
    with temporary_dir() as tempdir:
      output_jar = os.path.join(tempdir, os.path.basename(jar_path))
      with self.shader.binary_shader_for_rules(output_jar, jar_path, shading_rules) as shade_runner:
        result = execute_runner(shade_runner, workunit_factory=self.context.new_workunit,
                                workunit_name='jarjar')
        if result != 0:
          raise TaskError('Shading tool failed to shade {0} (error code {1})'.format(jar_path,
                                                                                result))
        if not os.path.exists(output_jar):
          raise TaskError('Shading tool returned success for {0}, but '
                          'the output jar was not found at {1}'.format(jar_path, output_jar))
        atomic_copy(output_jar, jar_path)
        return jar_path

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


Question: (protected) r = this >> n*DB

function bnpDRShiftTo(n, r) {
  for (var i = n; i < this.t; ++i)
    r[i - n] = this[i];
  r.t = Math.max(this.t - n, 0);
  r.s = this.s;
}

def _downgrade_v1(op):

    # Drop indices before batch
    # This is to prevent index collision when creating the temp table
    op.drop_index('ix_futures_contracts_root_symbol')
    op.drop_index('ix_futures_contracts_symbol')

    # Execute batch op to allow column modification in SQLite
    with op.batch_alter_table('futures_contracts') as batch_op:

        # Rename 'multiplier'
        batch_op.alter_column(column_name='multiplier',
                              new_column_name='contract_multiplier')

        # Delete 'tick_size'
        batch_op.drop_column('tick_size')

    # Recreate indices after batch
    op.create_index('ix_futures_contracts_root_symbol',
                    table_name='futures_contracts',
                    columns=['root_symbol'])
    op.create_index('ix_futures_contracts_symbol',
                    table_name='futures_contracts',
                    columns=['symbol'],
                    unique=True)

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


Question: // SetConfiguration sets the Configuration field's value.

func (s *UpdateCrawlerInput) SetConfiguration(v string) *UpdateCrawlerInput {
	s.Configuration = &v
	return s
}

def save_config(self):
        """"""
        self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy
        self.config_section['enable_vi_bindings'] = self.enable_vi_bindings
        self.config_section['show_completion_columns'] = \
            self.show_completion_columns
        self.config_section['show_help'] = self.show_help
        self.config_section['theme'] = self.theme
        self.config_obj.write()

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


Question:
Set the scope of header cells of table header.

        :param table_header: The table header.
        :type table_header: hatemile.util.html.htmldomelement.HTMLDOMElement

def _prepare_header_cells(self, table_header):

        cells = self.parser.find(table_header).find_children(
            'tr'
        ).find_children('th').list_results()
        for cell in cells:
            self.id_generator.generate_id(cell)

            cell.set_attribute('scope', 'col')

def get_result_children(self, result_data):

        specimens, samples, sites, locations = "", "", "", ""
        children = {'specimen': specimens, 'sample': samples,
                    'site': sites, 'location': locations}
        for dtype in children:
            header_name = 'er_' + dtype + '_names'
            if result_data[header_name]:
                children[dtype] = result_data[header_name].split(":")
                # make sure there are no extra spaces in names
                children[dtype] = [child.strip() for child in children[dtype]]

        return children['specimen'], children['sample'], children['site'], children['location']

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


Question:
/* (non-Javadoc)
@see com.ibm.ws.sib.processor.runtime.SIMPRemoteBrowserReceiverControllable#getBrowseID()

public long getBrowseID()
  {
    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.entry(tc, "getBrowseID");

    long browseID = aoBrowserSession.getKey().getBrowseId();

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled())
      SibTr.exit(tc, "getBrowseID", new Long(browseID));
    return browseID;
  }

public void setProbability(Parameter newProbability) {
		if (newProbability != probability) {
			NotificationChain msgs = null;
			if (probability != null)
				msgs = ((InternalEObject)probability).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.CONTROL_PARAMETERS__PROBABILITY, null, msgs);
			if (newProbability != null)
				msgs = ((InternalEObject)newProbability).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - BpsimPackage.CONTROL_PARAMETERS__PROBABILITY, null, msgs);
			msgs = basicSetProbability(newProbability, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, BpsimPackage.CONTROL_PARAMETERS__PROBABILITY, newProbability, newProbability));
	}

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


Question:
@param string         $methodName
@param StateInterface $fromState

@return IntrospectedTransition
@throws StateNotImplementedException

private function createIntrospectedTransition($methodName, StateInterface $fromState)
    {
        $toState = $this->getToState($fromState, $methodName);

        return new IntrospectedTransition(
            $methodName,
            $this->introspectedStates[$fromState->getKey()],
            $this->introspectedStates[$toState->getKey()]
        );
    }

<L, E extends Input.Impl> void dispatch(
      Class<L> listenerType, E event, Interaction<L, E> interaction, Interaction<L, E> onCancel) {
    dispatch(event.captureState.layer, listenerType, event, interaction, onCancel);
  }

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


Question:
// createBuildCAConfigMapSpec creates a ConfigMap template to hold certificate authorities
// used by the build pod.
// The returned ConfigMap has an owner reference to the provided pod, ensuring proper
// garbage collection.

func (bc *BuildController) createBuildCAConfigMapSpec(build *buildv1.Build, buildPod *corev1.Pod) *corev1.ConfigMap {
	// Create a ConfigMap with the `inject-cabundle` annotation, which tells the service cert signing controller
	// to add the service-ca.crt entry to this map.
	// See https://github.com/openshift/service-serving-cert-signer
	cm := &corev1.ConfigMap{
		ObjectMeta: metav1.ObjectMeta{
			Name: buildapihelpers.GetBuildCAConfigMapName(build),
			OwnerReferences: []metav1.OwnerReference{
				makeBuildPodOwnerRef(buildPod),
			},
			Annotations: map[string]string{
				"service.alpha.openshift.io/inject-cabundle": "true",
			},
		},
		Data: bc.additionalTrustedCAData,
	}

	if cm.Data == nil {
		cm.Data = make(map[string]string)
	}

	return cm
}

func setOpts(opts map[string]string, supportedOpts backendOptions) error {
	errors := 0

	for key, val := range opts {
		opt, ok := supportedOpts[key]
		if !ok {
			errors++
			log.WithField(logfields.Key, key).Error("unknown kvstore configuration key")
			continue
		}

		if opt.validate != nil {
			if err := opt.validate(val); err != nil {
				log.Errorf("invalid value for key %s: %s", key, err)
				errors++
			}
		}

	}

	// if errors have occurred, print the supported configuration keys to
	// the log
	if errors > 0 {
		log.Error("Supported configuration keys:")
		for key, val := range supportedOpts {
			log.Errorf("  %-12s %s", key, val.description)
		}

		return fmt.Errorf("invalid kvstore configuration, see log for details")
	}

	// modify the configuration atomically after verification
	for key, val := range opts {
		supportedOpts[key].value = val
	}

	return nil
}

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


Question:
@param      $contactClientId
@param      $operationId
@param bool $test

@return array

public function flushPreviousAuthTokens($contactClientId, $operationId, $test)
    {
        $q = $this->createQueryBuilder('a');
        $q->delete()
            ->where(
                $q->expr()->eq('a.contactClient', (int) $contactClientId),
                $q->expr()->eq('a.operation', (int) $operationId),
                $q->expr()->eq('a.test', (int) $test)
            );

        return $q->getQuery()->getArrayResult();
    }

private function formatAction(Action $action)
    {
        $info = [
            'envelope' => 'JSON-RPC-2.0',
            'transport' => 'POST',
            'name' => $action->getName(),
            'description' => $action->getDescription(),
            'parameters' => []
        ];

        foreach ($action->getParameters() as $parameter) {
            $parameterInfo = [
                'name' => $parameter->getName(),
                'type' => $parameter->getType(),
                'description' => $parameter->getDescription(),
                'required' => $parameter->isRequired()
            ];

            if (!$parameter->isRequired()) {
                $parameterInfo['default'] = $parameter->getDefault();
            }

            $info['parameters'][] = $parameterInfo;
        }

        if ($action->getResponse()) {
            $response = $action->getResponse();

            $info['response'] = $response->toArray();
        }

        return $info;
    }

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


Question:
// UnspentOutputs returns all unspent received transaction outputs.
// The order is undefined.

func (s *Store) UnspentOutputs(ns walletdb.ReadBucket) ([]Credit, error) {
	var unspent []Credit

	var op wire.OutPoint
	var block Block
	err := ns.NestedReadBucket(bucketUnspent).ForEach(func(k, v []byte) error {
		err := readCanonicalOutPoint(k, &op)
		if err != nil {
			return err
		}
		if existsRawUnminedInput(ns, k) != nil {
			// Output is spent by an unmined transaction.
			// Skip this k/v pair.
			return nil
		}
		err = readUnspentBlock(v, &block)
		if err != nil {
			return err
		}

		blockTime, err := fetchBlockTime(ns, block.Height)
		if err != nil {
			return err
		}
		// TODO(jrick): reading the entire transaction should
		// be avoidable.  Creating the credit only requires the
		// output amount and pkScript.
		rec, err := fetchTxRecord(ns, &op.Hash, &block)
		if err != nil {
			return err
		}
		txOut := rec.MsgTx.TxOut[op.Index]
		cred := Credit{
			OutPoint: op,
			BlockMeta: BlockMeta{
				Block: block,
				Time:  blockTime,
			},
			Amount:       btcutil.Amount(txOut.Value),
			PkScript:     txOut.PkScript,
			Received:     rec.Received,
			FromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),
		}
		unspent = append(unspent, cred)
		return nil
	})
	if err != nil {
		if _, ok := err.(Error); ok {
			return nil, err
		}
		str := "failed iterating unspent bucket"
		return nil, storeError(ErrDatabase, str, err)
	}

	err = ns.NestedReadBucket(bucketUnminedCredits).ForEach(func(k, v []byte) error {
		if existsRawUnminedInput(ns, k) != nil {
			// Output is spent by an unmined transaction.
			// Skip to next unmined credit.
			return nil
		}

		err := readCanonicalOutPoint(k, &op)
		if err != nil {
			return err
		}

		// TODO(jrick): Reading/parsing the entire transaction record
		// just for the output amount and script can be avoided.
		recVal := existsRawUnmined(ns, op.Hash[:])
		var rec TxRecord
		err = readRawTxRecord(&op.Hash, recVal, &rec)
		if err != nil {
			return err
		}

		txOut := rec.MsgTx.TxOut[op.Index]
		cred := Credit{
			OutPoint: op,
			BlockMeta: BlockMeta{
				Block: Block{Height: -1},
			},
			Amount:       btcutil.Amount(txOut.Value),
			PkScript:     txOut.PkScript,
			Received:     rec.Received,
			FromCoinBase: blockchain.IsCoinBaseTx(&rec.MsgTx),
		}
		unspent = append(unspent, cred)
		return nil
	})
	if err != nil {
		if _, ok := err.(Error); ok {
			return nil, err
		}
		str := "failed iterating unmined credits bucket"
		return nil, storeError(ErrDatabase, str, err)
	}

	return unspent, nil
}

function processSort(feed,sort,sortName) {
	if (warnReleaseStatus(sort.release_status)) {
		console.log('Warning: sort '+sortName+' is '+sort.release_status+deprecationInfo(feed,sort.name,'sort',sort.deprecated_since));
	}
	swagSort(sort);
	if (sort.sort_direction) {
		sort.sort_direction = toArray(sort.sort_direction);
		for (var i in sort.sort_direction) {
			var sortDirection = sort.sort_direction[i];
			var sortDirectionName = ('s-'+feed.name+'-'+sort.name+'-'+sortDirection.value).toCamelCase();
			if (seen.indexOf(sortDirectionName)<0) {
				processSortDirection(feed,sort,sortDirection,sortDirectionName);
				seen.push(sortDirectionName);
			}
			else {
				console.log('* Skipping sort '+sortDirectionName+' as duplicate name');
			}
		}
	}
	else {
		if (seen.indexOf(sortName)<0) {
			exportSort(feed,sort,sortName);
			seen.push(sortName);
		}
		else {
			console.log('* Skipping sort '+sortName+' as duplicate name');
		}
	}
}

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


Question:
Gets the last modification user.<p>

@return the last modification user

@Column(header = org.opencms.workplace.commons.Messages.GUI_LABEL_USER_LAST_MODIFIED_0, order = 70)
    public String getUserLastModified() {

        return m_bean.getUserLastModified();
    }

public function permissionSave(Permission $permission)
    {
        if ($permission->permission_id) {
            $query = "
                UPDATE
                    auth_permission
                SET
                    `name` = :name, description = :description, updated_on = " . $this->sql_time_func . "
                WHERE
                    permission_id = :permission_id
            ";
        } else {
            $query = "
                INSERT INTO
                    auth_permission (`name`, description, updated_on, added_on)
                VALUES
                    (:name, :description, " . $this->sql_time_func . ", " . $this->sql_time_func . ")
            ";
        }
        $cur = $this->db->prepare($query);
        $cur->bindParam(":name", $permission->name, PDO::PARAM_STR, 32);
        $cur->bindParam(":description", $permission->description, PDO::PARAM_STR);
        if ($permission->permission_id) {
            $cur->bindParam(":permission_id", $permission->permission_id, PDO::PARAM_INT);
        }
        $this->db->beginTransaction();
        try {
            $cur->execute();
            if (!$permission->permission_id) {
                $permission->permission_id = $this->db->lastInsertId();
            }
            $this->db->commit();
        } catch (PDOException $db_err) {
            $this->db->rollBack();
            if ($this->logger) {
                $this->logger->error("Failed to create/update permission", ['exception' => $db_err]);
            }
            return false;
        }
        return true;
    }

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


Question:
This method overrides the superclass to set default values into
            the parameter dictionary, in case empty entries are provided.

def setInstrumentParameters(self, instrpars):

        pri_header = self._image[0].header
        self.proc_unit = instrpars['proc_unit']

        if self._isNotValid (instrpars['gain'], instrpars['gnkeyword']):
            instrpars['gnkeyword'] = 'ADCGAIN' #gain has been hardcoded below

        if self._isNotValid (instrpars['rdnoise'], instrpars['rnkeyword']):
            instrpars['rnkeyword'] = None

        if self._isNotValid (instrpars['exptime'], instrpars['expkeyword']):
            instrpars['expkeyword'] = 'EXPTIME'

        for chip in self.returnAllChips(extname=self.scienceExt):
            chip._gain= 5.4 #measured gain
            chip._rdnoise   = self.getInstrParameter(
                instrpars['rdnoise'], pri_header, instrpars['rnkeyword']
            )
            chip._exptime   = self.getInstrParameter(
                instrpars['exptime'], pri_header, instrpars['expkeyword']
            )

            if chip._gain is None or self._exptime is None:
                print('ERROR: invalid instrument task parameter')
                raise ValueError

            # We need to treat Read Noise as a special case since it is
            # not populated in the NICMOS primary header
            if chip._rdnoise is None:
                chip._rdnoise = self._getDefaultReadnoise()

            chip._darkrate=self._getDarkRate()
            chip.darkcurrent = self.getdarkcurrent()

            chip._effGain = chip._gain
            # this is used in the static mask, static mask name also defined
            # here, must be done after outputNames
            self._assignSignature(chip._chip)

        # Convert the science data to electrons if specified by the user.
        self.doUnitConversions()

def render(self, fn=None, prompt=False, **params):

        from getpass import getpass
        expected_keys = self.expected_param_keys()
        compiled_params = Dict(**params)
        for key in expected_keys:
            if key not in compiled_params.keys():
                if prompt==True:
                    if key=='password':
                        compiled_params[key] = getpass("%s: " % key)
                    else:
                        compiled_params[key] = input("%s: " % key)
                        if 'path' in key:
                            compiled_params[key] = compiled_params[key].replace('\\','')
                else:
                    compiled_params[key] = "%%(%s)s" % key

        config = ConfigTemplate(fn=fn, **self)
        config.__dict__['ordered_keys'] = self.__dict__.get('ordered_keys')
        for block in config.keys():
            for key in config[block].keys():
                if type(config[block][key])==str:
                    config[block][key] = config[block][key] % compiled_params
        return config

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


Question: Write {@code byteCount} bytes from this to {@code out}.

public Buffer writeTo(OutputStream out, long byteCount) throws IOException {
    if (out == null) throw new IllegalArgumentException("out == null");
    checkOffsetAndCount(size, 0, byteCount);

    Segment s = head;
    while (byteCount > 0) {
      int toCopy = (int) Math.min(byteCount, s.limit - s.pos);
      out.write(s.data, s.pos, toCopy);

      s.pos += toCopy;
      size -= toCopy;
      byteCount -= toCopy;

      if (s.pos == s.limit) {
        Segment toRecycle = s;
        head = s = toRecycle.pop();
        SegmentPool.recycle(toRecycle);
      }
    }

    return this;
  }

static public int sizeOf(WsByteBuffer[] list) {
        if (null == list) {
            return 0;
        }
        int size = 0;
        for (int i = 0; i < list.length; i++) {
            if (null != list[i]) {
                size += list[i].remaining();
            }
        }
        return size;
    }

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


Question: // UnmarshalText implements encoding.TextUnmarshaler.

func (b *Uint) UnmarshalText(input []byte) error {
	var u64 Uint64
	err := u64.UnmarshalText(input)
	if u64 > Uint64(^uint(0)) || err == ErrUint64Range {
		return ErrUintRange
	} else if err != nil {
		return err
	}
	*b = Uint(u64)
	return nil
}

public static function utf8_to_entities($str, $dec=false, $nonnum=false) {
        static $callback = null ;

        if ($nonnum) {
            $str = self::entities_to_utf8($str, true);
        }

        // Avoid some notices from Typo3 code
        $oldlevel = error_reporting(E_PARSE);
        $result = self::typo3()->utf8_to_entities((string)$str);
        error_reporting($oldlevel);

        if ($dec) {
            if (!$callback) {
                $callback = function($matches) {
                    return '&#' . hexdec($matches[1]) . ';';
                };
            }
            $result = preg_replace_callback('/&#x([0-9a-f]+);/i', $callback, $result);
        }

        return $result;
    }

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


Question: // Write replaces the data associated with the file named by path.

func (c *Context) Write(path string, data []byte) error {
	if ae != nil {
		return ae.Write(c.ae, path, data)
	}
	return c.write(path, data)
}

function (subpath, preserve, newValue) {
    var args = Util.resolveArgs(
      arguments,
      function (x) { return Util.canRepresentSubpath(x) ? 'subpath' : null; },
      '?preserve',
      'newValue'
    );
    update(this, args.subpath, merge.bind(null, args.preserve, args.newValue));
    return this;
  }

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


Question:
Event handlers
Handle key down in <canvas> element

@param {Event} e Key down event

function _canvasKeyDown(e) {
        var code = e.keyCode,
            self = e.target,
            stepEditor = self.stepEditor;

        if (code >= KeyEvent.DOM_VK_LEFT && code <= KeyEvent.DOM_VK_DOWN) {
            e.preventDefault();

            // Arrow keys pressed
            switch (code) {
            case KeyEvent.DOM_VK_LEFT:
                stepEditor.stepCanvas.stepParams.timing = "start";
                break;
            case KeyEvent.DOM_VK_UP:
                // No upper limit
                stepEditor.stepCanvas.stepParams.count++;
                break;
            case KeyEvent.DOM_VK_RIGHT:
                stepEditor.stepCanvas.stepParams.timing = "end";
                break;
            case KeyEvent.DOM_VK_DOWN:
                if (stepEditor.stepCanvas.stepParams.count > 1) {
                    stepEditor.stepCanvas.stepParams.count--;
                }
                break;
            }

            // update step params
            stepEditor._stepParams = stepEditor.stepCanvas.stepParams;

            stepEditor._commitTimingFunction();
            stepEditor._updateCanvas();
            return true;

        } else if (code === KeyEvent.DOM_VK_ESCAPE) {
            return true;
        }

        return false;
    }

def draw_img_button(width=200, height=50, text='This is a button', color=rgb(200,100,50)):

    surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
    ctx = cairo.Context(surface)
    ctx.rectangle(0, 0, width - 1, height - 1)

    ctx.set_source_rgb(color.red/255.0, color.green/255.0, color.blue/255.0)
    ctx.fill()

    # Draw text
    ctx.set_source_rgb(1.0, 1.0, 1.0)
    ctx.select_font_face(
        "Helvetica",
        cairo.FONT_SLANT_NORMAL,
        cairo.FONT_WEIGHT_BOLD
    )
    ctx.set_font_size(15.0)
    ctx.move_to(15, 2 * height / 3)
    ctx.show_text(text)

    surface.write_to_png('button.png')

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


Question: Gathers the snap and wrap elements

function gatherSnapWrap() {
    var element;
    var value;
    for (element = $element; element.length; element = element.parent()) {
      value = element.attr('md-autocomplete-snap');
      if (angular.isDefined(value)) break;
    }

    if (element.length) {
      return {
        snap: element[0],
        wrap: (value.toLowerCase() === 'width') ? element[0] : $element.find('md-autocomplete-wrap')[0]
      };
    }

    var wrap = $element.find('md-autocomplete-wrap')[0];
    return {
      snap: wrap,
      wrap: wrap
    };
  }

static <K, V> void onSend(ProducerRecord<K, V> record, Span span) {
    setCommonTags(span);
    Tags.MESSAGE_BUS_DESTINATION.set(span, record.topic());
    if (record.partition() != null) {
      span.setTag("partition", record.partition());
    }
  }

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


Question: // NewMockMath creates a new mock instance

func NewMockMath(ctrl *gomock.Controller) *MockMath {
	mock := &MockMath{ctrl: ctrl}
	mock.recorder = &MockMathMockRecorder{mock}
	return mock
}

public function dispatch(
        MetaboxModel $metabox,
        MetaboxFactory $factory,
        HookFactory $hook
    ) {
        $this->metabox = $metabox;
        $this->factory = $factory;
        $this->hook = $hook;
    }

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


Question: Reads one line from the stream.

def readline(self, size=None):
        """"""
        if self._pos >= self.limit:
            return self.on_exhausted()
        if size is None:
            size = self.limit - self._pos
        else:
            size = min(size, self.limit - self._pos)
        try:
            line = self._readline(size)
        except (ValueError, IOError):
            return self.on_disconnect()
        if size and not line:
            return self.on_disconnect()
        self._pos += len(line)
        return line

def consume(self, limit=None):
        """"""
        for total_message_count in count():
            if limit and total_message_count >= limit:
                raise StopIteration

            if not self.channel.is_open:
                raise StopIteration

            self.channel.conn.drain_events()
            yield True

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


Question:
// MongoDB does not properly sort when keys are in parallel arrays ("Executor error: BadValue cannot sort with keys
// that are parallel arrays"), so... remove any sort options that have parallel arrays (and log it)

func removeParallelArraySorts(o *QueryOptions) {
	npSorts := make([]SortOption, 0, len(o.Sort))
	for i := range o.Sort {
		sort := o.Sort[i]
		isParallel := false
		for _, npSort := range npSorts {
			isParallel = isParallelArrayPath(sort.Parameter.Paths[0].Path, npSort.Parameter.Paths[0].Path)
			if isParallel {
				fmt.Printf("Cannot sub-sort on param '%s' because its path has parallel arrays with previous sort param '%s' (due to limitation in MongoDB)\n.", sort.Parameter.Name, npSort.Parameter.Name)
				break
			}
		}
		if !isParallel {
			npSorts = append(npSorts, sort)
		}
	}
	// If we ended up removing sort options, update the Options object to reflect that
	if len(o.Sort) != len(npSorts) {
		o.Sort = npSorts
	}
}

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question:
Search for a bug

 +query+ has to be either a +Query+ object or
 a +String+ that will be searched in the summary
 of the bugs.

def search_bugs(query)
      # allow plain strings to be passed, interpretting them
      query = Query.new.summary(query) if query.is_a?(String)

      ret = @client.call('Bug.search', query.query_map)
      handle_faults(ret)
      bugs = []
      ret['bugs'].each do |bug_data|
        bugs << Bug.new(self, bug_data)
      end
      bugs
    end

private SuggestedFix fixQualifiers(VisitorState state, MethodSymbol sym, SuggestedFix f) {
    SuggestedFix.Builder builder = SuggestedFix.builder().merge(f);
    new TreeScanner<Void, Void>() {
      @Override
      public Void visitMemberSelect(MemberSelectTree tree, Void unused) {
        fixQualifier(tree, tree.getExpression());
        return super.visitMemberSelect(tree, unused);
      }

      @Override
      public Void visitMemberReference(MemberReferenceTree tree, Void unused) {
        fixQualifier(tree, tree.getQualifierExpression());
        return super.visitMemberReference(tree, unused);
      }

      private void fixQualifier(Tree tree, ExpressionTree qualifierExpression) {
        if (sym.equals(ASTHelpers.getSymbol(tree))) {
          builder.replace(qualifierExpression, sym.owner.enclClass().getSimpleName().toString());
        }
      }
    }.scan(state.getPath().getCompilationUnit(), null);
    return builder.build();
  }

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


Question:
Called before each db query.
@param string $sql
@param array $params array of parameters
@param int $type type of query
@param mixed $extrainfo driver specific extra information
@return void

protected function query_start($sql, array $params = null, $type, $extrainfo = null) {
        parent::query_start($sql, $params, $type, $extrainfo);
    }

public function getAttribute($attribute)
    {
        switch ($attribute) {
            case \PDO::ATTR_AUTOCOMMIT:
                return true;
            case \PDO::ATTR_CASE:
            case \PDO::ATTR_CLIENT_VERSION:
            case \PDO::ATTR_CONNECTION_STATUS:
                return $this->client->connected;
            case \PDO::ATTR_DRIVER_NAME:
            case \PDO::ATTR_ERRMODE:
                return 'Swoole Style';
            case \PDO::ATTR_ORACLE_NULLS:
            case \PDO::ATTR_PERSISTENT:
            case \PDO::ATTR_PREFETCH:
            case \PDO::ATTR_SERVER_INFO:
                return self::$options['timeout'];
            case \PDO::ATTR_SERVER_VERSION:
                return 'Swoole Mysql';
            case \PDO::ATTR_TIMEOUT:
            default:
                throw new \InvalidArgumentException('Not implemented yet!');
        }
    }

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


Question: Return a fully-qualified environment_context string.

def environment_context_path(cls, project, environment, user, session,
                                 context):
        """"""
        return google.api_core.path_template.expand(
            'projects/{project}/agent/environments/{environment}/users/{user}/sessions/{session}/contexts/{context}',
            project=project,
            environment=environment,
            user=user,
            session=session,
            context=context,
        )

public static function setConnection($con, $env = null)
    {
        $env = self::selectEnvironment($env);
        self::$_connection[$env] = $con;

        // just send an exception when not on production mode
        if (in_array($env, array("development","test"))) {
            self::setErrorHandling(\PDO::ERRMODE_EXCEPTION);
        }
    }

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


Question: // SetReplicationGroupId sets the ReplicationGroupId field's value.

func (s *DescribeSnapshotsInput) SetReplicationGroupId(v string) *DescribeSnapshotsInput {
	s.ReplicationGroupId = &v
	return s
}

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

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

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


Question: Sets the designated parameter to the given Java array of bytes.

@Override
    public void setBytes(int parameterIndex, byte[] x) throws SQLException
    {
        checkParameterBounds(parameterIndex);
        this.parameters[parameterIndex-1] = x;
    }

public void init(final DeviceData deviceData, final ORB orb) throws DevFailed {
        deviceData.setAny(orb.create_any());
    }

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


Question:
`git merge-base ...`. Returns common ancestor for all passed commits

 @param [Array<Object>] args - list of commits to process. Last argument can be options for merge-base command
 @return [String]

def merge_base(*args)
      opts = args.last.is_a?(Hash) ? args.pop : {}

      arg_opts = opts.map { |k, v| "--#{k}" if v }.compact + args

      command('merge-base', arg_opts)
    end

func (cli *Client) ContainerCommit(ctx context.Context, container string, options types.ContainerCommitOptions) (types.IDResponse, error) {
	var repository, tag string
	if options.Reference != "" {
		ref, err := reference.ParseNormalizedNamed(options.Reference)
		if err != nil {
			return types.IDResponse{}, err
		}

		if _, isCanonical := ref.(reference.Canonical); isCanonical {
			return types.IDResponse{}, errors.New("refusing to create a tag with a digest reference")
		}
		ref = reference.TagNameOnly(ref)

		if tagged, ok := ref.(reference.Tagged); ok {
			tag = tagged.Tag()
		}
		repository = reference.FamiliarName(ref)
	}

	query := url.Values{}
	query.Set("container", container)
	query.Set("repo", repository)
	query.Set("tag", tag)
	query.Set("comment", options.Comment)
	query.Set("author", options.Author)
	for _, change := range options.Changes {
		query.Add("changes", change)
	}
	if !options.Pause {
		query.Set("pause", "0")
	}

	var response types.IDResponse
	resp, err := cli.post(ctx, "/commit", query, options.Config, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return response, err
	}

	err = json.NewDecoder(resp.body).Decode(&response)
	return response, err
}

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


Question:
Creates a UTF-8 encoded hash using the hash function

@param input string to encode
@param function hash function to use
@return the hash code

public static HashCode newHash(String input, HashFunction function) {
        return function.hashString(input, Charsets.UTF_8);
    }

private function unparseUrl($data)
    {
        $scheme = isset($data['scheme']) ? $data['scheme'] . '://' : '';
        $host = isset($data['host']) ? $data['host'] : '';
        $port = isset($data['port']) ? ':' . $data['port'] : '';
        $user = isset($data['user']) ? $data['user'] : '';
        $pass = isset($data['pass']) ? ':' . $data['pass'] : '';
        $pass = ($user || $pass) ? "$pass@" : '';
        $path = isset($data['path']) ? $data['path'] : '';
        $query = isset($data['query']) ? '?' . $data['query'] : '';
        $fragment = isset($data['fragment']) ? '#' . $data['fragment'] : '';

        return "$scheme$user$pass$host$port$path$query$fragment";
    }

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


Question:
:nodoc: internal use only

 Read

def each_message_chunk
      LOG 'reading message...'
      LOG_off()
      read_bytes = 0
      while (line = readuntil("\r\n")) != ".\r\n"
        read_bytes += line.size
        yield line.sub(/\A\./, '')
      end
      LOG_on()
      LOG "read message (#{read_bytes} bytes)"
    end

public void addWriter(PdfWriter writer) throws DocumentException {
        if (this.writer == null) {
            this.writer = writer;
            annotationsImp = new PdfAnnotationsImp(writer);
            return;
        }
        throw new DocumentException("You can only add a writer to a PdfDocument once.");
    }

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