Question: Provide a weather forecast for tomorrow based on historical weather at that location

def oneday_weather_forecast(
        location='Portland, OR',
        inputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity', 'Mean Humidity', 'Min Humidity', 'Max Sea Level Pressure', 'Mean Sea Level Pressure', 'Min Sea Level Pressure', 'Wind Direction'),
        outputs=('Min Temperature', 'Mean Temperature', 'Max Temperature', 'Max Humidity'),
        date=None,
        epochs=200,
        delays=(1, 2, 3, 4),
        num_years=4,
        use_cache=False,
        verbosity=1,
        ):

    date = make_date(date or datetime.datetime.now().date())
    num_years = int(num_years or 10)
    years = range(date.year - num_years, date.year + 1)
    df = weather.daily(location, years=years, use_cache=use_cache, verbosity=verbosity).sort()
    # because up-to-date weather history was cached above, can use that cache, regardless of use_cache kwarg
    trainer, df = train_weather_predictor(
        location,
        years=years,
        delays=delays,
        inputs=inputs,
        outputs=outputs,
        epochs=epochs,
        verbosity=verbosity,
        use_cache=True,
        )
    nn = trainer.module
    forecast = {'trainer': trainer}

    yesterday = dict(zip(outputs, nn.activate(trainer.ds['input'][-2])))
    forecast['yesterday'] = update_dict(yesterday, {'date': df.index[-2].date()})

    today = dict(zip(outputs, nn.activate(trainer.ds['input'][-1])))
    forecast['today'] = update_dict(today, {'date': df.index[-1].date()})

    ds = util.input_dataset_from_dataframe(df[-max(delays):], delays=delays, inputs=inputs, normalize=False, verbosity=0)
    tomorrow = dict(zip(outputs, nn.activate(ds['input'][-1])))
    forecast['tomorrow'] = update_dict(tomorrow, {'date': (df.index[-1] + datetime.timedelta(1)).date()})

    return forecast

func NewHistoryState(req *http.Request, resp *http.Response, dom *goquery.Document) *State {
	return &State{
		Request:  req,
		Response: resp,
		Dom:      dom,
	}
}

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


Question:
Executes the PhpMyAdminListTablesTask Task.

@return Robo\Result

public function run()
	{
        // Grab a list of tables
		$this->printTaskInfo('Getting list of tables.');
		$html = $this->loggedIn->getClient()->get('db_structure.php',
		[
			'query' =>
			[
				'db' => $this->remoteDbName,
				'server' => $this->loggedIn->getServerId(),
				'token' => $this->loggedIn->getToken()
			]
		])->getBody();

        // Extract a list of tables from the html
        $regex = '/<a href="sql\.php\?db=.*?table=(.*?)&pos=0" title="">.*?<\/a>/i';
		if (preg_match_all($regex, $html, $matches) !== false)
        {
            if (isset($matches[1]))
            {
                $this->tables = $matches[1];
            }
        }

        // If we get to here assume everything worked.
        // The tables can be accessed by calling getTask()->getTables().
		return Result::success($this);
    }

public function createTbl($dbname, $sql)
    {
        if (isset($dbname) && !empty(trim($dbname)) && isset($sql) && !empty(trim($sql))) {
            $this->db->exec("USE `{$dbname}` ");

            $this->db->exec($sql);

            return true;
        } else {
            return false;
        }
    }

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


Question:
Registers service of the form login authenticator and its alias.

@param ContainerBuilder $container The container builder
@param array            $routes    Array which contains security routes
@param string           $user      The user name

private function formLoginAuthenticator(ContainerBuilder $container, $routes, $user)
    {
        $container->setDefinition(
            'bengor.user_bundle.security.authenticator.form_login_' . $user . '_authenticator',
            new Definition(
                FormLoginAuthenticator::class, [
                    $container->getDefinition('router.default'),
                    $container->getDefinition('bengor_user.' . $user . '.command_bus'),
                    [
                        'login'                     => $routes[$user]['login']['name'],
                        'login_check'               => $routes[$user]['login_check']['name'],
                        'success_redirection_route' => $routes[$user]['success_redirection_route'],
                    ],
                ]
            )
        )->setPublic(false);

        $container->setAlias(
            'bengor_user.' . $user . '.form_login_authenticator',
            'bengor.user_bundle.security.authenticator.form_login_' . $user . '_authenticator'
        );
    }

public function be(UserContract $user, $driver = null)
    {
        $this->app['auth']->guard($driver)->setUser($user);
    }

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


Question: Schema for particular properties of the object.

def properties(self):
        """"""
        value = self._schema.get("properties", {})
        if not isinstance(value, dict):
            raise SchemaError(
                "properties value {0!r} is not an object".format(value))
        return value

def _get_requested_spec(self, obj, spec_name):
        """"""
        requested = self._specs_in[spec_name]
        if isinstance(requested, str):
            return _get_attr_by_tag(obj, requested, spec_name)
        else:
            return requested

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


Question:
Convert to PSR-7's ServerRequestInterface.

@param BrowserKitRequest $request
@return ServerRequestInterface

private function convertRequest(BrowserKitRequest $request)
    {
        $environment = Environment::mock($request->getServer());
        $uri = Uri::createFromString($request->getUri());
        $headers = Headers::createFromEnvironment($environment);
        $cookies = Cookies::parseHeader($headers->get('Cookie', []));

        $container = $this->app->getContainer();

        /* @var $slimRequest ServerRequestInterface */
        $slimRequest = $container->get('request');

        $slimRequest = $slimRequest->withMethod($request->getMethod())
          ->withUri($uri)
          ->withUploadedFiles($this->convertFiles($request->getFiles()))
          ->withCookieParams($cookies);

        foreach ($headers->keys() as $key) {
            $slimRequest = $slimRequest->withHeader($key, $headers->get($key));
        }

        if ($request->getContent() !== null) {
            $body = new RequestBody();
            $body->write($request->getContent());
            $slimRequest = $slimRequest
                ->withBody($body);
        }

        $parsed = [];
        if ($request->getMethod() !== 'GET') {
            $parsed = $request->getParameters();
        }

        // make sure we do not overwrite a request with a parsed body
        if (!$slimRequest->getParsedBody()) {
            $slimRequest = $slimRequest
                ->withParsedBody($parsed);
        }

        return $slimRequest;
    }

func (c *Conn) IndexWithParameters(index string, _type string, id string, parentId string, version int, op_type string,
	routing string, timestamp string, ttl int, percolate string, timeout string, refresh bool,
	args map[string]interface{}, data interface{}) (BaseResponse, error) {
	var url string
	var retval BaseResponse
	url, err := GetIndexUrl(index, _type, id, parentId, version, op_type, routing, timestamp, ttl, percolate, timeout, refresh)
	if err != nil {
		return retval, err
	}
	var method string
	if len(id) == 0 {
		method = "POST"
	} else {
		method = "PUT"
	}
	body, err := c.DoCommand(method, url, args, data)
	if err != nil {
		return retval, err
	}
	if err == nil {
		// marshall into json
		jsonErr := json.Unmarshal(body, &retval)
		if jsonErr != nil {
			return retval, jsonErr
		}
	}
	return retval, err
}

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


Question:
`cart_name` - Name of this release cart
        `cart_description` - list of ['reponame', item1, ..., itemN] lists

def create(self, cart_name, cart_description):

        cart = juicer.common.Cart.Cart(cart_name)

        # repo_items is a list that starts with the REPO name,
        # followed by the ITEMS going into the repo.
        for repo_items in cart_description:
            (repo, items) = (repo_items[0], repo_items[1:])
            juicer.utils.Log.log_debug("Processing %s input items for repo '%s'." % (len(items), repo))
            cart[repo] = items

        cart.save()
        return cart

public function getBasketPrice($dAmount, $aSelList, $oBasket)
    {
        $oUser = $oBasket->getBasketUser();
        $this->setArticleUser($oUser);

        $oBasketPrice = $this->_getPriceObject($oBasket->isCalculationModeNetto());

        // get base price
        $dBasePrice = $this->getBasePrice($dAmount);

        $dBasePrice = $this->_modifySelectListPrice($dBasePrice, $aSelList);
        $dBasePrice = $this->_preparePrice($dBasePrice, $this->getArticleVat(), $oBasket->isCalculationModeNetto());

        // applying select list price

        // setting price
        $oBasketPrice->setPrice($dBasePrice);

        $dVat = \OxidEsales\Eshop\Core\Registry::get(\OxidEsales\Eshop\Application\Model\VatSelector::class)->getBasketItemVat($this, $oBasket);
        $this->_calculatePrice($oBasketPrice, $dVat);

        // returning final price object
        return $oBasketPrice;
    }

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


Question: // SendMailV31 sends a mail to the send API v3.1

func (c *Client) SendMailV31(data *MessagesV31) (*ResultsV31, error) {
	url := c.apiBase + ".1/send"
	req, err := createRequest("POST", url, data, nil)
	if err != nil {
		return nil, err
	}

	req.Header.Set("Content-Type", "application/json")
	req.SetBasicAuth(c.APIKeyPublic(), c.APIKeyPrivate())

	r, err := c.httpClient.SendMailV31(req)
	if err != nil {
		return nil, err
	}

	decoder := json.NewDecoder(r.Body)

	switch r.StatusCode {
	case http.StatusOK:

		var res ResultsV31
		if err := decoder.Decode(&res); err != nil {
			return nil, err
		}
		return &res, nil

	case http.StatusBadRequest, http.StatusForbidden:

		var apiFeedbackErr APIFeedbackErrorsV31
		if err := decoder.Decode(&apiFeedbackErr); err != nil {
			return nil, err
		}
		return nil, &apiFeedbackErr

	default:

		var errInfo ErrorInfoV31
		if err := decoder.Decode(&errInfo); err != nil {
			return nil, err
		}
		return nil, &errInfo
	}
}

def _login(self):
        '''
        '''
        server, port, mode, debug = self.connection_details

        if mode == 'SSL':
            smtp_class = smtplib.SMTP_SSL
        else:
            smtp_class = smtplib.SMTP

        smtp = smtp_class(server, port)
        smtp.set_debuglevel(debug)

        if mode == 'TLS':
            smtp.starttls()

        self.authenticate(smtp)

        return smtp

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


Question:
After the component has been painted, the UIContexts for this component and all its children are cleared.

@param renderContext the renderContext to send output to.

