Question:
Pick a channel and start the call.

@param mixed $data     The data to send
@param array $metadata Metadata to send with the call, if applicable
(optional)
@param array $options  An array of options, possible keys:
'flags' => a number (optional)

public function start($argument, $metadata, $options)
    {
        $channel_ref = $this->_rpcPreProcess($argument);
        $real_channel = $channel_ref->getRealChannel($this->gcp_channel->credentials);
        $this->createRealCall($real_channel);
        $this->real_call->start($argument, $metadata, $options);
    }

func (c *Call) matches(args []interface{}) error {
	if !c.methodType.IsVariadic() {
		if len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}

		for i, m := range c.args {
			if !m.Matches(args[i]) {
				return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
					c.origin, strconv.Itoa(i), args[i], m)
			}
		}
	} else {
		if len(c.args) < c.methodType.NumIn()-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of matchers. Got: %d, want: %d",
				c.origin, len(c.args), c.methodType.NumIn()-1)
		}
		if len(c.args) != c.methodType.NumIn() && len(args) != len(c.args) {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: %d",
				c.origin, len(args), len(c.args))
		}
		if len(args) < len(c.args)-1 {
			return fmt.Errorf("Expected call at %s has the wrong number of arguments. Got: %d, want: greater than or equal to %d",
				c.origin, len(args), len(c.args)-1)
		}

		for i, m := range c.args {
			if i < c.methodType.NumIn()-1 {
				// Non-variadic args
				if !m.Matches(args[i]) {
					return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
						c.origin, strconv.Itoa(i), args[i], m)
				}
				continue
			}
			// The last arg has a possibility of a variadic argument, so let it branch

			// sample: Foo(a int, b int, c ...int)
			if i < len(c.args) && i < len(args) {
				if m.Matches(args[i]) {
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, gomock.Any())
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, someSliceMatcher)
					// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC)
					// Got Foo(a, b) want Foo(matcherA, matcherB)
					// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD)
					continue
				}
			}

			// The number of actual args don't match the number of matchers,
			// or the last matcher is a slice and the last arg is not.
			// If this function still matches it is because the last matcher
			// matches all the remaining arguments or the lack of any.
			// Convert the remaining arguments, if any, into a slice of the
			// expected type.
			vargsType := c.methodType.In(c.methodType.NumIn() - 1)
			vargs := reflect.MakeSlice(vargsType, 0, len(args)-i)
			for _, arg := range args[i:] {
				vargs = reflect.Append(vargs, reflect.ValueOf(arg))
			}
			if m.Matches(vargs.Interface()) {
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, someSliceMatcher)
				// Got Foo(a, b) want Foo(matcherA, matcherB, gomock.Any())
				// Got Foo(a, b) want Foo(matcherA, matcherB, someEmptySliceMatcher)
				break
			}
			// Wrong number of matchers or not match. Fail.
			// Got Foo(a, b) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c, d) want Foo(matcherA, matcherB, matcherC, matcherD, matcherE)
			// Got Foo(a, b, c, d, e) want Foo(matcherA, matcherB, matcherC, matcherD)
			// Got Foo(a, b, c) want Foo(matcherA, matcherB)
			return fmt.Errorf("Expected call at %s doesn't match the argument at index %s.\nGot: %v\nWant: %v",
				c.origin, strconv.Itoa(i), args[i:], c.args[i])

		}
	}

	// Check that all prerequisite calls have been satisfied.
	for _, preReqCall := range c.preReqs {
		if !preReqCall.satisfied() {
			return fmt.Errorf("Expected call at %s doesn't have a prerequisite call satisfied:\n%v\nshould be called before:\n%v",
				c.origin, preReqCall, c)
		}
	}

	// Check that the call is not exhausted.
	if c.exhausted() {
		return fmt.Errorf("Expected call at %s has already been called the max number of times.", c.origin)
	}

	return nil
}

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


Question:
使用 :mod:`subprocess` 模块调用 ``KindleGen`` 工具，
        将已准备好的书籍源文件编译生成 ``mobi`` 文件

def generate_mobi_file(self):
        '''

        '''
        opf_file = os.path.join(self.build_source_dir, 'moear.opf')
        command_list = [self.kg, opf_file]
        output = subprocess.Popen(
            command_list, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            shell=False).communicate()
        self._logger.info('生成命令: {}'.format(' '.join(command_list)))
        self._logger.info('生成 mobi : {}'.format(
            output[0].decode()))
        if output[1]:
            self._logger.error(output[1].decode())
            raise IOError('KindleGen转换失败: {}'.format(output[1]))

public function get_sha1() {

        if ($this->plugin && $this->editor) {
            $plugin = $this->get_submission_plugin();
            $options = portfolio_format_text_options();
            $options->context = context_module::instance($this->cmid);

            $text = format_text($plugin->get_editor_text($this->editor, $this->sid),
                                $plugin->get_editor_format($this->editor, $this->sid),
                                $options);
            $textsha1 = sha1($text);
            $filesha1 = '';
            try {
                $filesha1 = $this->get_sha1_file();
            } catch (portfolio_caller_exception $e) {
                // No files.
            }
            return sha1($textsha1 . $filesha1);
        }
        return $this->get_sha1_file();
    }

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


Question:
Rename a form tab after form fields have been configured.

TODO: groups of the renamed tab are still prefixed with the old tab name

@param type $tabName    the name of the tab to be renamed
@param type $newTabName the new name for the tab

public function renameFormTab($tabName, $newTabName, $keepOrder = true)
    {
        $tabs = $this->getFormTabs();

        if (!$tabs) {
            return;
        }

        if (!isset($tabs[$tabName])) {
            throw new \Exception(sprintf('Tab %s does not exist.', $tabName));
        }
        if (isset($tabs[$newTabName])) {
            return;
        }

        if ($keepOrder) {
            $keys = array_keys($tabs);
            $keys[array_search($tabName, $keys)] = $newTabName;
            $tabs = array_combine($keys, $tabs);
        } else {
            $tabs[$newTabName] = $tabs[$tabName];
            unset($tabs[$tabName]);
        }

        $this->setFormTabs($tabs);
    }

public function addMessage($label, $message, array $args = [])
    {
        $name = $this->generateName($label).'_message';
        $args = array_merge([
            'label' => $label,
            'message' => $message,
        ], $args);

        return $this->addField($name, 'message', $args);
    }

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


Question:
Handle OPTIONS requests.

Return information about the server's current configuration. Useful to get the protocol
version, the maximum upload file size and supported extensions.

@return \Psr\Http\Message\ResponseInterface

protected function handleOPTIONS(): ResponseInterface
	{
		return $this->response->withStatus(204)
		                      ->withHeader("Tus-Version", self::PROTOCOL_VERSION)
		                      ->withHeader("Tus-Max-Size", $this->uploadMaxFileSize)
		                      ->withHeader("Tus-Extension", "creation,checksum,termination,crosscheck,express");
	}

public static function toCake(PsrResponse $response)
    {
        $body = static::getBody($response);
        $data = [
            'status' => $response->getStatusCode(),
            'body' => $body['body'],
        ];
        $cake = new CakeResponse($data);
        if ($body['file']) {
            $cake->file($body['file']);
        }
        $cookies = static::parseCookies($response->getHeader('Set-Cookie'));
        foreach ($cookies as $cookie) {
            $cake->cookie($cookie);
        }
        $headers = static::collapseHeaders($response);
        $cake->header($headers);

        if (!empty($headers['Content-Type'])) {
            $cake->type($headers['Content-Type']);
        }

        return $cake;
    }

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


Question: Mojo entry point.

@Override
    public void execute() throws MojoExecutionException {

        try {
            if (getBootstrapPacksInfo().isEmpty()) {
                getLog().error("Could not find any Celerio Template Pack having a META-INF/celerio.txt file on the classpath!");
                return;
            }
            celerioWelcomeBanner();

            JdbcConnectivity jdbcConnectivity = null;

            if (useCommandLineParameters()) {
                jdbcConnectivity = setUpParamValuesAndReturnJdbcConnectivity();

                TemplatePackInfo tpi = getBootstrapPackInfoByName(bootstrapPackName);
                packCommand = tpi.getCommand();
                packCommandHelp = tpi.getCommandHelp();
            } else {
                if (isInteractive()) {
                    startInteractiveConfWizard();
                } else {
                    useDefaultConf();
                }
            }

            runCelerioInBootstrapMode(jdbcConnectivity);

            copySqlConf();

            copyCelerioXsd();

            printInstructionsOnceBootstrapIsReady();

        } catch (Exception e) {
            getLog().error(e.getMessage());
            throw new MojoExecutionException(e.getLocalizedMessage(), e);
        }
    }

public static Anima open(String url, String user, String pass, Quirks quirks) {
        return open(new Sql2o(url, user, pass, quirks));
    }

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


Question:
Create a new model instance by type.

        :rtype: Model

def _create_model_by_type(self, type):

        klass = None
        for cls in eloquent.orm.model.Model.__subclasses__():
            morph_class = cls.__morph_class__ or cls.__name__
            if morph_class == type:
                klass = cls
                break

        return klass()

def add(self, child):

        if isinstance(child, Run):
            self.add_run(child)
        elif isinstance(child, Record):
            self.add_record(child)
        elif isinstance(child, EventRecord):
            self.add_event_record(child)
        elif isinstance(child, DataDisplay):
            self.add_data_display(child)
        elif isinstance(child, DataWriter):
            self.add_data_writer(child)
        elif isinstance(child, EventWriter):
            self.add_event_writer(child)
        else:
            raise ModelError('Unsupported child element')

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