@Override
	protected void afterPaint(final RenderContext renderContext) {
		super.afterPaint(renderContext);

		final int size = getChildCount();

		for (int i = 0; i < size; i++) {
			WComponent child = getChildAt(i);
			child.reset();
		}
	}

def init(self):
        """"""
        # Wrap callback methods in appropriate ctypefunc instances so
        # that the Pulseaudio C API can call them
        self._context_notify_cb = pa_context_notify_cb_t(
            self.context_notify_cb)
        self._sink_info_cb = pa_sink_info_cb_t(self.sink_info_cb)
        self._update_cb = pa_context_subscribe_cb_t(self.update_cb)
        self._success_cb = pa_context_success_cb_t(self.success_cb)
        self._server_info_cb = pa_server_info_cb_t(self.server_info_cb)

        # Create the mainloop thread and set our context_notify_cb
        # method to be called when there's updates relating to the
        # connection to Pulseaudio
        _mainloop = pa_threaded_mainloop_new()
        _mainloop_api = pa_threaded_mainloop_get_api(_mainloop)
        context = pa_context_new(_mainloop_api, "i3pystatus_pulseaudio".encode("ascii"))

        pa_context_set_state_callback(context, self._context_notify_cb, None)
        pa_context_connect(context, None, 0, None)
        pa_threaded_mainloop_start(_mainloop)

        self.colors = self.get_hex_color_range(self.color_muted, self.color_unmuted, 100)
        self.sinks = []

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


Question:
Merge require or require-dev into a RootPackageInterface

@param string $type 'require' or 'require-dev'
@param RootPackageInterface $root
@param PluginState $state

protected function mergeRequires(
        $type,
        RootPackageInterface $root,
        PluginState $state
    ) {
        $linkType = BasePackage::$supportedLinkTypes[$type];
        $getter = 'get' . ucfirst($linkType['method']);
        $setter = 'set' . ucfirst($linkType['method']);

        $requires = $this->package->{$getter}();
        if (empty($requires)) {
            return;
        }

        $this->mergeStabilityFlags($root, $requires);

        $requires = $this->replaceSelfVersionDependencies(
            $type,
            $requires,
            $root
        );

        $root->{$setter}($this->mergeOrDefer(
            $type,
            $root->{$getter}(),
            $requires,
            $state
        ));
    }

function(name, cb){
		if(shuttingDown == true)
			return;
		if(!package.dependencies[name] && name != "isnode-mod-logger"){
			var error = { message: "Failed to load "+name+" Module - Module not referenced in node package file" };
			if(cb) { cb(error, null); }
			modules.logger.log("startup","ISNode System > " + error.message + ".");
			return;
		}
		var modPresent = isModuleAvailable(name);
		if(modPresent){
			var nameSplit = name.split("-");
			if(nameSplit[0] != "isnode" && nameSplit[1] != "mod"){
				var error = { message: "Attempted to load a non 'ismod' or 'isnode' module with the isnode module loader" };
				modules.logger.log("warning","ISNode System > " + error.message + ".");
				if(cb) { cb(error, null); }
				return;
			} else if (nameSplit[2] == "interface" && nameSplit[3]){
				try {
					modules.interfaces[nameSplit[3]] = require(name)(isnode);
					var output = {
						success: true,
						message: "Interface module ("+nameSplit[3]+") successfully loaded"
					}
					modules.logger.log("debug", "ISNode System > " + output.message);
					if(cb) { cb(null,output); }
					return;
				} catch (err) {
					var error = { message: "System Error. Attempted to load module that does not exist - " + name };
					modules.logger.log("error","ISNode System > " + error.message, err);
					if(cb) { cb(error, null); }
					return;
				}
			} else if (nameSplit[2] != "interface" && !nameSplit[3]) {
				try {
					modules[nameSplit[2]] = require(name)(isnode);
					var output = {
						success: true,
						message: "Standard module ("+nameSplit[2]+") successfully loaded"
					}
					modules.logger.log("debug", output.message + ".");
					if(cb) { cb(null, output); }
					return;
				} catch (err) {
					var error = { message: "System Error. Attempted to load module that does not exist - " + name, error: err };
					modules.logger.log("error","ISNode System > " + error.message+".", err);
					if(cb) { cb(error, null); }
					return;
				}
			} else {
				var error = { message: "Attempted to load an unsupported ismod module with the ismod module loader" };
				modules.logger.log("warning","ISNode System > " + error.message + ".");
				if(cb) { cb(error, null); }
				return;
			}
		} else {
			if(name == "isnode-mod-logger"){
				modules.logger = {
					log: function(level,logMsg,attrObj){
						console.log("("+level+") "+logMsg);
					}
				}
				var error = { message: "Logger module not available. Polyfill method loaded in its place" };
				modules.logger.log("warning","ISNode System > " + error.message + ".");
				if(cb) { cb(error, null); }
			} else {
				var error = { message: "Attempted to load an ismod module ("+name+") that does not exist. Try running 'npm install'." };
				modules.logger.log("warning","ISNode System > " + error.message + ".");
				if(cb) { cb(error, null); }
			}
			return;
		}
	}

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


Question:
Expands a zip file input stream into a temporary directory.

@param dir temporary directory
@param inputStream zip file input stream

private static void processZipStream(File dir, InputStream inputStream) throws IOException
   {
      ZipInputStream zip = new ZipInputStream(inputStream);
      while (true)
      {
         ZipEntry entry = zip.getNextEntry();
         if (entry == null)
         {
            break;
         }

         File file = new File(dir, entry.getName());
         if (entry.isDirectory())
         {
            FileHelper.mkdirsQuietly(file);
            continue;
         }

         File parent = file.getParentFile();
         if (parent != null)
         {
            FileHelper.mkdirsQuietly(parent);
         }

         FileOutputStream fos = new FileOutputStream(file);
         byte[] bytes = new byte[1024];
         int length;
         while ((length = zip.read(bytes)) >= 0)
         {
            fos.write(bytes, 0, length);
         }
         fos.close();
      }
   }

protected boolean checkParentDirs(String path, boolean createIfAbsent) throws IOException {
      String[] components = Util.components(path, SEPARATOR);
      if (components == null)
         return false;
      if (components.length == 1) // no parent directories to create, e.g. "data.txt"
         return true;

      StringBuilder sb = new StringBuilder();
      boolean first = true;

      for (int i = 0; i < components.length - 1; i++) {
         String tmp = components[i];
         if (!tmp.equals(SEPARATOR)) {
            if (first)
               first = false;
            else
               sb.append(SEPARATOR);
         }
         sb.append(tmp);
         String comp = sb.toString();
         if (comp.equals(SEPARATOR))
            continue;
         Metadata val = exists(comp);
         if (val != null) {
            if (val.isFile())
               throw new IOException(format("cannot create %s as component %s is a file", path, comp));
         } else if (createIfAbsent) {
            metadataCache.put(comp, new Metadata(0, System.currentTimeMillis(), chunkSize, Metadata.DIR));
         } else {
            // Couldn't find a component and we're not allowed to create components!
            return false;
         }

      }
      // check that we have found all the components we need.
      return true;
   }

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


Question:
Exchanges all keys with their associated values in an object.

@param {Object.<string, string>} obj An object of strings.
@return {Object.<string, string>} An object of strings.

function flip(obj) {
              var newObj = Object.create(null),
                  key;

              for (key in obj) {
                newObj[obj[key]] = key;
              }

              return newObj;
            }

function pretty(srcObj) {
      return typeOf(srcObj, 'arr', 'obj') ? JSON.stringify(srcObj, null, 2) : String(srcObj);
    }

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


Question:
// ComparePassword checks if the password matches the password recorded.
// Passwords that do not match return errors.

func (s *Service) ComparePassword(ctx context.Context, name string, password string) error {
	return s.kv.View(ctx, func(tx Tx) error {
		return s.comparePassword(ctx, tx, name, password)
	})
}

static public function notEq($value1, $value2, $message = null, $propertyPath = null)
        {
            if ($value1 == $value2) {
                $message = $message ?: sprintf(
                    'Value "%s" is equal to expected value "%s".',
                    static::stringify($value1),
                    static::stringify($value2)
                );

                throw static::createException($value1, $message,static::INVALID_NOT_EQ, $propertyPath, array('expected' => $value2));
            }
        }

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


Question:
Test the current Cellule object to see if it is a MessagingEngine

@return true if the current object is a MessagingEngine otherwise false

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

    boolean rc = (this instanceof MessagingEngine);

    if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(tc, "isMessagingEngine", Boolean.valueOf(rc));
    return rc;
  }

public function agent($name)
    {
        if (!is_string($name) || empty($name)) {
            throw new PhpSmsException('Expected the parameter to be non-empty string.');
        }
        $this->firstAgent = $name;

        return $this;
    }

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


Question:
find the next other letter from the current position
find the letter number from the current position
count until the char in the specified position is not a letter number or whitespace

@param c
@return String
@throws IOException

protected String nextLetterNumber( int c ) throws IOException
    {
        //StringBuilder isb = new StringBuilder();
        isb.clear();
        isb.append((char)c);
        int ch;
        while ( (ch = readNext()) != -1 ) {
            if ( StringUtil.isWhitespace(ch) ) {
                pushBack(ch);
                break;
            }

            if ( ! StringUtil.isLetterNumber( ch ) ) {
                pushBack(ch);
                break;
            }

            isb.append((char)ch);
        }

        return isb.toString();
    }

private void setSentenceSpan(JSONObject cNode, JSONObject parent) {
    try {
      JSONObject data = cNode.getJSONObject("data");

      int leftPosC = data.getInt(SENTENCE_LEFT);
      int rightPosC = data.getInt(SENTENCE_RIGHT);

      data = parent.getJSONObject("data");

      if (data.has(SENTENCE_LEFT)) {
        data.put(SENTENCE_LEFT, Math.min(leftPosC, data.getInt(SENTENCE_LEFT)));
      } else {
        data.put(SENTENCE_LEFT, leftPosC);
      }

      if (data.has(SENTENCE_RIGHT)) {
        data.put(SENTENCE_RIGHT,
                Math.max(rightPosC, data.getInt(SENTENCE_RIGHT)));
      } else {
        data.put(SENTENCE_RIGHT, rightPosC);
      }
    } catch (JSONException ex) {
      log.debug("error while setting left and right position for sentences", ex);
    }
  }

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


Question:
Runs the example.

@param adWordsServices the services factory.
@param session the session.
@throws ApiException if the API request failed with one or more service errors.
@throws RemoteException if the API request failed due to other errors.

public static void runExample(AdWordsServicesInterface adWordsServices, AdWordsSession session)
      throws RemoteException {
    // Get all of the feeds for the session's account.
    List<Feed> feeds = getFeeds(adWordsServices, session);

    for (Feed feed : feeds) {
      // Retrieve all the sitelinks from the current feed.
      Map<Long, SiteLinkFromFeed> feedItems = getSiteLinksFromFeed(adWordsServices, session, feed);

      // Get all the instances where a sitelink from this feed has been added to a campaign.
      List<CampaignFeed> campaignFeeds =
          getCampaignFeeds(adWordsServices, session, feed, PLACEHOLDER_SITELINKS);

      Set<Long> allFeedItemsToDelete = Sets.newHashSet();
      for (CampaignFeed campaignFeed : campaignFeeds) {
        // Retrieve the sitelinks that have been associated with this campaign.
        Set<Long> feedItemIds = getFeedItemIdsForCampaign(campaignFeed);

        ExtensionSettingPlatform platformRestrictions =
            getPlatformRestictionsForCampaign(campaignFeed);

        if (feedItemIds.isEmpty()) {
          System.out.printf("Migration skipped for campaign feed with campaign ID %d "
              + "and feed ID %d because no mapped feed item IDs were found in the "
              + "campaign feed's matching function.%n", campaignFeed.getCampaignId(),
              campaignFeed.getFeedId());
        } else {
          // Delete the campaign feed that associates the sitelinks from the feed to the campaign.
          deleteCampaignFeed(adWordsServices, session, campaignFeed);

          // Create extension settings instead of sitelinks.
          createExtensionSetting(adWordsServices,
              session,
              feedItems,
              campaignFeed,
              feedItemIds,
              platformRestrictions);

          // Mark the sitelinks from the feed for deletion.
          allFeedItemsToDelete.addAll(feedItemIds);
        }
      }

      // Delete all the sitelinks from the feed.
      deleteOldFeedItems(adWordsServices, session, allFeedItemsToDelete, feed);
    }
  }

func (c *RolesController) List(ctx *app.ListRolesContext) error {
	if ctx.ResourceType == nil { // todo: check for empty string too?
		return jsonapi.JSONErrorResponse(ctx, errors.NewBadParameterError("resource_type", "nil"))
	}

	var roleScopes []role.RoleDescriptor

	_, err := c.app.ResourceTypeRepository().Lookup(ctx, *ctx.ResourceType)
	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting roles for the resource type")
		// if not found, then NotFoundError would be returned,
		// hence returning the error as is.
		return jsonapi.JSONErrorResponse(ctx, err)
	}

	roleScopes, err = c.app.RoleManagementService().ListAvailableRolesByResourceType(ctx, *ctx.ResourceType)

	if err != nil {
		log.Error(ctx, map[string]interface{}{
			"resource_type": *ctx.ResourceType,
			"err":           err,
		}, "error getting available roles for the resource")
		return jsonapi.JSONErrorResponse(ctx, err)
	}
	respRoles := convertRoleScopeToAppRoles(roleScopes)
	res := &app.Roles{
		Data: respRoles,
	}
	return ctx.OK(res)
}

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


Question:
/*
(non-Javadoc)

@see com.ibm.websphere.cache.CacheAdminMBean#getCacheEntry(java.lang.String, java.lang.String)

@Override
    public String getCacheEntry(String cacheInstance, String cacheId) throws javax.management.AttributeNotFoundException { // 429429

        if (cacheId == null) {
            throw new AttributeNotFoundException(cacheId + " is null.");
        }

        //Get the cache for this cacheInstance
        DCache cache1 = getCache(cacheInstance);
        //Get the cache entry

        EntryInfo ei = new EntryInfo();
        ei.setId(cacheId);
        com.ibm.websphere.cache.CacheEntry cacheEntry = cache1.getEntry(ei, true);

        String stringEntry = null;
        if (null != cacheEntry) {
            stringEntry = cacheEntry.toString();
            // Release cacheEntry and decrement referenced count for it before
            // return.
            cacheEntry.finish();
        }

        if (tc.isDebugEnabled()) {
            Tr.debug(tc, "getCacheEntry: Returning: " + stringEntry
                         + " for cacheInstance = " + cacheInstance);
        }

        return stringEntry;
    }

public CMAWebhook addHeader(String key, String value) {
    if (this.headers == null) {
      this.headers = new ArrayList<CMAWebhookHeader>();
    }

    this.headers.add(new CMAWebhookHeader(key, value));
    return this;
  }

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


Question: // Get an initialized Threefish256 structure

func newThreefish256(key []byte, tweak []uint64) (*threefish256, error) {
    c := new(threefish256)

    // Initialize tweak
    setTweak(tweak, c.expanedTweak[:])

    c.expanedKey[EXPANDED_KEY_SIZE_256-1] = KEY_SCHEDULE_CONST

    // Convert key bytes to required uint64 array
    if key != nil {
        var tmpkey [EXPANDED_KEY_SIZE_256]uint64
        for i := 0; i < EXPANDED_KEY_SIZE_256-1; i++ {
            tmpkey[i] = binary.LittleEndian.Uint64(key[i*8 : i*8+8])
        }
        setKey(tmpkey[:], c.expanedKey[:])
    }
    return c, nil
}

public function getChanContents(int $channel=1) : string
    {
        if ( ! isset ($this->pipes[$channel]))
            throw new \InvalidArgumentException("No channel '$channel' defined.");
        return $this->pipes[$channel];
    }

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


Question:
{@inheritDoc} initialize the validator.

@see javax.validation.ConstraintValidator#initialize(java.lang.annotation.Annotation)

@Override
  public final void initialize(final AlternateSize pconstraintAnnotation) {
    size1 = pconstraintAnnotation.size1();
    size2 = pconstraintAnnotation.size2();
    ignoreWhiteSpaces = pconstraintAnnotation.ignoreWhiteSpaces();
    ignoreMinus = pconstraintAnnotation.ignoreMinus();
    ignoreSlashes = pconstraintAnnotation.ignoreSlashes();
    validateParameters();
  }

public Factvalue newFactvalue(WF wf, String prediction) {
	Factvalue factuality = new Factvalue(wf, prediction);
	annotationContainer.add(factuality, Layer.FACTUALITY_LAYER, AnnotationType.FACTVALUE);
	return factuality;
    }

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


Question: Get the current position.

function now() {
      var pos = {line: line, column: column}

      pos.offset = self.toOffset(pos)

      return pos
    }

public function setByPosition($pos, $value)
    {
        switch ($pos) {
            case 0:
                $this->setSkillId($value);
                break;
            case 1:
                $this->setGroupId($value);
                break;
        } // switch()

        return $this;
    }

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


Question: Build the SLSString.

def construct_sls_str(self, node):
        '''

        '''

        # Ensure obj is str, not py2 unicode or py3 bytes
        obj = self.construct_scalar(node)
        if six.PY2:
            obj = obj.encode('utf-8')
        return SLSString(obj)

func (kh *TLSKnownHost) String() string {
	return fmt.Sprintf("%s %s %x", kh.Host, kh.Alg, kh.Fingerprint)
}

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


Question: Calculates the request payload size

def calculate_size(name, timeout_millis):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += LONG_SIZE_IN_BYTES
    return data_size

protected function createStringPayload($job, $data)
    {
        return [
            'displayName' => is_string($job) ? explode('@', $job)[0] : null,
            'job' => $job, 'maxTries' => null,
            'timeout' => null, 'data' => $data,
        ];
    }

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


Question: // helper for SourceFileFunction recursion

func (env *Zlisp) sourceItem(item Sexp) error {
	switch t := item.(type) {
	case *SexpArray:
		for _, v := range t.Val {
			if err := env.sourceItem(v); err != nil {
				return err
			}
		}
	case *SexpPair:
		expr := item
		for expr != SexpNull {
			list := expr.(*SexpPair)
			if err := env.sourceItem(list.Head); err != nil {
				return err
			}
			expr = list.Tail
		}
	case *SexpStr:
		var f *os.File
		var err error

		if f, err = os.Open(t.S); err != nil {
			return err
		}
		defer f.Close()
		if err = env.SourceFile(f); err != nil {
			return err
		}

	default:
		return fmt.Errorf("source: Expected `string`, `list`, `array`. Instead found type %T val %v", item, item)
	}

	return nil
}

private function fileLineGenerator(string $fileName, callable $formatter = null)
    {
        $f = fopen($fileName, 'r');
        try {
            while ($line = fgets($f)) {
                if(!is_null($formatter)){
                    yield call_user_func($formatter, $line);
                }
                else {
                    yield $line;
                }
            }
        } finally {
            fclose($f);
        }
    }

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


Question:
Get the mime_type of a file

@access public
@param string $file The path to the file
@return string $mime_type

public static function detect_mime_type($path) {
		$handle = finfo_open(FILEINFO_MIME);
		$mime_type = finfo_file($handle, $path);

		if (strpos($mime_type, ';')) {
			$mime_type = preg_replace('/;.*/', ' ', $mime_type);
		}

		return trim($mime_type);
	}

private function runtimeFileType($name)
    {
        if (empty($name)) {
            return false;
        }
        $explodedName = explode(".", $name);
        switch ($explodedName[(count($explodedName) - 1)]) {
            case "php":
                return "php";
            case "rb":
                return "ruby";
            case "py":
                return "python";
            case "javascript":
                return "javascript";
            default:
                return "no_type_found";
        }
    }

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


Question:
Finalize executes any subclass-specific axes finalization steps.
        The user calls poof and poof calls finalize.

        Parameters
        ----------
        kwargs: generic keyword arguments.

def finalize(self, **kwargs):

        # Divide out the two features
        feature_one, feature_two = self.features_

        # Set the title
        self.set_title('Scatter Plot: {0} vs {1}'.format(
            str(feature_one), str(feature_two)))
        # Add the legend
        self.ax.legend(loc='best')
        self.ax.set_xlabel(str(feature_one))
        self.ax.set_ylabel(str(feature_two))

def storage_command(self, name, method_name=None, command_type=None, oauth=False, generic_update=None, **kwargs):

        if generic_update:
            command_name = '{} {}'.format(self.group_name, name) if self.group_name else name
            self.generic_update_command(name, **kwargs)
        elif command_type:
            command_name = self.command(name, method_name, command_type=command_type, **kwargs)
        else:
            command_name = self.command(name, method_name, **kwargs)
        self._register_data_plane_account_arguments(command_name)
        if oauth:
            self._register_data_plane_oauth_arguments(command_name)

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