Question:
Render the paginator using the given view.

@param  string|null  $view
@param  array  $data
@return string

public function render($view = null, $data = array())
    {
        if (is_null($view)) {
            $view = static::$defaultSimpleView;
        }

        $data = array_merge($data, array(
            'paginator' => $this,
        ));

        return new HtmlString(
            static::viewFactory()->make($view, $data)->render()
        );
    }

def all(path, options = {}, &block)
      all = []
      list_type, list_item = get_list_types(path)

      result = request('GET', path, options)
      raise RequestError.new result.status if result.status_code != 200 or result.parsed[list_type].nil?

      total = result.parsed[list_type]['totalItems'].to_i
      items = result.parsed[list_type]['itemsInPage'].to_i
      return all if total == 0

      pages = (total / config.page_size) + 1
      (0 .. pages - 1).each do |i|
        options[:query][:pgNum] = i
        result     = request('GET', path, options)
        raise RequestError.new result.status if result.status_code != 200
        list_items = result.parsed[list_type][list_item]
        list_items = [ list_items ] if items == 1
        list_items.each { |item| yield item if block_given? }
        all.concat list_items
      end
      all
    end

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


Question:
Decorator to cast return of function as the given type

    Parameters
    ----------
    returntype : `type`
        the desired return type of the decorated function

def return_as(returntype):

    def decorator(func):
        # @wraps(func) <- we can't use this as normal because it doesn't work
        #                 on python < 3 for instance methods,
        #                 see workaround below
        def wrapped(*args, **kwargs):
            result = func(*args, **kwargs)
            try:
                return returntype(result)
            except (TypeError, ValueError) as exc:
                exc.args = (
                    'failed to cast return from {0} as {1}: {2}'.format(
                        func.__name__, returntype.__name__, str(exc)),
                )
                raise
        try:
            return wraps(func)(wrapped)
        except AttributeError:  # python < 3.0.0
            wrapped.__doc__ == func.__doc__
            return wrapped

    return decorator

func (p *Params) Bind(dest interface{}, name string) {
	value := reflect.ValueOf(dest)
	if value.Kind() != reflect.Ptr {
		paramsLogger.Panic("Bind: revel/params: non-pointer passed to Bind: " + name)
	}
	value = value.Elem()
	if !value.CanSet() {
		paramsLogger.Panic("Bind: revel/params: non-settable variable passed to Bind: " + name)
	}

	// Remove the json from the Params, this will stop the binder from attempting
	// to use the json data to populate the destination interface. We do not want
	// to do this on a named bind directly against the param, it is ok to happen when
	// the action is invoked.
	jsonData := p.JSON
	p.JSON = nil
	value.Set(Bind(p, name, value.Type()))
	p.JSON = jsonData
}

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


Question:
Get the validated data from the request.

@return array

public function validated(): array
    {
        $rules = $this->container->call([$this, 'rules']);

        return $this->only(collect($rules)->keys()->map(function ($rule) {
            return str_contains($rule, '.') ? explode('.', $rule)[0] : $rule;
        })->unique()->toArray());
    }

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

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

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

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

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

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

        return $info;
    }

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


Question:
Refresh cache

@param string $url
@return void

public static function refresh( $url ) {
		$parser = new Parser( $url );

		$cache = [
			'permalink'   => $parser->get_permalink(),
			'thumbnail'   => $parser->get_thumbnail(),
			'title'       => $parser->get_title(),
			'description' => $parser->get_description(),
			'favicon'     => $parser->get_favicon(),
			'domain'      => $parser->get_domain(),
			'cached_time' => time(),
		];

		$expiration = empty( $cache['title'] ) ? HOUR_IN_SECONDS : YEAR_IN_SECONDS;

		set_transient( static::_get_meta_key( $url ), $cache, $expiration );
	}

public static function resetCache()
    {
        parent::$_aArticleVendors = array();
        parent::$_aArticleManufacturers = array();
        parent::$_aLoadedParents = null;
        parent::$_aSelList = null;
    }

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


Question:
Lists recursively files form a directory

@param dir        the directory to list
@param parentName name of the parent; to be used in construction the relative path of the returned files

@return a list foi files from the dir and any sub-folders

private List<String> listFiles( final File dir, final String parentName )
    {
        final List<String> fileNames = new ArrayList<String>();
        File[] files = null;
        if( dir.canRead() )
        {
            files = dir.listFiles();
        }
        if( files != null )
        {
            for( File file : files )
            {
                if( file.isDirectory() )
                {
                    fileNames.addAll( listFiles( file, parentName + file.getName() + "/" ) );
                }
                else
                {
                    fileNames.add( parentName + file.getName() );
                }
            }
        }
        return fileNames;
    }

func (b *Box) readDirNames(path string) ([]string, error) {

	f, err := b.Open(path)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	stat, err := f.Stat()
	if err != nil {
		return nil, err
	}

	if !stat.IsDir() {
		return nil, nil
	}

	infos, err := f.Readdir(0)
	if err != nil {
		return nil, err
	}

	var names []string

	for _, info := range infos {
		names = append(names, info.Name())
	}

	sort.Strings(names)
	return names, nil

}

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


Question:
删除指定分组

@param int $id 分组ID

@return bool. 注：删除成功时返回的是 '' ,删除失败时返回的是false,(包括分组ID不是数字或分组ID已经不存在)

public function delete($id)
    {
        if (!is_numeric($id)) {
            $this->setError('参数错误,分组ID不是数字');

            return false;
        }

        $queryStr = [
            'group' => ['id' => $id],
        ];

        $res = $this->_post('delete', $queryStr);

        return $res;
    }

func (s *GetDeploymentInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "GetDeploymentInput"}
	if s.DeploymentId == nil {
		invalidParams.Add(request.NewErrParamRequired("DeploymentId"))
	}

	if invalidParams.Len() > 0 {
		return invalidParams
	}
	return nil
}

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


Question:
Get rating

If no "rating" value has been set, this method will
set and return a default "rating" value,
if any such value is available

@see getDefaultRating()

@return string|null rating or null if no rating has been set

public function getRating() : ?string
    {
        if ( ! $this->hasRating()) {
            $this->setRating($this->getDefaultRating());
        }
        return $this->rating;
    }