Question:
Helper method that returns a list of elements that match the
        given path pattern of form {type}.{group}.{label}.

        The input may be a Layout, an Overlay type or a single
        Element.

def search(cls, element, pattern):

        if isinstance(element, Layout):
            return [el for cell in element for el in cls.search(cell, pattern)]
        if isinstance(element, (NdOverlay, Overlay)):
            return [el for el in element if el.matches(pattern)]
        elif isinstance(element, Element):
            return [element] if element.matches(pattern) else []

private void putPlaceholdersIntoMap(
      MsgNode originalMsg,
      Iterable<? extends SoyMsgPart> parts,
      Map<String, Function<Expression, Statement>> placeholderNameToPutStatement) {
    for (SoyMsgPart child : parts) {
      if (child instanceof SoyMsgRawTextPart || child instanceof SoyMsgPluralRemainderPart) {
        // raw text doesn't have placeholders and remainders use the same placeholder as plural they
        // are a member of.
        continue;
      }
      if (child instanceof SoyMsgPluralPart) {
        putPluralPartIntoMap(originalMsg, placeholderNameToPutStatement, (SoyMsgPluralPart) child);
      } else if (child instanceof SoyMsgSelectPart) {
        putSelectPartIntoMap(originalMsg, placeholderNameToPutStatement, (SoyMsgSelectPart) child);
      } else if (child instanceof SoyMsgPlaceholderPart) {
        putPlaceholderIntoMap(
            originalMsg, placeholderNameToPutStatement, (SoyMsgPlaceholderPart) child);
      } else {
        throw new AssertionError("unexpected child: " + child);
      }
    }
  }

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


Question:
> Delegate additional optional properties to the `KindError` class.
If `actual` and `expected` properties given in `options` object.

@param  {Object} `self`
@return {Object}

function delegateOptional (self) {
  if (hasOwn(self, 'actual') && hasOwn(self, 'expected')) {
    var kindOf = tryRequire('kind-of-extra', 'kind-error')
    delegate(self, {
      orig: {
        actual: self.actual,
        expected: self.expected
      },
      type: {
        actual: kindOf(self.actual),
        expected: kindOf(self.expected)
      },
      inspect: {
        actual: util.inspect(self.actual),
        expected: util.inspect(self.expected)
      }
    })
    if (typeof self.message === 'function') {
      self.message = self.message.call(self, self.type, self.inspect) // eslint-disable-line no-useless-call
    }
  }
  return self
}

func (o *UpdateJSONWebKeyReader) ReadResponse(response runtime.ClientResponse, consumer runtime.Consumer) (interface{}, error) {
	switch response.Code() {

	case 200:
		result := NewUpdateJSONWebKeyOK()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return result, nil

	case 401:
		result := NewUpdateJSONWebKeyUnauthorized()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 403:
		result := NewUpdateJSONWebKeyForbidden()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	case 500:
		result := NewUpdateJSONWebKeyInternalServerError()
		if err := result.readResponse(response, consumer, o.formats); err != nil {
			return nil, err
		}
		return nil, result

	default:
		return nil, runtime.NewAPIError("unknown error", response, response.Code())
	}
}

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


Question: Calculates the request payload size

def calculate_size(name, attribute, ordered):

    data_size = 0
    data_size += calculate_size_str(name)
    data_size += calculate_size_str(attribute)
    data_size += BOOLEAN_SIZE_IN_BYTES
    return data_size

protected function createStringPayload($job, $data)
    {
        return [
            'displayName' => is_string($job) ? explode('@', $job)[0] : null,
            'job' => $job, 'maxTries' => null,
            'timeout' => null, 'data' => $data,
        ];
    }

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


Question:
Function: contains

Returns true if the specified point (x, y) is contained in the given rectangle.

Parameters:

bounds - <mxRectangle> that represents the area.
x - X-coordinate of the point.
y - Y-coordinate of the point.

function(bounds, x, y)
	{
		return (bounds.x <= x && bounds.x + bounds.width >= x &&
				bounds.y <= y && bounds.y + bounds.height >= y);
	}

public GeoRect getBoundingBox() {
        double radDist = radius / EARTH_RADIUS;
        double radLat = Math.toRadians(latitude);
        double radLon = Math.toRadians(longitude);

        double minLat = radLat - radDist;
        double maxLat = radLat + radDist;

        double minLon, maxLon;
        if (minLat > MIN_LAT && maxLat < MAX_LAT) {
            double deltaLon = Math.asin(Math.sin(radDist) /
                Math.cos(radLat));
            minLon = radLon - deltaLon;
            if (minLon < MIN_LON) {
                minLon += 2d * Math.PI;
            }
            maxLon = radLon + deltaLon;
            if (maxLon > MAX_LON) {
                maxLon -= 2d * Math.PI;
            }
        } else {
            // a pole is within the distance
            minLat = Math.max(minLat, MIN_LAT);
            maxLat = Math.min(maxLat, MAX_LAT);
            minLon = MIN_LON;
            maxLon = MAX_LON;
        }

        return new GeoRect(
            new GeoPoint(Math.toDegrees(maxLat), Math.toDegrees(minLon)),
            new GeoPoint(Math.toDegrees(minLat), Math.toDegrees(maxLon))
        );
    }

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


Question:
deserialize a data tree from the most recent snapshot
@return the zxid of the snapshot

@Override
    public long deserialize(DataTree dt, Map<Long, Long> sessions)
            throws IOException {
        // we run through 100 snapshots (not all of them)
        // if we cannot get it running within 100 snapshots
        // we should  give up
        List<File> snapList = findNValidSnapshots(100);
        if (snapList.size() == 0) {
            return -1L;
        }
        File snap = null;
        boolean foundValid = false;
        for (int i = 0; i < snapList.size(); i++) {
            snap = snapList.get(i);
            InputStream snapIS = null;
            CheckedInputStream crcIn = null;
            try {
                LOG.info("Reading snapshot " + snap);
                snapIS = new BufferedInputStream(new FileInputStream(snap));
                crcIn = new CheckedInputStream(snapIS, new Adler32());
                InputArchive ia = BinaryInputArchive.getArchive(crcIn);
                deserialize(dt,sessions, ia);
                long checkSum = crcIn.getChecksum().getValue();
                long val = ia.readLong("val");
                if (val != checkSum) {
                    throw new IOException("CRC corruption in snapshot :  " + snap);
                }
                foundValid = true;
                break;
            } catch(IOException e) {
                LOG.warn("problem reading snap file " + snap, e);
            } finally {
                if (snapIS != null)
                    snapIS.close();
                if (crcIn != null)
                    crcIn.close();
            }
        }
        if (!foundValid) {
            throw new IOException("Not able to find valid snapshots in " + snapDir);
        }
        dt.lastProcessedZxid = Util.getZxidFromName(snap.getName(), "snapshot");
        return dt.lastProcessedZxid;
    }

public function build(): RequestChildNodesRequest
	{
		$instance = new RequestChildNodesRequest();
		if ($this->nodeId === null) {
			throw new BuilderException('Property [nodeId] is required.');
		}
		$instance->nodeId = $this->nodeId;
		$instance->depth = $this->depth;
		$instance->pierce = $this->pierce;
		return $instance;
	}

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


Question:
Select currently running activity.

@return mixed Returns either `NULL` or {@see \odTimeTracker\Model\ActivityEntity}.

public function selectRunningActivity()
	{
		$stmt = $this->pdo->prepare(<<<EOT
SELECT
	t1.*,
	t2.ProjectId AS "Project.ProjectId",
	t2.Name AS "Project.Name",
	t2.Description AS "Project.Description",
	t2.Created AS "Project.Created"
FROM `$this->tableName` AS t1
LEFT JOIN Projects AS t2 ON t1.ProjectId = t2.ProjectId
WHERE t1.Stopped IS NULL OR t1.Stopped = ''
LIMIT 1 ;
EOT
		);
		$res = $stmt->execute();

		if ($res === false) {
			return null;
		}

		$row = $stmt->fetch();

		if (!is_array($row)) {
			return null;
		}

		return $this->prepareEntity($row);
	}

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

        invalid_tree_records = dict()
        invalid_tq_records = dict()

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

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

                tree.update_node(job_record)

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

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

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

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


Question:
获取注册的标签
@param string $name
@return mixed

public static function getTag(string $name)
    {
        if (isset(self::$tags[$name])) {
            return self::$tags[$name];
        }
        $class = '\\sdopx\\plugin\\' . Utils::toCamel($name) . 'Tag';
        if (class_exists($class)) {
            self::$tags[$name] = new $class();
            return self::$tags[$name];
        }
        return null;
    }

protected function generateStandardUrl(array $urlParameters = array(), $absolute = false)
    {
        $urlParameters = $this->addRequestVariablesToUrlParameters($urlParameters);

        $anchor = '';
        if ($this->hasAnchor())
        {
            $anchor = '#'.$this->getAnchor();
        }

        return $this->getRouter()->generate($this->getRouteName(), $urlParameters, $absolute) . $anchor;
    }

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


Question: //SetGrayStroke set the grayscale for the stroke, takes a float64 between 0.0 and 1.0

func (gp *GoPdf) SetGrayStroke(grayScale float64) {
	gp.curr.grayStroke = grayScale
	gp.getContent().AppendStreamSetGrayStroke(grayScale)
}

def compute_colors_for_labels(self, labels):

        colors = labels[:, None] * self.palette
        colors = (colors % 255).numpy().astype("uint8")
        return colors

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


Question:
square root operation

        Returns
        -------
        Matrix : Matrix
            square root of self

def sqrt(self):

        if self.isdiagonal:
            return type(self)(x=np.sqrt(self.__x), isdiagonal=True,
                              row_names=self.row_names,
                              col_names=self.col_names,
                              autoalign=self.autoalign)
        elif self.shape[1] == 1: #a vector
            return type(self)(x=np.sqrt(self.__x), isdiagonal=False,
                              row_names=self.row_names,
                              col_names=self.col_names,
                              autoalign=self.autoalign)
        else:
            return type(self)(x=la.sqrtm(self.__x), row_names=self.row_names,
                              col_names=self.col_names,
                              autoalign=self.autoalign)

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:
Checks if the user given exists in the database.

@param User $aUser The user

@return bool

private function exist(User $aUser)
    {
        $count = $this->execute(
            'SELECT COUNT(*) FROM user WHERE id = :id', [':id' => $aUser->id()->id()]
        )->fetchColumn();

        return (int) $count === 1;
    }

private function create_basic_request($method) {
        $this->header_add(sprintf('%s %s %s', $method, $this->_path, $this->_protocol));
        $this->header_add(sprintf('Host: %s:%s', $this->_server, $this->_port));
        //$request .= sprintf('Connection: Keep-Alive');
        $this->header_add(sprintf('User-Agent: %s', $this->_user_agent));
        $this->header_add('Connection: TE');
        $this->header_add('TE: Trailers');
        if ($this->_auth == 'basic') {
            $this->header_add(sprintf('Authorization: Basic %s', base64_encode("$this->_user:$this->_pass")));
        } else if ($this->_auth == 'digest') {
            if ($signature = $this->digest_signature($method)){
                $this->header_add($signature);
            }
        } else if ($this->_auth == 'bearer') {
            $this->header_add(sprintf('Authorization: Bearer %s', $this->oauthtoken));
        }
    }

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


Question:
@param string                  $content
@param int                     $position
@param int                     $state
@param \ViKon\Parser\TokenList $tokenList

@throws \ViKon\Parser\Rule\RuleException

public function parseToken($content, $position, $state, TokenList $tokenList) {
        switch ($state) {
            case Lexer::STATE_MATCHED:
                $this->handleMatchedState($content, $position, $tokenList);
                break;
            default:
                parent::parseToken($content, $position, $state, $tokenList);
                break;
        }
    }

def parse_data_to_internal(self, data=None):

        if data is None:
            f = open(self.location_dat, "rb")
            data = {
                "PMCA SPECTRUM": {},
                "DATA": [],
                "DP5 CONFIGURATION": {},
                "DPP STATUS": {}
            }
            delimiter = {
                "PMCA SPECTRUM": " - ",
                "DP5 CONFIGURATION": "=",
                "DPP STATUS": ":"
            }
            comments = {
                "PMCA SPECTRUM": None,
                "DP5 CONFIGURATION": ";",
                "DPP STATUS": None
            }
            for e in f:
                if "<<" in e:
                    if "<<END>>" in e:
                        current = None
                    elif "<<PMCA SPECTRUM>>" in e:
                        current = "PMCA SPECTRUM"
                    elif "<<DATA>>" in e:
                        current = "DATA"
                    elif "<<DP5 CONFIGURATION>>" in e:
                        current = "DP5 CONFIGURATION"
                    elif "<<DPP STATUS>>" in e:
                        current = "DPP STATUS"
                    elif "<<ROI>>" in e:
                        current = "ROI"
                else:
                    if current == "DATA":
                        data["DATA"].append(float(e))
                    elif current == "ROI":
                        continue
                    elif current is not None:
                        e = e.split("\r\n")[0]
                        if comments[current] is not None:
                            e = e.split(comments[current], 1)[0]
                        e_list = e.split(delimiter[current], 1)
                        data[current][e_list[0]] = e_list[1]
            f.close()
        self.save_to_internal(data)

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


Question: Helper to process the xml response from AWS

def _process_request(self, request_type, params, marker_elems=None):

        response = self.make_request(request_type, params, verb='POST')
        return self._process_response(response, marker_elems)

@Override
    public java.util.concurrent.Future<PutItemResult> putItemAsync(String tableName, java.util.Map<String, AttributeValue> item,
            com.amazonaws.handlers.AsyncHandler<PutItemRequest, PutItemResult> asyncHandler) {

        return putItemAsync(new PutItemRequest().withTableName(tableName).withItem(item), asyncHandler);
    }

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


Question:
Transforms the GRASS bounds strings in metric or degree to decimal.

@param north the north string.
@param south the south string.
@param east the east string.
@param west the west string.
@return the array of the bounds in doubles.

@SuppressWarnings("nls")
    private double[] nsewStringsToNumbers( String north, String south, String east, String west ) {

        double no = -1.0;
        double so = -1.0;
        double ea = -1.0;
        double we = -1.0;

        if (north.indexOf("N") != -1 || north.indexOf("n") != -1) {
            north = north.substring(0, north.length() - 1);
            no = degreeToNumber(north);
        } else if (north.indexOf("S") != -1 || north.indexOf("s") != -1) {
            north = north.substring(0, north.length() - 1);
            no = -degreeToNumber(north);
        } else {
            no = Double.parseDouble(north);
        }
        if (south.indexOf("N") != -1 || south.indexOf("n") != -1) {
            south = south.substring(0, south.length() - 1);
            so = degreeToNumber(south);
        } else if (south.indexOf("S") != -1 || south.indexOf("s") != -1) {
            south = south.substring(0, south.length() - 1);
            so = -degreeToNumber(south);
        } else {
            so = Double.parseDouble(south);
        }
        if (west.indexOf("E") != -1 || west.indexOf("e") != -1) {
            west = west.substring(0, west.length() - 1);
            we = degreeToNumber(west);
        } else if (west.indexOf("W") != -1 || west.indexOf("w") != -1) {
            west = west.substring(0, west.length() - 1);
            we = -degreeToNumber(west);
        } else {
            we = Double.parseDouble(west);
        }
        if (east.indexOf("E") != -1 || east.indexOf("e") != -1) {
            east = east.substring(0, east.length() - 1);
            ea = degreeToNumber(east);
        } else if (east.indexOf("W") != -1 || east.indexOf("w") != -1) {
            east = east.substring(0, east.length() - 1);
            ea = -degreeToNumber(east);
        } else {
            ea = Double.parseDouble(east);
        }

        return new double[]{no, so, ea, we};
    }

def genbank_to_gene_coords(infile, genes):
    ''''''
    coords = {}

    for seq_record in SeqIO.parse(infile, "genbank"):
        for feature in seq_record.features:
            if feature.type == 'gene':
                gene_name = feature.qualifiers.get('gene', [None])[0]
                if gene_name not in genes:
                    continue

                if feature.location.strand == 1:
                    coords[gene_name] = {'start': int(feature.location.start), 'end': int(feature.location.end) - 1}
                else:
                    coords[gene_name] = {'end': int(feature.location.start), 'start': int(feature.location.end) - 1}

    return coords

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


Question:
remove the last . in the string it it ends with a .
            for the url structure must follow the flask routing format
            it should be /model/method instead of /model/method/

def blueprint_name_to_url(name):

        if name[-1:] == ".":
            name = name[:-1]
        name = str(name).replace(".", "/")
        return name

def resource_collection_create(self, data, **kwargs):
        ""
        api_path = "/api/v2/resource_collections.json"
        return self.call(api_path, method="POST", data=data, **kwargs)

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


Question: Adds the Wisdom annotation to the iPOJO manipulator.

@Override
    public void configure() {
        bind(Controller.class)
                .to(new AnnotationVisitorFactory() {
                    public AnnotationVisitor newAnnotationVisitor(BindingContext context) {
                        return new WisdomControllerVisitor(context.getWorkbench(), context.getReporter());
                    }
                });

        bind(Service.class)
                .to(new AnnotationVisitorFactory() {
                    public AnnotationVisitor newAnnotationVisitor(BindingContext context) {
                        return new WisdomServiceVisitor(context.getWorkbench(), context.getReporter());
                    }
                });

        bind(View.class)
                .when(on(ElementType.FIELD))
                .to(new AnnotationVisitorFactory() {
                    public AnnotationVisitor newAnnotationVisitor(BindingContext context) {
                        return new WisdomViewVisitor(context.getWorkbench(), context.getReporter(),
                                context.getFieldNode());
                    }
                });

        bind(Model.class)
                .when(on(ElementType.FIELD))
                .to(new AnnotationVisitorFactory() {
                    public AnnotationVisitor newAnnotationVisitor(BindingContext context) {
                        return new WisdomModelVisitor(context.getWorkbench(), context.getReporter(),
                                context.getFieldNode());
                    }
                });
    }

public void setupInMapper() {
        inputLabels = context.getConfiguration().getStrings(SimpleJob.FILETER_OUTPUT_LABELS);
        if (inputLabels == null) {
            inputLabels = context.getConfiguration().getStrings(SimpleJob.BEFORE_SUMMARIZER_OUTPUT_LABELS);
        }
        boolean label =
                context.getConfiguration().getStrings(SimpleJob.SUMMARIZER_OUTPUT_LABELS) == null ?
                        true : false;
        writer = new BasicWriter(label);
    }

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


Question:
Gets all issues for this file that have a certain severity.

@param string $severity The severity. Should be one of the Issue class' SEVERITY_* constants
@return Issue[] All issues with the given severity

public function getIssuesBySeverity(string $severity): array
    {
        return array_values(array_filter($this->getIssues(), function(Issue $i) use ($severity) {
            return $i->getSeverity() === $severity;
        }));
    }

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

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

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

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

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

		return $this->errorPayload;
	}

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


Question:
Get value for option "key".

    Resolution precedence is CLI option > target option > pants.ini option.

    :param options: Options returned by `task.get_option()`
    :param target: Target
    :param key: Key to get using the resolution precedence

def resolved_option(options, target, key):

    option_value = options.get(key)
    if not isinstance(target, AppBase) or options.is_flagged(key):
      return option_value
    v = target.payload.get_field_value(key, None)
    return option_value if v is None else v

func SetOrdererEnv(cmd *cobra.Command, args []string) {
	// read in the legacy logging level settings and, if set,
	// notify users of the FABRIC_LOGGING_SPEC env variable
	var loggingLevel string
	if viper.GetString("logging_level") != "" {
		loggingLevel = viper.GetString("logging_level")
	} else {
		loggingLevel = viper.GetString("logging.level")
	}
	if loggingLevel != "" {
		mainLogger.Warning("CORE_LOGGING_LEVEL is no longer supported, please use the FABRIC_LOGGING_SPEC environment variable")
	}
	// need to init logging here as cobra does not currently support
	// chaining PersistentPreRun functions
	loggingSpec := os.Getenv("FABRIC_LOGGING_SPEC")
	flogging.InitFromSpec(loggingSpec)
	// set the orderer environment from flags
	viper.Set("orderer.tls.rootcert.file", caFile)
	viper.Set("orderer.tls.clientKey.file", keyFile)
	viper.Set("orderer.tls.clientCert.file", certFile)
	viper.Set("orderer.address", OrderingEndpoint)
	viper.Set("orderer.tls.serverhostoverride", ordererTLSHostnameOverride)
	viper.Set("orderer.tls.enabled", tlsEnabled)
	viper.Set("orderer.tls.clientAuthRequired", clientAuth)
	viper.Set("orderer.client.connTimeout", connTimeout)
}

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