public Observable<ServiceResponse<Void>> publishVideoReviewWithServiceResponseAsync(String teamName, String reviewId) {
        if (this.client.baseUrl() == null) {
            throw new IllegalArgumentException("Parameter this.client.baseUrl() is required and cannot be null.");
        }
        if (teamName == null) {
            throw new IllegalArgumentException("Parameter teamName is required and cannot be null.");
        }
        if (reviewId == null) {
            throw new IllegalArgumentException("Parameter reviewId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{baseUrl}", this.client.baseUrl());
        return service.publishVideoReview(teamName, reviewId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<Void>>>() {
                @Override
                public Observable<ServiceResponse<Void>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<Void> clientResponse = publishVideoReviewDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question: Adds the given basic block in the function

def add_basic_block(self, basic_block):
        """"""
        assert(isinstance(basic_block, BasicBlock))
        self.basic_block_list.append(basic_block)

func (o *Options) readOpts() *readOptions {
	var mask bool
	var maskVal string

	// Hide input and prompt nothing on screen.
	if o.Hide {
		mask = true
	}

	// Mask input and prompt default maskVal.
	if o.Mask {
		mask = true
		maskVal = defaultMaskVal
	}

	// Mask input and prompt custom maskVal.
	if o.MaskVal != "" {
		maskVal = o.MaskVal
	}

	return &readOptions{
		mask:    mask,
		maskVal: maskVal,
	}
}

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


Question:
Add article to recommendation list

@param string $sOXID Object ID
@param string $sDesc recommended article description

@throws Exception

@return bool

public function addArticle($sOXID, $sDesc)
    {
        $blAdd = false;
        if ($sOXID) {
            // We force reading from master to prevent issues with slow replications or open transactions (see ESDEV-3804 and ESDEV-3822).
            $database = \OxidEsales\Eshop\Core\DatabaseProvider::getMaster(\OxidEsales\Eshop\Core\DatabaseProvider::FETCH_MODE_ASSOC);

            if (!$database->getOne("select oxid from oxobject2list where oxobjectid=" . $database->quote($sOXID) . " and oxlistid=" . $database->quote($this->getId()))) {
                $sUid = \OxidEsales\Eshop\Core\Registry::getUtilsObject()->generateUID();
                $sQ = "insert into oxobject2list ( oxid, oxobjectid, oxlistid, oxdesc ) values ( '$sUid', " . $database->quote($sOXID) . ", " . $database->quote($this->getId()) . ", " . $database->quote($sDesc) . " )";
                $blAdd = $database->execute($sQ);
            }
        }

        return $blAdd;
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
%This function returns an envelope for network of size N; The envelope can
    %either be suppressive (periodic = 0) or flat and equal to one (periodic = 1)

def create_envelope(periodic,N):
  '''

  '''
  kappa = 0.3; # controls width of main body of envelope
  a0 = 30;    # contrls steepness of envelope

  if periodic==0:
      A = np.zeros(N)
      for m in range(N):
          r = np.abs(m-N/2);
          if r<kappa*N:
              A[m] = 1
          else:
              A[m] = np.exp(-a0*((r-kappa*N)/((1-kappa)*N))**2)
  else:
      A = np.ones((1,N));

  return A

def set_sampled_topics(self, sampled_topics):

        assert sampled_topics.dtype == np.int and \
            len(sampled_topics.shape) <= 2

        if len(sampled_topics.shape) == 1:
            self.sampled_topics = \
                sampled_topics.reshape(1, sampled_topics.shape[0])
        else:
            self.sampled_topics = sampled_topics

        self.samples = self.sampled_topics.shape[0]

        self.tt = self.tt_comp(self.sampled_topics)
        self.dt = self.dt_comp(self.sampled_topics)

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


Question:
Similar to notebook_jobs,
        but uses the default manager to return archived experiments as well.

def all_notebook_jobs(self):

        from db.models.notebooks import NotebookJob

        return NotebookJob.all.filter(project=self)

def implode(self, env):

        juicer.utils.Log.log_debug("imploding %s" % self.cart_name)

        # rm -r self.remotes_storage()
        if os.path.exists(self.remotes_storage):
            for item in os.listdir(self.remotes_storage):
                ipath = os.path.expanduser(self.remotes_storage + '/' + item)
                if os.path.exists(ipath):
                    juicer.utils.Log.log_debug("removing %s" % ipath)
                    os.remove(ipath)
                juicer.utils.Log.log_debug("removing %s's remote item storage dir" % self.cart_name)
                os.rmdir(self.remotes_storage)

        # rm cart_file()
        if os.path.exists(self.cart_file()):
            juicer.utils.Log.log_debug("removing %s's cart file" % self.cart_name)
            os.remove(self.cart_file())

        # db.carts.delete(self.name)
        juicer.utils.Log.log_debug("removing %s from the database" % self.cart_name)
        juicer.utils.cart_db()[env].remove({'_id': self.cart_name})

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


Question:
Checks entity

@param $object
@return bool
@throws InvalidArgumentException

private function isExpectedObject($object)
    {
        $className = $this->getClass();
        if (!is_object($object) || !$object instanceof $className) {
            throw new InvalidArgumentException();
        }

        return true;
    }

public function equalTo($expected): Expect {
            $this->testsTheEqualityAgainstAValue = true;
            $this->expected = $expected;

            return $this;
        }

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


Question:
Returns all installed modules.

The installed modules are all modules that are not the root module.

@return Module[] The installed modules indexed by their names.

public function getInstalledModules()
    {
        $modules = $this->modules;

        if ($this->rootModule) {
            unset($modules[$this->rootModule->getName()]);
        }

        return $modules;
    }

private function getPackage($path)
    {
        $path = realpath($path) ?: $path;
        foreach (self::getVendors() as $vendorRoot) {
            if (0 === strpos($path, $vendorRoot)) {
                $relativePath = substr($path, \strlen($vendorRoot) + 1);
                $vendor = strstr($relativePath, \DIRECTORY_SEPARATOR, true);
                if (false === $vendor) {
                    throw new \RuntimeException(sprintf('Could not find directory separator "%s" in path "%s"', \DIRECTORY_SEPARATOR, $relativePath));
                }

                return rtrim($vendor.'/'.strstr(substr(
                    $relativePath,
                    \strlen($vendor) + 1
                ), \DIRECTORY_SEPARATOR, true), '/');
            }
        }

        throw new \RuntimeException(sprintf('No vendors found for path "%s"', $path));
    }

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


Question:
Checks if a record is owned by an user.

Example:
<code>
$posts->isOwnedBy(2, 4);
</code>
it checks if the posts with ID 2 belongs to the user with ID 4.
@param int $recordId Record ID
@param int $userId User ID
@return bool

public function isOwnedBy($recordId, $userId = null)
    {
        return (bool)$this->find()
            ->where(['id' => $recordId, 'user_id' => $userId])
            ->first();
    }

public function store(Request $request)
    {
        $this->validate($request, [
            'ticket_id'   => 'required|exists:ticketit,id',
            'content'     => 'required|min:6',
        ]);

        $comment = new Models\Comment();

        $comment->setPurifiedContent($request->get('content'));

        $comment->ticket_id = $request->get('ticket_id');
        $comment->user_id = \Auth::user()->id;
        $comment->save();

        $ticket = Models\Ticket::find($comment->ticket_id);
        $ticket->updated_at = $comment->created_at;
        $ticket->save();

        return back()->with('status', trans('ticketit::lang.comment-has-been-added-ok'));
    }

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


Question: Update the domain for a particular service and version.

def update_domain(self, service_id, version_number, name_key, **kwargs):
		""""""
		body = self._formdata(kwargs, FastlyDomain.FIELDS)
		content = self._fetch("/service/%s/version/%d/domain/%s" % (service_id, version_number, name_key), method="PUT", body=body)
		return FastlyDomain(self, content)

func NewTLSClient(endpoint string, cert, key, ca string) (*Client, error) {
	client, err := NewVersionedTLSClient(endpoint, cert, key, ca, "")
	if err != nil {
		return nil, err
	}
	client.SkipServerVersionCheck = true
	return client, nil
}

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


Question:
Returns a string that can be used as inline cell styling (e.g. `<td style="<%=cell.format.to_css%>"><%=cell%></td>`)
 @return String very basic CSS styling string

def to_css
      css_parts = []
      background = [flattened[:background_color].to_s,flattened[:background].to_s].join(" ").strip
      css_parts.push("background: #{background}") if background and background != ""
      css_parts.push("color: #{flattened[:color].to_s}") if flattened[:color]
      css_parts.join("; ")
    end

def compiled_columns(self):
        """"""

        def get_column_args(column):
            tmp = []
            for arg_name, arg_val in column.items():
                if arg_name not in ('name', 'type'):
                    if arg_name in ('server_default', 'server_onupdate'):
                        arg_val = '"{}"'.format(arg_val)
                    tmp.append(ALCHEMY_TEMPLATES.column_arg.safe_substitute(arg_name=arg_name,
                                                                            arg_val=arg_val))
            return ", ".join(tmp)

        res = []
        for column in self.column_definitions:
            column_args = get_column_args(column)
            column_type, type_params = ModelCompiler.get_col_type_info(column.get('type'))
            column_name = column.get('name')
            if column_type in MUTABLE_DICT_TYPES:
                column_type = ALCHEMY_TEMPLATES.mutable_dict_type.safe_substitute(type=column_type,
                                                                                type_params=type_params)
                type_params = ''
            res.append(
                ALCHEMY_TEMPLATES.column_definition.safe_substitute(column_name=column_name,
                                                                    column_type=column_type,
                                                                    column_args=column_args,
                                                                    type_params=type_params))
        join_string = "\n" + self.tab
        return join_string.join(res)

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


Question:
Returns proper description for thread.
@return string

public function getDescription()
    {
        $description = Yii::t('podium/view', 'No New Posts');
        $append = false;

        if ($this->locked) {
            $description = Yii::t('podium/view', 'Locked Thread');
            $append = true;
        } elseif ($this->pinned) {
            $description = Yii::t('podium/view', 'Pinned Thread');
            $append = true;
        } elseif ($this->posts >= Podium::getInstance()->podiumConfig->get('hot_minimum')) {
            $description = Yii::t('podium/view', 'Hot Thread');
            $append = true;
        }
        if ($this->userView) {
            if ($this->new_post_at > $this->userView->new_last_seen) {
                if (!$append) {
                    $description = Yii::t('podium/view', 'New Posts');
                } else {
                    $description .= ' (' . Yii::t('podium/view', 'New Posts') . ')';
                }
            } elseif ($this->edited_post_at > $this->userView->edited_last_seen) {
                if (!$append) {
                    $description = Yii::t('podium/view', 'Edited Posts');
                } else {
                    $description = ' (' . Yii::t('podium/view', 'Edited Posts') . ')';
                }
            }
        } else {
            if (!$append) {
                $description = Yii::t('podium/view', 'New Posts');
            } else {
                $description .= ' (' . Yii::t('podium/view', 'New Posts') . ')';
            }
        }
        return $description;
    }

def expect_comment_end(self):

        match = self._expect_match('#}', COMMENT_END_PATTERN)
        self.advance(match.end())

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


Question: // UdpTransport implementation of SendMaybeRecv, queues a request to send a message to the server

func (t *UdpTransport) SendMaybeRecv(message *proto.Msg) (*proto.Msg, error) {
	response_ch := make(chan response)
	t.requestQueue <- request{message, response_ch}
	r := <-response_ch
	return r.message, r.err
}

def drain_events(self, timeout=None):
        """"""
        chanmap = self.channels
        chanid, method_sig, args, content = self._wait_multiple(
            chanmap, None, timeout=timeout,
        )

        channel = chanmap[chanid]

        if (content and
                channel.auto_encode_decode and
                hasattr(content, 'content_encoding')):
            try:
                content.body = content.body.decode(content.content_encoding)
            except Exception:
                pass

        amqp_method = (self._method_override.get(method_sig) or
                       channel._METHOD_MAP.get(method_sig, None))

        if amqp_method is None:
            raise AMQPNotImplementedError(
                'Unknown AMQP method {0!r}'.format(method_sig))

        if content is None:
            return amqp_method(channel, args)
        else:
            return amqp_method(channel, args, content)

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


Question:
Returns the input delta but only if it will not result in exceeding the
limit of the maximum number of bytes that can be processed by AES/GCM.

@throws SecurityException
if the number of bytes processed has exceeded the maximum
allowed by AES/GCM.

private int checkMax(int delta) {
        if (outputByteCount + delta > ContentCryptoScheme.MAX_GCM_BYTES) {
            securityViolated = true;
            throw new SecurityException(
                    "Number of bytes processed has exceeded the maximum allowed by AES/GCM; [outputByteCount="
                            + outputByteCount + ", delta=" + delta + "]");
        }
        return delta;
    }

def Deserialize(self, reader):

        super(AssetState, self).Deserialize(reader)
        self.AssetId = reader.ReadUInt256()
        self.AssetType = reader.ReadByte()
        self.Name = reader.ReadVarString()

        position = reader.stream.tell()

        try:
            self.Amount = reader.ReadFixed8()
        except Exception as e:
            reader.stream.seek(position)
            self.Amount = reader.ReadFixed8()

        self.Available = reader.ReadFixed8()
        self.Precision = reader.ReadByte()

        # fee mode
        reader.ReadByte()

        self.Fee = reader.ReadFixed8()
        self.FeeAddress = reader.ReadUInt160()
        self.Owner = ECDSA.Deserialize_Secp256r1(reader)
        self.Admin = reader.ReadUInt160()
        self.Issuer = reader.ReadUInt160()
        self.Expiration = reader.ReadUInt32()
        self.IsFrozen = reader.ReadBool()

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


Question:
Draws a report (multiple tables).
@param {Array} results Report results for every file.
@returns {string} A column of text tables.

function drawReport(results) {
    let files;

    files = results.map(result => {
        if (!result.messages.length) {
            return "";
        }

        return `\n${result.filePath}\n\n${drawTable(result.messages)}`;
    });

    files = files.filter(content => content.trim());

    return files.join("");
}

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

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

            $loopResult->addRow($loopResultRow);
        }

        return $loopResult;
    }

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


Question:
Finds the hotspot based on the inputed name.

        :param      name | <str>

        :return     <XNodeHotspot> || None

def findHotspot( self, name ):

        for hotspot in self._hotspots:
            if ( hotspot.name() == name ):
                return hotspot
        return None

def get_nodes_by_tag(self, graph, tag_name):

        for node, real_node in self.parsed_nodes(graph):
            if tag_name in real_node.tags:
                yield node

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


Question: From comment on http://php.net/manual/en/ref.bc.php

static function bcconv($fNumber)
    {
        $sAppend = '';
        $iDecimals = ini_get('precision') - floor(log10(abs($fNumber)));
        if (0 > $iDecimals) {
            $fNumber *= pow(10, $iDecimals);
            $sAppend = str_repeat('0', -$iDecimals);
            $iDecimals = 0;
        }

        return number_format($fNumber, $iDecimals, '.', '').$sAppend;
    }

protected function getFlyConsole()
	{
		if ( ! is_null($this->flyconsole)) return $this->flyconsole;

		$this->app->loadDeferredProviders();

		$this->flyconsole = ConsoleApplication::make($this->app);

		return $this->flyconsole->boot();
	}

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


Question:
Check that a given string is a well-formed email address.

@param value
Value to check.

@return Returns true if it's a valid email address else false is returned.

public static boolean isValid(final String value) {
        if (value == null) {
            return true;
        }
        if (value.length() == 0) {
            return false;
        }
        try {
            InternetAddress.parse(value, false);
            return true;
        } catch (final AddressException ex) {
            return false;
        }
    }

def match(self, message: Message) -> bool:

        if self.template:
            return self.template.match(message)
        return True

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


Question:
Generate a free postage object we can use in our code.

@todo This is a little hacky, ideally we need to find a cleaner
way of dealing with postage options that doesn't involve unsaved
database objects.

@return PostageArea

public static function CreateFreePostageObject()
    {
        $postage = new PostageArea();
        $postage->ID = -1;
        $postage->Title = _t("Checkout.FreeShipping", "Free Shipping");
        $postage->Country = "*";
        $postage->ZipCode = "*";

        return $postage;
    }

def _serialized(self):
        """"""
        return {'title': self.title,
                'summary': self.summary,
                'areadesc': self.areadesc,
                'event': self.event,
                'samecodes': self.samecodes,
                'zonecodes': self.zonecodes,
                'expiration': self.expiration,
                'updated': self.updated,
                'effective': self.effective,
                'published': self.published,
                'severity': self.severity,
                'category': self.category,
                'urgency': self.urgency,
                'msgtype': self.msgtype,
                'link': self.link,
                }

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


Question:
// GetTemplateRecord fetches a template record.
//
// See https://developer.dnsimple.com/v2/templates/records/#get

func (s *TemplatesService) GetTemplateRecord(accountID string, templateIdentifier string, templateRecordID int64) (*templateRecordResponse, error) {
	path := versioned(templateRecordPath(accountID, templateIdentifier, templateRecordID))
	templateRecordResponse := &templateRecordResponse{}

	resp, err := s.client.get(path, templateRecordResponse)
	if err != nil {
		return nil, err
	}

	templateRecordResponse.HttpResponse = resp
	return templateRecordResponse, nil
}

func (client *Client) TargetCF(settings TargetSettings) (Warnings, error) {
	client.cloudControllerURL = settings.URL

	client.connection = cloudcontroller.NewConnection(cloudcontroller.Config{
		DialTimeout:       settings.DialTimeout,
		SkipSSLValidation: settings.SkipSSLValidation,
	})

	for _, wrapper := range client.wrappers {
		client.connection = wrapper.Wrap(client.connection)
	}

	apiInfo, resourceLinks, warnings, err := client.GetInfo()
	if err != nil {
		return warnings, err
	}

	client.Info = apiInfo

	resources := map[string]string{}
	for resource, link := range resourceLinks {
		resources[resource] = link.HREF
	}
	client.router = internal.NewRouter(internal.APIRoutes, resources)

	return warnings, nil
}

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


Question:
Helper function which ensures that {@link NullSafetySentinel} instances don't escape from this
visitor.

@param node The node to evaluate.
@return The result of evaluating the node.

private SoyValue visitNullSafeNode(ExprNode node) {
    SoyValue value = visitNullSafeNodeRecurse(node);
    // Transform null sentinel into a normal null value.
    if (value == NullSafetySentinel.INSTANCE) {
      return NullData.INSTANCE;
    }
    return value;
  }

def parse(node)
      node.xpath('*').each do |node_child|
        case node_child.name
        when 'solidFill'
          @type = :solid
          @color = Color.new(parent: self).parse_color_model(node_child)
        when 'gradFill'
          @type = :gradient
          @color = GradientColor.new(parent: self).parse(node_child)
        when 'noFill'
          @color = :none
          @type = :none
        when 'srgbClr'
          @color = Color.new(parent: self).parse_hex_string(node_child.attribute('val').value)
        when 'schemeClr'
          @color = Color.new(parent: self).parse_scheme_color(node_child)
        end
      end
      self
    end

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


Question:
Normalize the response value into a 3-tuple (rv, status, headers)
        :type rv: tuple|*
        :returns: tuple(rv, status, headers)
        :rtype: tuple(Response|JsonResponse|*, int|None, dict|None)

def normalize_response_value(rv):

    status = headers = None
    if isinstance(rv, tuple):
        rv, status, headers = rv + (None,) * (3 - len(rv))
    return rv, status, headers

def create_from_json(cls, json_data):

        zipcode = ZipCode()
        zipcode.zipcode = json_data["zipcode_info"]["zipcode"]
        zipcode.meta = json_data["meta"] if "meta" in json_data else None

        zipcode.component_results = _create_component_results(json_data, "zipcode_info")

        return zipcode

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


Question:
Update hover style for the speficied styleId.

@param styleId {string} - a unique id that exists as class attribute in the DOM
@param properties {object} - the components properties optionally containing hoverStyle

function updatePseudoClassStyle(styleId, properties) {
  const hoverStyle = {
    ...style.hoverStyle,
    ...properties.hoverStyle,
  };
  const disabledHoverStyle = {
    ...style.disabledHoverStyle,
    ...properties.disabledHoverStyle,
  };

  const styles = [
    {
      id: styleId,
      style: hoverStyle,
      pseudoClass: 'hover',
    },
    {
      id: styleId,
      style: disabledHoverStyle,
      pseudoClass: 'hover',
      disabled: true,
    },
  ];
  injectStyles(styles);
}

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Should only be done once at the very beginning

@return \Cake\Http\Response|null

public function importFromCore() {
		if (!empty($this->request->query['reset'])) {
			$this->Languages->truncate();
		}
		//$languages = $this->Languages->iso3ToIso2();
		$languages = $this->Languages->catalog();
		$count = 0;
		$errors = [];
		foreach ($languages as $language) {
			if (!($code = $this->Languages->iso3ToIso2($language['localeFallback']))) {
				$code = '';
			}
			$data = [
				'name' => $language,
				'ori_name' => $language,
				'code' => $code,
				'locale' => $language['locale'],
				'locale_fallback' => $language['localeFallback'],
				'direction' => $language['direction']
			];
			$language = $this->Languages->newEntity($data);
			if ($this->Languages->save($language)) {
				$count++;
			} else {
				$errors[] = ['data' => $language, 'errors' => $this->Languages->validationErrors];
			}
		}

		$this->Flash->success($count . ' of ' . count($languages) . ' ' . __('languages added'));

		$errorMessage = [];
		foreach ($errors as $error) {
			$errorMessage[] = $error['data'] . ' (' . returns($error['errors']) . ')';
		}
		$this->Flash->warning(__('not added') . ' ' . implode(', ', $errorMessage));
		return $this->redirect(['action' => 'index']);
	}

func (c *Client) Status(patterns []string) (*params.FullStatus, error) {
	var result params.FullStatus
	p := params.StatusParams{Patterns: patterns}
	if err := c.facade.FacadeCall("FullStatus", p, &result); err != nil {
		return nil, err
	}
	// Older servers don't fill out model type, but
	// we know a missing type is an "iaas" model.
	if result.Model.Type == "" {
		result.Model.Type = model.IAAS.String()
	}
	return &result, nil
}

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


Question:
Return all unoccupied Ports referenced by this Compound.

        Returns
        -------
        list of mb.Compound
            A list of all unoccupied ports referenced by the Compound

def available_ports(self):

        from mbuild.port import Port
        return [port for port in self.labels.values()
                if isinstance(port, Port) and not port.used]

def emit_code_from_ir(compound_match_query, compiler_metadata):
    """"""
    # If the compound match query contains only one match query,
    # just call `emit_code_from_single_match_query`
    # If there are multiple match queries, construct the query string for each
    # individual query and combine them as follows.
    #
    # SELECT EXPAND($result)
    # LET
    #    $optional__0 = (
    #        <query_string_0>
    #    ),
    #    $optional__1 = (
    #        <query_string_1>
    #    ),
    #    $optional__2 = (
    #        <query_string_2>
    #    ),
    #
    #    . . .
    #
    #    $result = UNIONALL($optional__0, $optional__1, . . . )

    match_queries = compound_match_query.match_queries
    if len(match_queries) == 1:
        query_string = emit_code_from_single_match_query(match_queries[0])
    elif len(match_queries) > 1:
        query_string = emit_code_from_multiple_match_queries(match_queries)
    else:
        raise AssertionError(u'Received CompoundMatchQuery with an empty list of MatchQueries: '
                             u'{}'.format(match_queries))

    return query_string

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


Question:
Create php classes using raw element data; called recursively

@param array $element
@param null|BaseElement $parent

private function process(array $element, $parent = null)
    {
        $apiElement = $element['element'];

        if (isset($this->elementMap[$apiElement])) {
            $this->processElement(
                $element,
                $this->elementMap[$apiElement],
                $parent
            );
        }

        if ($element['element'] === 'category') {
            // todo extend the element map to check for classes, then merge processCategory into processElement
            $this->processCategory($element, $parent);
        }
    }

public function addChild(Step $step)
    {
        if (!$this->children->contains($step)) {
            $this->children->add($step);
            $step->setParent($this);
        }

        return $this;
    }

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


Question:
Returns a dict to communicate with the server

        :param restrict_keys: a set of keys to restrict the returned data to
        :rtype: dict

def to_api_data(self, restrict_keys=None):

        cc = self._cc  # alias
        data = {
            cc('subject'): self.__subject,
            cc('body'): {
                cc('contentType'): self.body_type,
                cc('content'): self.__body},
            cc('start'): self._build_date_time_time_zone(self.__start),
            cc('end'): self._build_date_time_time_zone(self.__end),
            cc('attendees'): self.__attendees.to_api_data(),
            cc('location'): {cc('displayName'): self.__location},
            cc('categories'): self.__categories,
            cc('isAllDay'): self.__is_all_day,
            cc('importance'): cc(self.__importance.value),
            cc('isReminderOn'): self.__is_reminder_on,
            cc('reminderMinutesBeforeStart'): self.__remind_before_minutes,
            cc('responseRequested'): self.__response_requested,
            cc('sensitivity'): cc(self.__sensitivity.value),
            cc('showAs'): cc(self.__show_as.value),
        }

        if self.__recurrence:
            data[cc('recurrence')] = self.__recurrence.to_api_data()

        if self.has_attachments:
            data[cc('attachments')] = self.__attachments.to_api_data()

        if restrict_keys:
            for key in list(data.keys()):
                if key not in restrict_keys:
                    del data[key]
        return data

def get_component_types(topic_id, remoteci_id, db_conn=None):
    """"""

    db_conn = db_conn or flask.g.db_conn
    rconfiguration = remotecis.get_remoteci_configuration(topic_id,
                                                          remoteci_id,
                                                          db_conn=db_conn)

    # if there is no rconfiguration associated to the remoteci or no
    # component types then use the topic's one.
    if (rconfiguration is not None and
            rconfiguration['component_types'] is not None):
        component_types = rconfiguration['component_types']
    else:
        component_types = get_component_types_from_topic(topic_id,
                                                         db_conn=db_conn)

    return component_types, rconfiguration

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


Question:
Loads the given key, or - with isFile set true - the key from the keyfile.

@param string $key
@param bool $isFile
@param bool $isCert
@throws Exception

public function loadKey($key, $isCert = false)
    {
        if (is_file($key)) {
            $this->key = file_get_contents($key);
        } else {
            $this->key = $key;
        }
        if ($isCert) {
            $this->key = openssl_x509_read($this->key);
            openssl_x509_export($this->key, $str_cert);
            $this->x509Certificate = $str_cert;
            $this->key = $str_cert;
        } else {
            $this->x509Certificate = null;
        }
        if ($this->cryptParams['library'] == 'openssl') {
            switch ($this->cryptParams['type']) {
                case 'public':
                    if ($isCert) {
                        /* Load the thumbprint if this is an X509 certificate. */
                        $this->X509Thumbprint = self::getRawThumbprint($this->key);
                    }
                    $this->key = openssl_get_publickey($this->key);
                    if (!$this->key) {
                        throw new Exception('Unable to extract public key');
                    }
                    break;

                case 'private':
                    $this->key = openssl_get_privatekey($this->key, $this->passphrase);
                    break;

                case'symmetric':
                    if (strlen($this->key) < $this->cryptParams['keysize']) {
                        throw new Exception('Key must contain at least 25 characters for this cipher');
                    }
                    break;

                default:
                    throw new Exception('Unknown type');
            }
        }
    }

public function process(ContainerBuilder $container)
    {
        $bundles         = $container->getParameter('kernel.bundles');
        $bundleContainer = $container->getDefinition('atoum.configuration.bundle.container');
        $configuration   = $container->getParameterBag()->resolveValue($container->getParameter('atoum.bundles'));

        foreach ($configuration as $bundleName => $data) {
            if (!isset($bundles[$bundleName])) {
                throw new \LogicException(sprintf('Bundle "%s" does not exists.', $bundleName));
            }

            $rc        = new \ReflectionClass($bundles[$bundleName]);
            $directory = dirname($rc->getFileName());

            $directories = array_map(
                function ($v) use ($directory) {
                    return $directory.'/'.$v;
                },
                $data['directories']
            );

            $definition = new Definition(
                $container->getParameter('atoum.configuration.bundle.class'),
                array($bundleName, $directories)
            );

            $bundleContainer->addMethodCall('add', array($definition));
        }
    }

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


Question:
Peek status queue
        :param int n: number of messages to return as part of peek.
        :param bool raw: should message content be returned as is (no parsing).

def peek(self, n=1, raw=False):

        def _peek_specific_q(_q, _n):
            has_messages = False
            for m in _q.service.peek_messages(_q.name, num_messages=_n):
                if m is not None:
                    has_messages = True
                    result.append(m if raw else self._deserialize_message(m))

                    # short circut to prevent unneeded work
                    if len(result) == n:
                        return True
            return has_messages

        q_services = self._get_q_services()
        random.shuffle(q_services)

        per_q = int(n / len(q_services)) + 1

        result = []

        non_empty_qs = []

        for q in q_services:
            if _peek_specific_q(q, per_q):
                non_empty_qs.append(q)

            if len(result) == n:
                return result

        # in-case queues aren't balanced, and we didn't get enough messages, iterate again and this time get all that we can
        for q in non_empty_qs:
            _peek_specific_q(q, n)
            if len(result) == n:
                return result

        # because we ask for n / len(qs) + 1, we might get more message then requests
        return result

function subscribeRaw(peripheralId, serviceUuid, uuid, state, callback) {

  //todo catch exceptions
  var peripheral = peripherals[peripheralId];
  var characteristic = servicesCache[peripheralId].services[serviceUuid].characteristics[uuid];
  var handle = characteristic.descriptors['2902'];

  if (state == false) {
    value = '0000';
  } else {
    if (characteristic.properties == 'indicate'){
      value = '0200';
    } else  {// notify
      value = '0100';
    }
  }

  //if not connected, connect
  checkConnected(peripheral, function(){
    peripheral.writeHandle(handle, new Buffer(value, 'hex'), false, function(error){
      if (error){
        debug('Subscribe error '.red + peripheralId + ' : ' + serviceUuid + ' : ' + uuid )
      }
      sendEvent({
        type: 'notify',
        peripheralId: peripheralId,
        serviceUuid: serviceUuid,
        characteristicUuid: uuid,
        state: state
      });
    });
  })

  checkRawNotificationListeners();
}

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


Question: restore the auto increment value for the table to what it was previously

def _restore_auto_increment(self, table):
        """"""
        query, seq_table, seq_column, seq_name = self._get_auto_increment_info(table)
        if query:
            queries = [query, "select nextval('{}')".format(seq_name)]
            return self._run_queries(queries)

final public function getWriteMode()
    {
        switch ($this->getDataMode()) {
            case Configuration::DATA_MODE_WIPE:
            case Configuration::DATA_MODE_PROGRESSIVE:
                $this->setWriteMode(static::WRITE_MODE_INSERT);
                break;
            default:
                $this->setWriteMode(static::WRITE_MODE_UPSERT);
        }
        return $this->writeMode;
    }

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


Question: Use this operation to get disk adapters.

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

public static String resolveDataSourceTypeFromDialect(String dialect)
    {
        if (StringUtils.contains(dialect, "Oracle"))
        {
            return "Oracle";
        }
        else if (StringUtils.contains(dialect, "MySQL"))
        {
            return "MySQL";
        }
        else if (StringUtils.contains(dialect, "DB2390Dialect"))
        {
            return "DB2/390";
        }
        else if (StringUtils.contains(dialect, "DB2400Dialect"))
        {
            return "DB2/400";
        }
        else if (StringUtils.contains(dialect, "DB2"))
        {
            return "DB2";
        }
        else if (StringUtils.contains(dialect, "Ingres"))
        {
            return "Ingres";
        }
        else if (StringUtils.contains(dialect, "Derby"))
        {
            return "Derby";
        }
        else if (StringUtils.contains(dialect, "Pointbase"))
        {
            return "Pointbase";
        }
        else if (StringUtils.contains(dialect, "Postgres"))
        {
            return "Postgres";
        }
        else if (StringUtils.contains(dialect, "SQLServer"))
        {
            return "SQLServer";
        }
        else if (StringUtils.contains(dialect, "Sybase"))
        {
            return "Sybase";
        }
        else if (StringUtils.contains(dialect, "HSQLDialect"))
        {
            return "HyperSQL";
        }
        else if (StringUtils.contains(dialect, "H2Dialect"))
        {
            return "H2";
        }

        return dialect;

    }

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


Question: Outputs *k* draws from the multinomial distribution.

def dequeue(self, k):
        """"""
        if self.j + k <= self.M:
            out = self.A[self.j:(self.j + k)]
            self.j += k
        elif k <= self.M:
            out = np.empty(k, 'int')
            nextra = self.j + k - self.M
            out[:(k - nextra)] = self.A[self.j:]
            self.enqueue()
            out[(k - nextra):] = self.A[:nextra]
            self.j = nextra
        else:
            raise ValueError('MultinomialQueue: k must be <= M (the max \
                             capacity of the queue)')
        return out

@Override
  public void doMultimediaAuthAnswer(ClientCxDxSession appSession, JMultimediaAuthRequest request, JMultimediaAuthAnswer answer)
      throws InternalException, IllegalDiameterStateException, RouteException, OverloadException {
    logger.info("Diameter Cx/Dx Session Factory :: doMultimediaAuthAnswer :: appSession[{}], Request[{}], Answer[{}]",
        new Object[]{appSession, request, answer});
  }

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


Question:
@param ServerDoc $doc

@return array

@throws \ReflectionException

protected function getMethodErrorsExternalSchemaList(ServerDoc $doc) : array
    {
        $list = [];
        foreach ($doc->getMethodList() as $method) {
            $list = array_merge(
                $list,
                $this->normalizeErrorList(
                    $method->getCustomErrorList(),
                    DefinitionRefResolver::CUSTOM_ERROR_DEFINITION_TYPE
                )
            );
        }

        return $list;
    }

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

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

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

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

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

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

        return $info;
    }

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


Question:
/* Volume Indicators */
// Ad - Chaikin A/D Line

func Ad(inHigh []float64, inLow []float64, inClose []float64, inVolume []float64) []float64 {

	outReal := make([]float64, len(inClose))

	startIdx := 0
	nbBar := len(inClose) - startIdx
	currentBar := startIdx
	outIdx := 0
	ad := 0.0
	for nbBar != 0 {
		high := inHigh[currentBar]
		low := inLow[currentBar]
		tmp := high - low
		close := inClose[currentBar]
		if tmp > 0.0 {
			ad += (((close - low) - (high - close)) / tmp) * (inVolume[currentBar])
		}
		outReal[outIdx] = ad
		outIdx++
		currentBar++
		nbBar--
	}
	return outReal
}

function(module) {
		if (gui.Type.isObject(module.mixin)) {
			gui.Spirit.mixin(module.mixin);
		}
		if (gui.Type.isArray(module.channel)) {
			gui.channel(module.channel);
		}
		if (gui.Type.isObject(module.plugin)) {
			gui.Object.each(module.plugin, function(prefix, Plugin) {
				if (gui.Type.isDefined(Plugin)) {
					gui.Spirit.plugin(prefix, Plugin);
				} else { // TODO: move check into gui.Spirit.plugin
					console.error("Undefined plugin for prefix: " + prefix);
				}
			});
		}
	}

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


Question:
Adds an entry for a configuration setting.

    Args:
      key: The name of the setting.
      val: The value of the setting.

def _ParseEntry(self, key, val):

    if key in self._repeated:
      setting = self.section.setdefault(key, [])
      setting.extend(val)
    else:
      self.section.setdefault(key, val)

public function initializeArguments()
    {
        parent::initializeArguments();
        $this->registerArgument('results', '\Solarium\QueryType\Select\Result\Result', 'Query results', true);
        $this->registerArgument('document', '\Solarium\QueryType\Select\Result\Document', 'Result document to work on',
            true);
        $this->registerArgument('field', 'string', 'name of field in document to highlight', true);
        $this->registerArgument('alternateField', 'string',
            'name of alternate field in document to use for highlighting', false, null);
        $this->registerArgument('index', 'int', 'if the field is an array: index of the single element to highlight',
            false);
        $this->registerArgument('idKey', 'string', 'name of the field in document that is its ID', false, 'id');
        $this->registerArgument('highlightTagOpen', 'string', 'opening tag to insert to begin highlighting', false,
            '');
        $this->registerArgument('highlightTagClose', 'string', 'closing tag to insert to end highlighting', false,
            '');
        $this->registerArgument('raw', 'boolean', 'whether to not HTML escape the output', false, false);
    }

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


Question:
Remove unique identities or identities from the registry.

        By default, it removes the unique identity identified by <identifier>.
        To remove an identity, set <identity> parameter.

def run(self, *args):

        params = self.parser.parse_args(args)

        identifier = params.identifier
        identity = params.identity

        code = self.remove(identifier, identity)

        return code

public function escapeIdentifier($input, bool $join = true)
    {
        if (is_array($input)) {
            $input = array_map([$this, 'escapeIdentifier'], array_filter($input));
            return $join ? join(', ', $input) : $input;
        } elseif ($input instanceof Sql) {
            return $input->toString();
        } elseif ($input instanceof Identifier) {
            $input = $input->toString();
        }

        if (!is_string($input)) {
            throw new AgentException(sprintf('String, array and Query\Sql,Identifier type identifiers'.
                ' accepted only, %s given!', gettype($input)));
        }

        $input = trim($input);
        if ($input == '' || $input == '*') {
            return $input;
        }

        // functions, parentheses etc are not allowed
        if (strpos($input, '(') !== false) {
            throw new AgentException('Found parentheses in input, complex identifiers not allowed!');
        }

        // trim all non-word characters
        $input = preg_replace('~^[^\w]|[^\w]$~', '', $input);
        if ($input == '') {
            return $input;
        }

        // multiple fields
        if (strpos($input, ',')) {
            return $this->escapeIdentifier(Util::split(',', $input), $join);
        }

        // aliases
        if (strpos($input, ' ')) {
            return preg_replace_callback('~([^\s]+)\s+(AS\s+)?(\w+)~i', function ($match) {
                return $this->escapeIdentifier($match[1]) . (
                    ($as = trim($match[2])) ? ' '. strtoupper($as) .' ' : ' '
                ) . $this->escapeIdentifier($match[3]);
            }, $input);
        }

        // dots
        if (strpos($input, '.')) {
            return implode('.', array_map([$this, 'escapeIdentifier'], explode('.', $input)));
        }

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

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


Question:
Returns this applications' context path.
@return context path.

protected String getContextPath(){

        if(context != null) return context;

        if(get("context_path") == null){
            throw new ViewException("context_path missing - red alarm!");
        }
        return  get("context_path").toString();
    }

protected function defaultReturnUrl()
    {
        $params = Yii::$app->getRequest()->get();
        foreach ($params as $name => $value) {
            if (strncmp('openid', $name, 6) === 0) {
                unset($params[$name]);
            }
        }
        $params[0] = Yii::$app->requestedRoute;
        $url = Yii::$app->getUrlManager()->createUrl($params);

        return $this->getTrustRoot() . $url;
    }

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


Question: Checks if a list representing the state of the variables is valid.

def _check_state(self, state):

        if not hasattr(state, '__iter__') or isinstance(state, six.string_types):
            raise ValueError('Start state must be a non-string iterable object.')
        state_vars = {s.var for s in state}
        if not state_vars == set(self.variables):
            raise ValueError('Start state must represent a complete assignment to all variables.'
                             'Expected variables in state: {svar}, Got: {mvar}.'.format(svar=state_vars,
                                                                                mvar=set(self.variables)))
        for var, val in state:
            if val >= self.cardinalities[var]:
                raise ValueError('Assignment {val} to {var} invalid.'.format(val=val, var=var))
        return True

public function set($name, array $data = [])
    {
        $this->setName($name);
        $this->setData($data);

        return $this->isValid();
    }

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


Question: channel: 1=OP1, 2=OP2, AUX is not supported

def get_set_voltage(self, channel):

        ret = self.ask("V%d?" % channel)
        if ret[:3] != "V%d " % channel:
            print("ttiQl355tp.get_voltage() format error", ret)
            return None
        return float(ret[3:])

func (n *NetworkServerAPI) GetVersion(ctx context.Context, req *empty.Empty) (*ns.GetVersionResponse, error) {
	region, ok := map[string]common.Region{
		common.Region_AS923.String(): common.Region_AS923,
		common.Region_AU915.String(): common.Region_AU915,
		common.Region_CN470.String(): common.Region_CN470,
		common.Region_CN779.String(): common.Region_CN779,
		common.Region_EU433.String(): common.Region_EU433,
		common.Region_EU868.String(): common.Region_EU868,
		common.Region_IN865.String(): common.Region_IN865,
		common.Region_KR920.String(): common.Region_KR920,
		common.Region_RU864.String(): common.Region_RU864,
		common.Region_US915.String(): common.Region_US915,
	}[band.Band().Name()]

	if !ok {
		log.WithFields(log.Fields{
			"band_name": band.Band().Name(),
		}).Warning("unknown band to common name mapping")
	}

	return &ns.GetVersionResponse{
		Region:  region,
		Version: config.Version,
	}, nil
}

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


Question:
Test if a given object resides inside the cache.<p>

@param theCacheObject the object to test
@return true if the object is inside the cache, false otherwise

private boolean isCached(I_CmsLruCacheObject theCacheObject) {

        if ((theCacheObject == null) || (m_objectCount == 0)) {
            // the cache is empty or the object is null (which is never cached)
            return false;
        }

        I_CmsLruCacheObject nextObj = theCacheObject.getNextLruObject();
        I_CmsLruCacheObject prevObj = theCacheObject.getPreviousLruObject();

        if ((nextObj != null) || (prevObj != null)) {
            // the object has either a predecessor or successor in the linked
            // list of all cached objects, so it is inside the cache
            return true;
        }

        // both nextObj and preObj are null
        if ((m_objectCount == 1)
            && (m_listHead != null)
            && (m_listTail != null)
            && m_listHead.equals(theCacheObject)
            && m_listTail.equals(theCacheObject)) {
            // the object is the one and only object in the cache
            return true;
        }

        return false;
    }

public function clear()
    {
        $cleared = false;
        try {
            /* @todo Not at all sure about this... do we really want to flush()? What happens if the storage supports
            /*       namespaces, but none has been provided? */
            $options = $this->storage->getOptions();
            $namespace = $options->getNamespace();
            if ($this->storage instanceof ClearByNamespaceInterface && $namespace) {
                $cleared = $this->storage->clearByNamespace($namespace);
            } elseif ($this->storage instanceof FlushableInterface) {
                $cleared = $this->storage->flush();
            } else {
                throw new CacheException(sprintf("Storage %s does not support clear()", get_class($this->storage)));
            }
        } catch (Exception\InvalidArgumentException $e) {
            throw new InvalidArgumentException($e->getMessage(), $e->getCode(), $e);

        } catch (Exception\ExceptionInterface $e) {
            throw new CacheException($e->getMessage(), $e->getCode(), $e);
        }

        return $cleared;
    }

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


Question:
Displays a form to create a new Customer entity.

@return \Symfony\Component\HttpFoundation\Response

public function newAction()
        {

            $oCustomer = new Customer();
            $form      = $this->createCreateForm($oCustomer);

            return $this->render('SlashworksAppBundle:Customer:new.html.twig', array(
                'entity' => $oCustomer,
                'form'   => $form->createView(),
            ));
        }

public function onKernelRequest(GetResponseEvent $event): void
    {
        if ('sonata_admin_dashboard' === $event->getRequest()->get('_route')) {
            $modelManager = $this->admin->getModelManager();

            $defaultDashboard = $modelManager->findOneBy($this->admin->getClass(), [
                'default' => true,
                'enabled' => true,
            ]);

            if ($defaultDashboard) {
                $url = $this->admin->generateObjectUrl('render', $defaultDashboard, ['default' => true]);
                $event->setResponse(new RedirectResponse($url));
            }
        }
    }

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


Question:
// SetSeparators sets the begin and end separator values for lists.   Setting
// the separators to "", empty strings, results in no separators being added.
// By default, "(" and ")" are used as the begin and end separators,

func (e *Encoder) SetSeparators(beg, end string) {
	e.sepBeg = beg
	e.sepEnd = end
}

def new(self, fname=None, editorstack=None, text=None):

        # If no text is provided, create default content
        empty = False
        try:
            if text is None:
                default_content = True
                text, enc = encoding.read(self.TEMPLATE_PATH)
                enc_match = re.search(r'-*- coding: ?([a-z0-9A-Z\-]*) -*-',
                                      text)
                if enc_match:
                    enc = enc_match.group(1)
                # Initialize template variables
                # Windows
                username = encoding.to_unicode_from_fs(
                                os.environ.get('USERNAME', ''))
                # Linux, Mac OS X
                if not username:
                    username = encoding.to_unicode_from_fs(
                                   os.environ.get('USER', '-'))
                VARS = {
                    'date': time.ctime(),
                    'username': username,
                }
                try:
                    text = text % VARS
                except Exception:
                    pass
            else:
                default_content = False
                enc = encoding.read(self.TEMPLATE_PATH)[1]
        except (IOError, OSError):
            text = ''
            enc = 'utf-8'
            default_content = True
            empty = True

        create_fname = lambda n: to_text_string(_("untitled")) + ("%d.py" % n)
        # Creating editor widget
        if editorstack is None:
            current_es = self.get_current_editorstack()
        else:
            current_es = editorstack
        created_from_here = fname is None
        if created_from_here:
            while True:
                fname = create_fname(self.untitled_num)
                self.untitled_num += 1
                if not osp.isfile(fname):
                    break
            basedir = getcwd_or_home()

            if self.main.projects.get_active_project() is not None:
                basedir = self.main.projects.get_active_project_path()
            else:
                c_fname = self.get_current_filename()
                if c_fname is not None and c_fname != self.TEMPFILE_PATH:
                    basedir = osp.dirname(c_fname)
            fname = osp.abspath(osp.join(basedir, fname))
        else:
            # QString when triggered by a Qt signal
            fname = osp.abspath(to_text_string(fname))
            index = current_es.has_filename(fname)
            if index is not None and not current_es.close_file(index):
                return

        # Creating the editor widget in the first editorstack (the one that
        # can't be destroyed), then cloning this editor widget in all other
        # editorstacks:
        finfo = self.editorstacks[0].new(fname, enc, text, default_content,
                                         empty)
        finfo.path = self.main.get_spyder_pythonpath()
        self._clone_file_everywhere(finfo)
        current_editor = current_es.set_current_filename(finfo.filename)
        self.register_widget_shortcuts(current_editor)
        if not created_from_here:
            self.save(force=True)

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


Question:
Gets the userLists value for this MutateMembersReturnValue.

@return userLists   * The user lists associated in mutate members operations.

public com.google.api.ads.adwords.axis.v201809.rm.UserList[] getUserLists() {
        return userLists;
    }

function (req, res, options) {
    if (!options) {
      options = {};
    }
    options.operation = 'SAVE';
    options.res = res;
    if (req.params.model) {
      options.model = req.params.model;
    }
    if (req.body) {
      options.item = req.body;
    }
    if (req.params.data) {
      options.data = req.params.data;
    }
    exports.save.before(req, res, options);
    var userId = req.session['user-id'];
    vulpejs.models.save({
      model: options.model,
      item: options.item,
      data: options.data,
      validate: options.validate || false,
      userId: userId,
      callback: {
        success: function (item) {
          if (!vulpejs.utils.execute(options.callback, {
              item: item,
              postedItem: options.item,
              res: res,
            })) {
            exports.save.after(req, res, item);
            res.json({
              item: item,
              postedItem: options.item,
            });
          }
        },
        error: function (error) {
          exports.response.error(options, error);
        },
        validate: function (validate) {
          exports.response.validate(options, validate);
        },
      },
    });
  }

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


Question:
// Get all replication controllers whose selectors would match a given set of
// labels.
// TODO Move this to pkg/client and ideally implement it server-side (instead
// of getting all RC's and searching through them manually).

func getReplicationControllersForLabels(c client.ReplicationControllerInterface, labelsToMatch labels.Labels) ([]api.ReplicationController, error) {
	// Get all replication controllers.
	// TODO this needs a namespace scope as argument
	rcs, err := c.List(unversioned.ListOptions{})
	if err != nil {
		return nil, fmt.Errorf("error getting replication controllers: %v", err)
	}

	// Find the ones that match labelsToMatch.
	var matchingRCs []api.ReplicationController
	for _, controller := range rcs.Items {
		selector := labels.SelectorFromSet(controller.Spec.Selector)
		if selector.Matches(labelsToMatch) {
			matchingRCs = append(matchingRCs, controller)
		}
	}
	return matchingRCs, nil
}

def remote_chassis_id_mac_uneq_store(self, remote_chassis_id_mac):

        if remote_chassis_id_mac != self.remote_chassis_id_mac:
            self.remote_chassis_id_mac = remote_chassis_id_mac
            return True
        return False

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


Question:
Convert a Matplotlib Figure to a Leaflet map. Embed in IPython notebook.

    Parameters
    ----------
    fig : figure, default gcf()
        Figure used to convert to map
    closefig : boolean, default True
        Close the current Figure

def display(fig=None, closefig=True, **kwargs):

    from IPython.display import HTML
    if fig is None:
        fig = plt.gcf()
    if closefig:
        plt.close(fig)

    html = fig_to_html(fig, **kwargs)

    # We embed everything in an iframe.
    iframe_html = '<iframe src="data:text/html;base64,{html}" width="{width}" height="{height}"></iframe>'\
    .format(html = base64.b64encode(html.encode('utf8')).decode('utf8'),
            width = '100%',
            height= int(60.*fig.get_figheight()),
           )
    return HTML(iframe_html)

def __convert_order_params_for_blotter(asset,
                                           limit_price,
                                           stop_price,
                                           style):

        if style:
            assert (limit_price, stop_price) == (None, None)
            return style
        if limit_price and stop_price:
            return StopLimitOrder(limit_price, stop_price, asset=asset)
        if limit_price:
            return LimitOrder(limit_price, asset=asset)
        if stop_price:
            return StopOrder(stop_price, asset=asset)
        else:
            return MarketOrder()

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


Question:
Move edges from node 1 to node 2

         Not self edges though

         Overwrites edges

def move_edges(self,n1,n2):

      #Traverse edges to find incoming with n1
      incoming = []
      for e in self._edges.values():
         if e.node2.id == n1.id: incoming.append(e)
      #Traverse edges to find outgoing from n1
      outgoing = []
      for e in self._edges.values():
         if e.node1.id == n1.id: outgoing.append(e)
      #Make new edges to the new target
      for e in incoming:
         if e.node1.id == n2.id: continue # skip self
         newedge = Edge(e.node1,n2,payload_list=n2.payload_list+n1.payload_list)
         self.add_edge(newedge)
      for e in outgoing:
         if e.node2.id == n2.id: continue # skip self
         newedge = Edge(n2,e.node2,payload_list=n2.payload_list+n1.payload_list)
         self.add_edge(newedge)
      #now remove the edges that got transfered
      for e in incoming: self.remove_edge(e)
      for e in outgoing: self.remove_edge(e)

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

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


Question: // Run exercises a YARPC server from a tchannel client.

func Run(t crossdock.T) {
	fatals := crossdock.Fatals(t)

	encoding := t.Param(params.Encoding)
	server := t.Param(params.Server)
	serverHostPort := fmt.Sprintf("%v:%v", server, serverPort)

	ch, err := tchannel.NewChannel("tchannel-client", nil)
	fatals.NoError(err, "Could not create channel")

	call := call{Channel: ch, ServerHostPort: serverHostPort}

	switch encoding {
	case "raw":
		runRaw(t, call)
	case "json":
		runJSON(t, call)
	case "thrift":
		runThrift(t, call)
	default:
		fatals.Fail("", "unknown encoding %q", encoding)
	}
}

def connect_channels(self, channels):
        """"""
        self.log.info(f"Connecting to channels...")
        for chan in channels:
            chan.connect(self.sock)
            self.log.info(f"\t{chan.channel}")

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


Question: 获取某个菜谱分类url下的所有菜谱url

def get_class_recipes(class_url, max_page=20, sleep=0.1):
    """"""
    class_url = class_url + "?page={page}"
    recipes = dict()

    # 暴力爬取方案，每个菜谱分类请求100页
    for page in range(1, max_page):
        time.sleep(sleep)
        url = class_url.format(page=page)
        print("current url: ", url)
        response = requests.get(url, headers=get_header())
        html = BeautifulSoup(response.text, "lxml")

        # 获取本页菜谱
        menus = html.find("div", {'class': 'new-menu-list search-menu-list clearfix mt10'})
        if menus:
            print("get recipes fail: ", url)
            menus = menus.find_all('a')
            for m in menus:
                name = re.sub("\n| ", "", m.text)
                recipe_url = urljoin(HOME_URL, m['href'])
                recipes[name] = recipe_url

        # 判断是否是最后一页
        # next_page = html.find('div', {'class': 'paging mt20'}).text
        # if "下一页" in next_page:
        #     page += 1
        # else:
        #     break
    return recipes

protected function getRedirectUri()
    {
        if (isset($_POST['redirect'])) {
            return $_POST['redirect'];
        }
        if (isset($_GET['redirect'])) {
            return $_GET['redirect'];
        }
        return \Staq::App()->getCurrentUri();
    }

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


Question:
Do the job.
Throw exceptions on errors (the job will be retried).

public function execute() {
        global $CFG;

        // The directories hosting the candidate stale temp files eventually are $CFG->tempdir and $CFG->backuptempdir.

        // Do the job on each of the directories above.
        // Let's start with $CFG->tempdir.
        $this->execute_on($CFG->tempdir);

        // Run on $CFG->backuptempdir too, if different from the default one, '$CFG->tempdir/backup'.
        if (realpath(dirname($CFG->backuptempdir)) !== realpath($CFG->tempdir)) {
            // The $CFG->backuptempdir setting is different from the default '$CFG->tempdir/backup'.
            $this->execute_on($CFG->backuptempdir);
        }
    }

public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}

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


Question:
show all the invalid properties with reasons.

@return array invalid properties with reasons

public function listInvalidProperties()
    {
        $invalid_properties = [];
        if ($this->container['characterId'] === null) {
            $invalid_properties[] = "'characterId' can't be null";
        }
        if ($this->container['joinTime'] === null) {
            $invalid_properties[] = "'joinTime' can't be null";
        }
        if ($this->container['role'] === null) {
            $invalid_properties[] = "'role' can't be null";
        }
        $allowed_values = ["fleet_commander", "wing_commander", "squad_commander", "squad_member"];
        if (!in_array($this->container['role'], $allowed_values)) {
            $invalid_properties[] = "invalid value for 'role', must be one of #{allowed_values}.";
        }

        if ($this->container['roleName'] === null) {
            $invalid_properties[] = "'roleName' can't be null";
        }
        if ($this->container['shipTypeId'] === null) {
            $invalid_properties[] = "'shipTypeId' can't be null";
        }
        if ($this->container['solarSystemId'] === null) {
            $invalid_properties[] = "'solarSystemId' can't be null";
        }
        if ($this->container['squadId'] === null) {
            $invalid_properties[] = "'squadId' can't be null";
        }
        if ($this->container['takesFleetWarp'] === null) {
            $invalid_properties[] = "'takesFleetWarp' can't be null";
        }
        if ($this->container['wingId'] === null) {
            $invalid_properties[] = "'wingId' can't be null";
        }
        return $invalid_properties;
    }

function validate(schema) {
        var key, item;
        for (key in schema) {
            if (schema.hasOwnProperty(key)) {
                item = schema[key];
                if (!item.text) {
                    console.error("[PreferenceManager] missing required field: 'text' of '" + key + "'");
                }
                if (!item.type) {
                    console.error("[PreferenceManager] missing required field: 'type' of '" + key + "'");
                }
                if (item.type !== "Section" && typeof item['default'] === "undefined") {
                    console.error("[PreferenceManager] missing required field: 'default' of '" + key + "'");
                }
                if (item.type === "Combo" || item.type === "Dropdown") {
                    if (item.options && item.options.length > 0) {
                        var i, len;
                        for (i = 0, len = item.options.length; i < len; i++) {
                            if (typeof item.options[i].value === "undefined") {
                                console.error("[PreferenceManager] missing required field of option item: 'value' of '" + key + "'");
                            }
                            if (typeof item.options[i].text === "undefined") {
                                console.error("[PreferenceManager] missing required field of option item: 'text' of '" + key + "'");
                            }
                        }
                    } else {
                        console.error("[PreferenceManager] missing required field or no items: 'options' of '" + key + "'");
                    }
                }
            }
        }
        return true;
    }

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


Question:
create a ImportFrom node and register it in the locals of the given
    node with the specified name

def attach_import_node(node, modname, membername):

    from_node = nodes.ImportFrom(modname, [(membername, None)])
    _attach_local_node(node, from_node, membername)

def process_raw_data(cls, raw_data):
        """"""
        properties = raw_data.get("properties", {})

        load_balancing_rules = []
        for raw_content in properties.get("loadBalancingRules", []):
            resource = Resource.from_raw_data(raw_content)
            load_balancing_rules.append(resource)
        properties["loadBalancingRules"] = load_balancing_rules

        inbound_nat_rules = []
        for raw_content in properties.get("inboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            inbound_nat_rules.append(resource)
        properties["inboundNatRules"] = inbound_nat_rules

        outbound_nat_rules = []
        for raw_content in properties.get("outboundNatRules", []):
            resource = Resource.from_raw_data(raw_content)
            outbound_nat_rules.append(resource)
        properties["outboundNatRules"] = outbound_nat_rules

        raw_content = properties.get("subnet", None)
        if raw_content is not None:
            resource = Resource.from_raw_data(raw_content)
            properties["subnet"] = resource

        return super(FrontendIPConfigurations, cls).process_raw_data(raw_data)

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


Question: set value into @env

def build
      path, qs = url.split('?')

      headrs = (headers || {}).inject({}) do |heads, (k, v)|
        heads.tap { |h| h["HTTP_#{k.gsub(/\-/, '_').upcase}"] = v }
      end

      env.merge!(headrs)

      env['REQUEST_METHOD'] = method.upcase

      if env['REQUEST_URI']
        env['REQUEST_URI'] = env['REQUEST_URI'].gsub(/#{ParallelBatchApi.batch_path}.*/, url)
      end

      env['REQUEST_PATH'] = env['PATH_INFO'] = path
      env['ORIGINAL_FULLPATH'] = url

      env['rack.request.query_string'] = qs
      env['QUERY_STRING'] = qs

      env['rack.request.form_hash'] = params
      env['rack.request.query_hash'] = method == ParallelBatchApi::HTTP_METHOD_GET ? params : nil

      env['action_dispatch.request.parameters'] = params
      env['action_dispatch.request.request_parameters'] = params

      env['CONTENT_TYPE'] = 'text/plain'
      env['HTTP_CONTENT_TYPE'] = 'text/plain'
      env['ROW_POST_DATA'] = ''
    end

def load_config(filepath)
      return {} if filepath.nil? || !File.exist?(filepath)

      config_file = File.open(filepath).read

      # Replace environment variables
      config_file = parse_environment_variables(config_file)

      YAML.safe_load(config_file)
    end

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


Question:
// Warningf logs with a warning level.
// Arguments are handled in the manner of fmt.Printf.

func (logger *Logger) Warningf(format string, args ...interface{}) {
	logger.output(log.Warning, fmt.Sprintf(format, args...))
}

def parseBasicOptions(parser):

    (options, args) = parser.parse_args()

    setLoggingFromOptions(options)

    #Set up the temp dir root
    if options.tempDirRoot == "None":
        options.tempDirRoot = os.getcwd()

    return options, args

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