Question:
@param string $message

@return string

@throws ContainerExceptionInterface
@throws NotFoundExceptionInterface

private function getMessage(string $message): string
    {
        /** @var FormatterFactoryInterface $factory */
        $factory   = $this->getContainer()->get(FormatterFactoryInterface::class);
        $formatter = $factory->createFormatter(Messages::NAMESPACE_NAME);
        $result    = $formatter->formatMessage($message);

        return $result;
    }

public void warn (String msg, Object... args) {
    warn(format(msg, args), getCause(args));
  }

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


Question:
Return directory content or false on error

@param  string   $hash   file hash
@return array|false
@author Dmitry (dio) Levashov

public function scandir($hash) {
		if (($dir = $this->dir($hash)) == false) {
			return false;
		}

		return $dir['read']
			? $this->getScandir($this->decode($hash))
			: $this->setError(elFinder::ERROR_PERM_DENIED);
	}

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

func (s *DescribeParametersInput) SetSource(v string) *DescribeParametersInput {
	s.Source = &v
	return s
}

public <T> T getField(String locale, String key) {
    return localize(locale).getField(key);
  }

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


Question: // SetChapEnabled sets the ChapEnabled field's value.

func (s *DeviceiSCSIAttributes) SetChapEnabled(v bool) *DeviceiSCSIAttributes {
	s.ChapEnabled = &v
	return s
}

def probe_enable(cls, resource):

        oper = cls.call('hosting.rproxy.probe.enable', cls.usable_id(resource))
        cls.echo('Activating probe on %s' % resource)
        cls.display_progress(oper)
        cls.echo('The probe have been activated')
        return oper

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


Question: Validates that the conditions Hash follows an expected format

def conditions_hash_validations
      conditions.each do |comparator, mappings|
        errors.add(:conditions, "can't use undefined comparators") unless Scram::DSL::Definitions::COMPARATORS.keys.include? comparator.to_sym
        errors.add(:conditions, "comparators must have values of type Hash") unless mappings.is_a? Hash
      end
    end

public function setMinute($minute)
    {
        if (!preg_match(self::$_regex['minute'], $minute)) {
            throw new \InvalidArgumentException(sprintf('Minute "%s" is incorect', $minute));
        }

        $this->minute = $minute;

        return $this->generateHash();
    }

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


Question:
Return an index relative to the cursor position pointing to the end
        of the next word. Return `None` if nothing was found.

def find_next_word_ending(self, include_current_position=False, count=1, WORD=False):

        if count < 0:
            return self.find_previous_word_ending(count=-count, WORD=WORD)

        if include_current_position:
            text = self.text_after_cursor
        else:
            text = self.text_after_cursor[1:]

        regex = _FIND_BIG_WORD_RE if WORD else _FIND_WORD_RE
        iterable = regex.finditer(text)

        try:
            for i, match in enumerate(iterable):
                if i + 1 == count:
                    value = match.end(1)

                    if include_current_position:
                        return value
                    else:
                        return value + 1

        except StopIteration:
            pass

private function preIndent()
    {
        $prev = $this->tokens->getId($this->tokens->key() - 1);

        switch ($this->tokens->getId()) {
            case DocLexer::T_AT:
                if ($prev
                    && (DocLexer::T_COLON !== $prev)
                    && (DocLexer::T_COMMA !== $prev)
                    && (DocLexer::T_EQUALS !== $prev)
                    && (DocLexer::T_OPEN_CURLY_BRACES !== $prev)
                    && (DocLexer::T_OPEN_PARENTHESIS !== $prev)) {
                    $this->indent(true);
                }

                break;
            case DocLexer::T_CLOSE_CURLY_BRACES:
                $this->level--;

                if (DocLexer::T_OPEN_CURLY_BRACES !== $prev) {
                    $this->indent();
                }

                break;
            case DocLexer::T_CLOSE_PARENTHESIS:
                $this->level--;

                if (DocLexer::T_OPEN_PARENTHESIS !== $prev) {
                    $this->indent();
                }

                break;
        }
    }

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


Question:
// Diff returns a diff of two requested devices. If contextual diff is enabled,
// non-changed fields will still be returned.

func (r *RequestedDevice) Diff(other *RequestedDevice, contextual bool) *ObjectDiff {
	diff := &ObjectDiff{Type: DiffTypeNone, Name: "Device"}
	var oldPrimitiveFlat, newPrimitiveFlat map[string]string

	if reflect.DeepEqual(r, other) {
		return nil
	} else if r == nil {
		diff.Type = DiffTypeAdded
		newPrimitiveFlat = flatmap.Flatten(other, nil, true)
	} else if other == nil {
		diff.Type = DiffTypeDeleted
		oldPrimitiveFlat = flatmap.Flatten(r, nil, true)
	} else {
		diff.Type = DiffTypeEdited
		oldPrimitiveFlat = flatmap.Flatten(r, nil, true)
		newPrimitiveFlat = flatmap.Flatten(other, nil, true)
	}

	// Diff the primitive fields.
	diff.Fields = fieldDiffs(oldPrimitiveFlat, newPrimitiveFlat, contextual)

	return diff
}

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

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


Question:
Returns a BigQuery Extract Job configuration for the given source table, format and destination
URIs.

public static ExtractJobConfiguration of(
      TableId sourceTable, List<String> destinationUris, String format) {
    return newBuilder(sourceTable, destinationUris).setFormat(format).build();
  }

def export_model(model, model_type, export_dir, model_column_fn):

  wide_columns, deep_columns = model_column_fn()
  if model_type == 'wide':
    columns = wide_columns
  elif model_type == 'deep':
    columns = deep_columns
  else:
    columns = wide_columns + deep_columns
  feature_spec = tf.feature_column.make_parse_example_spec(columns)
  example_input_fn = (
      tf.estimator.export.build_parsing_serving_input_receiver_fn(feature_spec))
  model.export_savedmodel(export_dir, example_input_fn,
                          strip_default_attrs=True)

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


Question:
获取指数列表

    Keyword Arguments:
        ip {[type]} -- [description] (default: {None})
        port {[type]} -- [description] (default: {None})

    Returns:
        [type] -- [description]

def QA_fetch_get_index_list(ip=None, port=None):

    ip, port = get_mainmarket_ip(ip, port)
    api = TdxHq_API()
    with api.connect(ip, port):
        data = pd.concat(
            [pd.concat([api.to_df(api.get_security_list(j, i * 1000)).assign(sse='sz' if j == 0 else 'sh').set_index(
                ['code', 'sse'], drop=False) for i in range(int(api.get_security_count(j) / 1000) + 1)], axis=0) for j
                in range(2)], axis=0)
        # data.code = data.code.apply(int)
        sz = data.query('sse=="sz"')
        sh = data.query('sse=="sh"')

        sz = sz.assign(sec=sz.code.apply(for_sz))
        sh = sh.assign(sec=sh.code.apply(for_sh))
        return pd.concat([sz, sh]).query('sec=="index_cn"').sort_index().assign(
            name=data['name'].apply(lambda x: str(x)[0:6]))

def networks(self):

        import ns1.rest.ipam
        return ns1.rest.ipam.Networks(self.config)

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


Question:
/* (non-Javadoc)
@see org.springframework.jdbc.core.namedparam.SqlParameterSource#getValue(java.lang.String)

@Override
    public Object getValue(String paramName) throws IllegalArgumentException {
        if (!hasValue(paramName)) {
            throw new IllegalArgumentException("Can't find criteria with name " + paramName);
        }
        if (LIMIT_NAME.equals(paramName)) {
            return limit;
        }
        if (OFFSET_NAME.equals(paramName)) {
            return offset;
        }
        return criterias.get(paramName).getValue();
    }

protected static JRDesignExpression getExpressionFromVariable(JRDesignVariable var){
		JRDesignExpression exp = new JRDesignExpression();
		exp.setText("$V{" + var.getName() + "}");
		exp.setValueClass(var.getValueClass());
		return exp;
	}

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


Question:
Scanning local plugin directories and third-party plugin packages.

        :returns: No return, but self.__plugins will be updated

        :raises: PluginError: raises an exception, maybe CSSLoadError, VersionError, based PluginError

def __scanPlugins(self):

        self.logger.info("Initialization Plugins Start, local plugins path: %s, third party plugins: %s" % (self.plugins_abspath, self.plugin_packages))

        #: Load third-party plugins
        if self.plugin_packages and isinstance(self.plugin_packages, (list, tuple)):
            for package_name in self.plugin_packages:
                try:
                    plugin = __import__(package_name)
                except ImportError as e:
                    raise PluginError("ImportError for %s, detail is %s" %(package_name, e))
                else:
                    plugin_abspath = os.path.dirname(os.path.abspath(plugin.__file__))
                    self.__loadPlugin(plugin, plugin_abspath, package_name)

        #: Load local plug-in directory
        if os.path.isdir(self.plugins_abspath) and os.path.isfile(os.path.join(self.plugins_abspath, "__init__.py")):
            for package_name in os.listdir(self.plugins_abspath):
                package_abspath = os.path.join(self.plugins_abspath, package_name)
                if os.path.isdir(package_abspath) and os.path.isfile(os.path.join(package_abspath, "__init__.py")):
                    self.logger.info("find plugin package: %s" % package_name)
                    #: Dynamic load module (plugins.package): you can query custom information and get the plugin's class definition through getPluginClass
                    plugin = __import__("{0}.{1}".format(self.plugins_folder, package_name), fromlist=[self.plugins_folder, ])
                    self.__loadPlugin(plugin, package_abspath, package_name)

public function decorateException($error)
    {
        $application = $this->application;

        if (is_callable($error)) {
            $error = $application->getContainer()->call($error, [$application]);
        }

        if (is_object($error) && !($error instanceof \Exception)) {
            $error = method_exists($error,
                '__toString') ? $error->__toString() : 'Error with object ' . get_class($error);
        }

        if (is_resource($error)) {
            $error = 'Error with resource type ' . get_resource_type($error);
        }

        if (is_array($error)) {
            $error = implode("\n", $error);
        }

        if (!($error instanceof \Exception)) {
            $error = new \Exception(is_scalar($error) ? $error : 'Error with ' . gettype($error));
        }

        return $error;
    }

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


Question: Set domain of the colors based on min and max of a list of values.

def set_domain(self, values):
        """"""
        _flattenedList = sorted(flatten(values))
        self.domain = tuple(_flattenedList[0] if d == 'min' else d for d in self.domain)
        self.domain = tuple(_flattenedList[-1] if d == 'max' else d for d in self.domain)

public void setOutRGB(IntRange outRGB) {
        this.outRed = outRGB;
        this.outGreen = outRGB;
        this.outBlue = outRGB;

        CalculateMap(inRed, outRGB, mapRed);
        CalculateMap(inGreen, outRGB, mapGreen);
        CalculateMap(inBlue, outRGB, mapBlue);
    }

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


Question:
Validates VAT.

@param \OxidEsales\Eshop\Application\Model\CompanyVatIn $oVatIn Company VAT identification number object.

@return bool

public function validate(\OxidEsales\Eshop\Application\Model\CompanyVatIn $oVatIn)
    {
        $oCheckVat = new stdClass();
        $oCheckVat->countryCode = $oVatIn->getCountryCode();
        $oCheckVat->vatNumber = $oVatIn->getNumbers();

        $blResult = $this->_checkOnline($oCheckVat);
        if (!$blResult) {
            $this->setError('ID_NOT_VALID');
        }

        return $blResult;
    }

def format_company(organization)
      {
        company_id: organization.id,
        name: organization.name,
        created_at: organization.created_at.to_i,
        custom_attributes: {
          industry: organization.industry,
          size: organization.size,
          credit_card_details: organization.has_credit_card_details?,
          credit_card_expiry: organization.credit_card.expiry_date,
          app_count: organization.app_instances.count,
          app_list: organization.app_instances.map(&:name).sort.to_sentence,
          user_count: organization.users.count
        }
      }
    end

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


Question:
判断指定数组dests中是否包含指定数据src
@param src 数据
@param dests 数组，不能为空
@return 返回true表示dests中包含src

public static boolean contains(Object src, Object... dests) {
        if (dests == null) {
            throw new NullPointerException("dest must not be null");
        }

        if (src == null) {
            return false;
        }

        for (Object dest : dests) {
            if (src == dest || src.equals(dest)) {
                return true;
            }
        }
        return false;
    }

public static Pair<Optional<Table>, Optional<List<Partition>>> getDestinationTableMeta(String dbName,
      String tableName, Properties props) {

    Optional<Table> table = Optional.<Table>absent();
    Optional<List<Partition>> partitions = Optional.<List<Partition>>absent();

    try {
      HiveMetastoreClientPool pool = HiveMetastoreClientPool.get(props,
          Optional.fromNullable(props.getProperty(HiveDatasetFinder.HIVE_METASTORE_URI_KEY)));
      try (AutoReturnableObject<IMetaStoreClient> client = pool.getClient()) {
        table = Optional.of(client.get().getTable(dbName, tableName));
        if (table.isPresent()) {
          org.apache.hadoop.hive.ql.metadata.Table qlTable = new org.apache.hadoop.hive.ql.metadata.Table(table.get());
          if (HiveUtils.isPartitioned(qlTable)) {
            partitions = Optional.of(HiveUtils.getPartitions(client.get(), qlTable, Optional.<String>absent()));
          }
        }
      }
    } catch (NoSuchObjectException e) {
      return ImmutablePair.of(table, partitions);
    } catch (IOException | TException e) {
      throw new RuntimeException("Could not fetch destination table metadata", e);
    }

    return ImmutablePair.of(table, partitions);
  }

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


Question: Begin capturing PCAPs and sending them to workbench

def execute(self):
        '''  '''

        # Create a temporary directory
        self.temp_dir = tempfile.mkdtemp()
        os.chdir(self.temp_dir)

        # Spin up the directory watcher
        DirWatcher(self.temp_dir, self.file_created)

        # Spin up tcpdump
        self.subprocess_manager(self.tcpdump_cmd)

func (e *endpoint) WritePacket(r *stack.Route, _ *stack.GSO, hdr buffer.Prependable, payload buffer.VectorisedView, protocol tcpip.NetworkProtocolNumber) *tcpip.Error {
	// Add the ethernet header here.
	eth := header.Ethernet(hdr.Prepend(header.EthernetMinimumSize))
	ethHdr := &header.EthernetFields{
		DstAddr: r.RemoteLinkAddress,
		Type:    protocol,
	}
	if r.LocalLinkAddress != "" {
		ethHdr.SrcAddr = r.LocalLinkAddress
	} else {
		ethHdr.SrcAddr = e.addr
	}
	eth.Encode(ethHdr)

	v := payload.ToView()
	// Transmit the packet.
	e.mu.Lock()
	ok := e.tx.transmit(hdr.View(), v)
	e.mu.Unlock()

	if !ok {
		return tcpip.ErrWouldBlock
	}

	return nil
}

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


Question: Run the ontology mapping on the statements.

def map_statements(self):
        """"""
        for stmt in self.statements:
            for agent in stmt.agent_list():
                if agent is None:
                    continue
                all_mappings = []
                for db_name, db_id in agent.db_refs.items():
                    if isinstance(db_id, list):
                        db_id = db_id[0][0]
                    mappings = self._map_id(db_name, db_id)
                    all_mappings += mappings
                for map_db_name, map_db_id, score, orig_db_name in all_mappings:
                    if map_db_name in agent.db_refs:
                        continue
                    if self.scored:
                        # If the original one is a scored grounding,
                        # we take that score and multiply it with the mapping
                        # score. Otherwise we assume the original score is 1.
                        try:
                            orig_score = agent.db_refs[orig_db_name][0][1]
                        except Exception:
                            orig_score = 1.0
                        agent.db_refs[map_db_name] = \
                            [(map_db_id, score * orig_score)]
                    else:
                        if map_db_name in ('UN', 'HUME'):
                            agent.db_refs[map_db_name] = [(map_db_id, 1.0)]
                        else:
                            agent.db_refs[map_db_name] = map_db_id

def write_summary_cnts(self, go_ids):
        """"""
        obo = self.obo
        cnts = self.get_cnts_levels_depths_recs([obo.get(GO) for GO in go_ids])
        self._write_summary_cnts(cnts)

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


Question:
Instantiate value with the given name.

@param string $valueName The name of the value.

@return static The newly instantiated value.

private static function instantiate(string $valueName): self
    {
        $value = new static(...(array) self::constant($valueName));
        $value->name = $valueName;

        return $value;
    }

protected function setValue(array $return, Configuration $configuration, Parameter $parameter)
  {
    $key   = $configuration->getRenameTo() !== null ? $configuration->getRenameTo() : $configuration->getKey();
    $array = array($key => $parameter->getValue());

    return array_merge($return, $array);
  }

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


Question:
Returns an English label for a given datatype.

@param datatype
the datatype to label
@return the label

private String getDatatypeLabel(DatatypeIdValue datatype) {
		if (datatype.getIri() == null) { // TODO should be redundant once the
											// JSON parsing works
			return "Unknown";
		}

		switch (datatype.getIri()) {
		case DatatypeIdValue.DT_COMMONS_MEDIA:
			return "Commons media";
		case DatatypeIdValue.DT_GLOBE_COORDINATES:
			return "Globe coordinates";
		case DatatypeIdValue.DT_ITEM:
			return "Item";
		case DatatypeIdValue.DT_QUANTITY:
			return "Quantity";
		case DatatypeIdValue.DT_STRING:
			return "String";
		case DatatypeIdValue.DT_TIME:
			return "Time";
		case DatatypeIdValue.DT_URL:
			return "URL";
		case DatatypeIdValue.DT_PROPERTY:
			return "Property";
		case DatatypeIdValue.DT_EXTERNAL_ID:
			return "External identifier";
		case DatatypeIdValue.DT_MATH:
			return "Math";
		case DatatypeIdValue.DT_MONOLINGUAL_TEXT:
			return "Monolingual Text";
		default:
			throw new RuntimeException("Unknown datatype " + datatype.getIri());
		}
	}

public function formatOutput(Route $route, Output $output, $type = self::STYLE_DETAIL)
    {
        switch ($type) {
            case self::STYLE_DETAIL:
                $output->write('Route [');
                $output->write('<success>"' . $route->getName() . '"</success>');
                $output->writeln(']');
                $output->writeln("Path:\t\t" . str_replace('//', '/', $route->getPath()));
                $output->writeln("Method:\t\t" . $route->getMethod());
                $output->writeln("Format:\t\t" . implode(', ', $route->getFormats()));
                $output->writeln("Callback:\t" . (is_callable($route->getCallback()) ? 'Closure' : $route->getCallback()));
                $output->writeln("Defaults:\t" . implode(', ', $route->getDefaults()));
                $output->writeln("Requirements:\t" . implode(', ', $route->getRequirements()));
                $output->writeln("Path-Regex:\t" . $route->getPathRegex());
                $output->writeln('');
                break;
            case self::STYLE_LIST:
            default:
                $name = $route->getName();
                $method = $route->getMethod();
                $schema = $route->getScheme() ?? 'http';
                $path = $route->getPath();
                $output->write($name . str_repeat(' ', 25 - strlen($name)));
                $output->write($method . str_repeat(' ', 15 - strlen($method)));
                $output->write($schema . str_repeat(' ', 15 - strlen($schema)));
                $output->writeln($path);
        }

        return;
    }

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


Question:
Get label name.

@return [[@doctodo return_type:getLabelName]] [[@doctodo return_description:getLabelName]]

public function getLabelName()
    {
        if (is_null($this->_labelName)) {
            $this->_labelName = $this->name;
            $storage = $this->storage;
            if (!empty($storage)) {
                if (empty($this->_labelName)) {
                    $this->_labelName = $storage->file_name;
                } else {
                    $this->_labelName .= " ({$storage->file_name})";
                }
            }
        }

        return $this->_labelName;
    }

function(item_data){
      var item_text, // The text that will display in the item
          todo_div, todo_checkbox, todo_delete, todo_wrapper; // DOM elements (main div, checkbox that indicates done-ness)

      todo.data[item_data.__id__] = item_data;

      item_text = ''; // By default, start with an empty string.
      if (item_data.hasOwnProperty('deadline')){ // Parse how much time is left to complete this task.
        parsed_deadline = todo.parse_remaining_time(item_data.deadline.timestamp);
        if (parsed_deadline <= 0){
          item_text += 'Overdue'; // If time is up, put a bold "Overdue" flag on the item.
        } else {
        item_text += 'Due in ' + parsed_deadline + ' hours.'; // Else, put a subtler flag indicating the hours left to complete the task.
        }
      }
      // Build the elements
      todo_wrapper = $('
');
      todo_div = $('
' + item_text + '
');
      todo_div.find('.value').text(item_data.text); // Use $.text() to prevent script injection
      todo_checkbox = $('<input type="checkbox" />'),
      todo_delete = $('

');

      // Styling for if the item is done: "done" class crosses out text and makes it lighter. Check off the checkbox, too.
      if (item_data.done){
        todo_div.addClass('done');
        todo_checkbox.attr('checked', true);
      }

      /*
        Prepend the checkbox to the div element and give the whole thing
        a click function to toggle the listing's done status.
        (This is just for UI's sake: it's easier to click the whole thing than ticking the checkbox itself.
        The CSS cursor: pointer on the item will make it clear that it's clickable)
      */
      todo_div.prepend(todo_checkbox).click(function(){
        var item_data = todo.data[$(this).parent().attr('item')];
        todo.toggle_item(item_data);
      }).css({
        background: todo.priority_colors[item_data.priority] // Give the item the color corresponding to its priority level.
      });

      // Bind click event to the delete button
      todo_delete.click(function(e){
        e.stopPropagation();
        todo.delete_item($(this).parent().parent().attr('item'))
      });

      // Commit the element to the page.
      $(todo_div).append(todo_delete);
      $(todo_wrapper).prepend(todo_div);
      $('#todo').prepend(todo_wrapper);

      // In case this is the first item added, hide the "You haven't added any items yet" message.
      $('#empty_list').hide();
    }

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


Question:
Converts a collection of dates to a JSON array with the long representation of the dates as strings.
@param dates the list to convert.
@return JSON array with long values of dates as string

private JSONValue datesToJsonArray(Collection<Date> dates) {

        if (null != dates) {
            JSONArray result = new JSONArray();
            for (Date d : dates) {
                result.set(result.size(), dateToJson(d));
            }
            return result;
        }
        return null;
    }

public static ResultMap getResultMap(Configuration configuration,Class<?> entityClass) {
        List<ResultMapping> resultMappings = new ArrayList<ResultMapping>();

        Set<ColumnMapper> entityClassColumns = EntityHelper.getEntityMapper(entityClass).getColumnsMapper();
        for (ColumnMapper entityColumn : entityClassColumns) {
            ResultMapping.Builder builder = new ResultMapping.Builder(configuration, entityColumn.getProperty(), entityColumn.getColumn(), entityColumn.getJavaType());
            if (entityColumn.getJdbcType() != null) {
                builder.jdbcType(entityColumn.getJdbcType());
            }

            List<ResultFlag> flags = new ArrayList<ResultFlag>();
            if (entityColumn.isId()) {
                flags.add(ResultFlag.ID);
            }
            builder.flags(flags);
            builder.lazy(false);
            resultMappings.add(builder.build());
        }
        ResultMap.Builder builder = new ResultMap.Builder(configuration, "BaseResultMap", entityClass, resultMappings, true);
        return builder.build();
    }

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


Question: Opens a dialog allowing the user to pick a measurement file

def choose_meas_file(self, event=None):

        dlg = wx.FileDialog(
            self, message="Please choose a measurement file",
            defaultDir=self.WD,
            defaultFile="measurements.txt",
            wildcard="measurement files (*.magic,*.txt)|*.magic;*.txt",
            style=wx.FD_OPEN | wx.FD_CHANGE_DIR
        )
        if self.show_dlg(dlg) == wx.ID_OK:
            meas_file = dlg.GetPath()
            dlg.Destroy()
        else:
            meas_file = ''
            self.data_model = 2.5
            dlg.Destroy()
        return meas_file

def dashboard_import(self, name, fileobj):

        data = self._upload(fileobj)
        return self.raw_query('dashboard', 'importTab', data={
            'filename': data['filename'],
            'name': name,
        })

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


Question:
// NewLookAheadBufferUsing returns a new LookAheadBuffer which uses the
// provided buffer as its raw buffer.  This allows buffer reuse, which reduces
// unnecessary memory allocation.

func NewLookAheadBufferUsing(src io.Reader, rawBuffer []byte) *LookAheadBuffer {
	return &LookAheadBuffer{
		src:           src,
		buffer:        rawBuffer,
		bytesBuffered: 0,
	}
}

def list
      # TODO: remove dependency on Guard in this whole file
      # collect metadata
      data = PluginUtil.plugin_names.sort.inject({}) do |hash, name|
        hash[name.capitalize] = Guard.state.session.plugins.all(name).any?
        hash
      end

      # presentation
      header = [:Plugin, :Guardfile]
      final_rows = []
      data.each do |name, used|
        final_rows << { Plugin: name, Guardfile: used ? "✔" : "✘" }
      end

      # render
      Formatador.display_compact_table(final_rows, header)
    end

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


Question:
Checks whether or not the method is safe.

@see https://tools.ietf.org/html/rfc7231#section-4.2.1

@param bool $andCacheable Adds the additional condition that the method should be cacheable. True by default.

@return bool

public function isMethodSafe(/* $andCacheable = true */)
    {
        if (!func_num_args() || func_get_arg(0)) {
            // This deprecation should be turned into a BadMethodCallException in 4.0 (without adding the argument in the signature)
            // then setting $andCacheable to false should be deprecated in 4.1
            @trigger_error('Checking only for cacheable HTTP methods with Symfony\Component\HttpFoundation\Request::isMethodSafe() is deprecated since version 3.2 and will throw an exception in 4.0. Disable checking only for cacheable methods by calling the method with `false` as first argument or use the Request::isMethodCacheable() instead.', E_USER_DEPRECATED);

            return in_array($this->getMethod(), array('GET', 'HEAD'));
        }

        return in_array($this->getMethod(), array('GET', 'HEAD', 'OPTIONS', 'TRACE'));
    }

public function tailable($tail = true)
    {
        $tail = (boolean) $tail;
        $this->tailable = $tail;
        $this->riakCursor->tailable($tail);
        return $this;
    }

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


Question:
Read all translation strings from a file located into a module.

@param	Module|NULL		Module object or NULL to read the common translation file.

@return	array:string

public function readTranslation($module) {

		// get the right translation folder
		$file = APPLICATION_PATH . (is_a($module,'Pair\Module') ? '/modules/' . $module->name : '') . '/translations/' . $this->getRepresentation() . '.ini';

		// checks that folder exists
		if (file_exists($file)) {

			// scans file and gets translation strings
			$strings = parse_ini_file($file);
			return (is_array($strings) ? $strings : array());

		} else {

			return array();

		}

	}

public function getKeywords(array $languageCodes)
    {
        $keywords = [];

        foreach ($languageCodes as $languageCode) {
            if (isset($this->keywords[$languageCode])) {
                $keywords[$languageCode] = $this->keywords[$languageCode];
            }
        }

        if (empty($keywords)) {
            return [
                $this->mainLanguageCode => $this->getKeyword($this->mainLanguageCode),
            ];
        }

        return $keywords;
    }

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


Question: // SetApplicationName sets the ApplicationName field's value.

func (s *ApplicationInfo) SetApplicationName(v string) *ApplicationInfo {
	s.ApplicationName = &v
	return s
}

func (s *DescribeActivityTypeInput) SetActivityType(v *ActivityType) *DescribeActivityTypeInput {
	s.ActivityType = v
	return s
}

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


Question:
Default mailer.

@param  mixed
@param  string

@return void
@internal

public function defaultMailer($message, string $email): void
    {
        $host = \preg_replace('#[^\w.-]+#', '', $_SERVER['HTTP_HOST'] ?? php_uname('n'));
        $parts = \str_replace(
            ["\r\n", "\n"],
            ["\n", PHP_EOL],
            [
                'headers' => \implode("\n", [
                        'From: ' . ($this->fromEmail ?: "noreply@$host"),
                        'X-Mailer: Tracy',
                        'Content-Type: text/plain; charset=UTF-8',
                        'Content-Transfer-Encoding: 8bit',
                    ]) . "\n",
                'subject' => "PHP: An error occurred on the server $host",
                'body' => Dumper::formatMessage($message) . "\n\nsource: " . Helpers::getSource(),
            ]
        );

        \mail($email, $parts['subject'], $parts['body'], $parts['headers']);
    }

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


Question:
Generate a Facebook recommend button (which is a like button,
but with a different action / label)

@param array $params Various Facebook URL parameters
@param bool $useFacebookPageAsUrl
@return string

public function facebookRecommendButton(
        array $params = array(), $useFacebookPageAsUrl = false
    ) {
        $this->_needsFacebookInit = true;
        $params['action'] = 'recommend';
        return $this->facebookLikeButton($params, $useFacebookPageAsUrl);
    }

function createPhotoUrl(id, farm, server, secret, size) {
		size = (size) ? '_' + size : '';
		return 'https://farm' + farm + '.staticflickr.com/' + server + '/' + id + '_' + secret + size + '.jpg';
	}

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


Question: // Clone creates a new volume from an existing volume

func (s *VolumeServer) Clone(
	ctx context.Context,
	req *api.SdkVolumeCloneRequest,
) (*api.SdkVolumeCloneResponse, error) {
	if s.cluster() == nil || s.driver(ctx) == nil {
		return nil, status.Error(codes.Unavailable, "Resource has not been initialized")
	}

	if len(req.GetName()) == 0 {
		return nil, status.Error(
			codes.InvalidArgument,
			"Must supply a uniqe name")
	} else if len(req.GetParentId()) == 0 {
		return nil, status.Error(
			codes.InvalidArgument,
			"Must parent volume id")
	}

	locator := &api.VolumeLocator{
		Name: req.GetName(),
	}
	source := &api.Source{
		Parent: req.GetParentId(),
	}

	// Get spec. This also checks if the parend id exists.
	// This will also check for Ownership_Read access.
	parentVol, err := s.Inspect(ctx, &api.SdkVolumeInspectRequest{
		VolumeId: req.GetParentId(),
	})
	if err != nil {
		return nil, err
	}

	// Create the clone
	id, err := s.create(ctx, locator, source, parentVol.GetVolume().GetSpec())
	if err != nil {
		return nil, err
	}

	return &api.SdkVolumeCloneResponse{
		VolumeId: id,
	}, nil
}

def restore_replicas(self) -> None:
        '''

        '''
        self.backup_instances_faulty.clear()
        for inst_id in range(self.node.requiredNumberOfInstances):
            if inst_id not in self.node.replicas.keys():
                self.node.replicas.add_replica(inst_id)

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