Question:
Overrides the implementation from DefaultPlatform

@author     Niklas Närhinen <niklas@narhinen.net>
@return string
@see DefaultPlatform::getModifyColumnsDDL

public function getModifyColumnsDDL($columnDiffs)
    {
        $ret = '';
        foreach ($columnDiffs as $columnDiff) {
            $ret .= $this->getModifyColumnDDL($columnDiff);
        }

        return $ret;
    }

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:
动画结束回调
@param inst

function (inst) {
    if (inst.state === 'pinning') {
      inst.state = 'pinned';
      componentEvent('pinned', 'headroom', inst, inst.$headroom);
    }

    if (inst.state === 'unpinning') {
      inst.state = 'unpinned';
      componentEvent('unpinned', 'headroom', inst, inst.$headroom);
    }
  }

def build(self):

        self._cmd_parser.add_argument(
            'install',
            type=str,
            default=None,
            nargs="+",
            help=(""),
        )

        self._cmd_parser.add_argument(
            '-l',
            '--location',
            default=None,
            help=("Specify the installation location. ")
        )

        return super(Cmd, self).build()

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


Question:
/*
	Open a file, directory, or URI using the specified application.
	Don't wait for the open command to complete.
*/

func StartWith(input string, appName string) error {
	return openWith(input, appName).Start()
}

def mount(self, readonly=True):

        self._handler.add_drive_opts(self.disk_path, readonly=True)
        self._handler.launch()

        for mountpoint, device in self._inspect_disk():
            if readonly:
                self._handler.mount_ro(device, mountpoint)
            else:
                self._handler.mount(device, mountpoint)

        if self._handler.inspect_get_type(self._root) == 'windows':
            self.path = self._windows_path
        else:
            self.path = posix_path

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


Question:
Register fonts section and settings.

@action customize_registers
@since 1.0.0

@param WP_Customize_Manager $wp_customize

public function fonts( WP_Customize_Manager $wp_customize ) {

		if ( ! $this->fonts || ! $this->font_types ) {

			return;

		}

		$wp_customize->add_section(
			'fonts',
			array(
				'title'    => esc_html__( 'Fonts', 'rock' ),
				'priority' => 40,
			)
		);

		foreach ( $this->font_types as $name => $args ) {

			if ( empty( $name ) || empty( $args['default'] ) ) {

				continue;

			}

			$name = sanitize_key( $name );

			$wp_customize->add_setting(
				$name,
				array(
					'default'           => $args['default'],
					'sanitize_callback' => array( $this, 'sanitize_font' ),
				)
			);

			$fonts             = array_combine( $this->fonts, $this->fonts );
			$default           = $this->get_default_font( $name );
			$fonts[ $default ] = sprintf( esc_html_x( '%s (Default)', 'font name', 'rock' ), $default );

			$wp_customize->add_control(
				$name,
				array(
					'label'       => ! empty( $args['label'] ) ? $args['label'] : $name,
					'description' => ! empty( $args['description'] ) ? $args['description'] : null,
					'section'     => ! empty( $args['section'] ) ? $args['section'] : 'fonts',
					'priority'    => ! empty( $args['priority'] ) ? absint( $args['priority'] ) : null,
					'type'        => ! empty( $args['type'] ) ? $args['type'] : 'select',
					'choices'     => $fonts,
				)
			);

		}

	}

public function addMetaBoxes()
    {
        // Publish
        add_meta_box(
            'modularity-mb-editor-publish',
            __('Save modules', 'modularity'),
            function () {
                include MODULARITY_TEMPLATE_PATH . 'editor/modularity-publish.php';
            },
            $this->screenHook,
            'side'
        );

        // Modules
        add_meta_box(
            'modularity-mb-modules',
            __('Enabled modules', 'modularity'),
            function () {
                $enabled = \Modularity\ModuleManager::$enabled;
                $available = \Modularity\ModuleManager::$available;
                $deprecated = \Modularity\ModuleManager::$deprecated;

                $modules = array();
                if (is_array($enabled) && !empty($enabled)) {
                    foreach ($enabled as $module) {
                        if (isset($available[$module]) && !in_array($module, $deprecated)) {
                            $modules[$module] = apply_filters('Modularity/Editor/SidebarIncompability', $available[$module], $module);
                        }
                    }
                }

                uasort($modules, function ($a, $b) {
                    return $a['labels']['name'] > $b['labels']['name'];
                });

                include MODULARITY_TEMPLATE_PATH . 'editor/modularity-enabled-modules.php';
            },
            $this->screenHook,
            'side'
        );

        $this->addSidebarsMetaBoxes();
    }

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


Question:
// Check returns true if the Graph given as a parameter conforms to the
// schema represented by the receiver Graph.

func (g *Graph) Check(x *Graph) (bool, string) {

	for i := 0; i < g.Len(); i++ {
		ns := g.GetAt(i)
		nx := x.GetAt(i)

		b := ns.checkNode(nx)
		if !b {
			if ns != nil {
				return false, "want " + ns.ThisString() + ", got " + nx.ThisString()
			}
		}

		ok, mess := ns.Check(nx)
		if !ok {
			return false, mess
		}
	}

	return true, ""
}

protected function validateConfig()
    {
        $message = null;
        if (empty($this->config['api_key'])) {
            $message = 'Geocoder Config: Api Key is mandatory for using Google API.';
        }
        elseif (empty($this->config['request_url'])) {
            $message = 'Geocoder Config: Request URL is mandatory for using Google API.';
        }
        elseif (empty($this->config['output_format'])) {
            $message = 'Geocoder Config: Output Format is mandatory for using Google API.';
        }
        elseif ( ! in_array($this->config['output_format'], self::SUPPORTED_FORMATS)) {
            $message = 'Geocoder Config: Given Format is not supported.';
        }

        if ($message) {
            throw  new \InvalidArgumentException($message);
        }
    }

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


Question:
Returns the {@link HttpResponseStatus} represented by the specified code.
If the specified code is a standard RTSP getStatus code, a cached instance
will be returned.  Otherwise, a new instance will be returned.

public static HttpResponseStatus valueOf(int code) {
        switch (code) {
        case 250: return LOW_STORAGE_SPACE;
        case 302: return MOVED_TEMPORARILY;
        case 451: return PARAMETER_NOT_UNDERSTOOD;
        case 452: return CONFERENCE_NOT_FOUND;
        case 453: return NOT_ENOUGH_BANDWIDTH;
        case 454: return SESSION_NOT_FOUND;
        case 455: return METHOD_NOT_VALID;
        case 456: return HEADER_FIELD_NOT_VALID;
        case 457: return INVALID_RANGE;
        case 458: return PARAMETER_IS_READONLY;
        case 459: return AGGREGATE_OPERATION_NOT_ALLOWED;
        case 460: return ONLY_AGGREGATE_OPERATION_ALLOWED;
        case 461: return UNSUPPORTED_TRANSPORT;
        case 462: return DESTINATION_UNREACHABLE;
        case 463: return KEY_MANAGEMENT_FAILURE;
        case 505: return RTSP_VERSION_NOT_SUPPORTED;
        case 551: return OPTION_NOT_SUPPORTED;
        default:  return HttpResponseStatus.valueOf(code);
        }
    }

def get_auth_uri(auth_service, client_id, scope, redirect_uri, response_type,
                 state, access_type, approval_prompt):
  """"""
  errors = []
  if response_type not in VALID_RESPONSE_TYPES:
    errors.append(
        '{0} is not a valid response_type, must be {1}.'.format(
        response_type, VALID_RESPONSE_TYPES))
  if not client_id:
    errors.append('client_id is missing or empty.')
  if not redirect_uri:
    errors.append('redirect_uri is missing or empty.')
  if not scope:
    errors.append('scope is missing or empty.')
  if access_type not in VALID_ACCESS_TYPES:
    errors.append('access_type is invalid.')
  if approval_prompt not in VALID_APPROVAL_PROMPTS:
    errors.append('approval_prompt is invalid')
  if errors:
    raise ValueError('Invalid parameters: {0}'.format('\n'.join(errors)))
  params = {
      'response_type': response_type,
      'client_id': client_id,
      'redirect_uri': redirect_uri,
      'scope': scope,
      'access_type': access_type,
      'approval_prompt': approval_prompt,
      'state': state,
  }
  return '?'.join([auth_service, urllib.urlencode(params)])

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


Question: shutdown all configured cluster monitors.

@Override
	public void shutdownClusterMonitors() {
		for (String clusterName : clustersProvider.getClusterNames()) {
			ClusterMonitor<AggDataFromCluster> clusterMonitor = (ClusterMonitor<AggDataFromCluster>) AggregateClusterMonitor
					.findOrRegisterAggregateMonitor(clusterName);
			clusterMonitor.stopMonitor();
			clusterMonitor.getDispatcher().stopDispatcher();
		}
	}

func (db *StakeDatabase) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup,
	reorgChan chan *txhelpers.ReorgData) *ChainMonitor {
	return &ChainMonitor{
		ctx:       ctx,
		db:        db,
		wg:        wg,
		reorgChan: reorgChan,
	}
}

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


Question:
Get all cache directory
@return Renderer
@throws

public function getAllEnvActivity()
    {
        $directory = array();
        $iterator = new DirectoryIterator(FEnv::get("framework.cache"));
        foreach ($iterator as $dir_info) {
            if ($dir_info->isDir() && !$dir_info->isDot()) {
                $octal_perms = substr(sprintf('%o', $dir_info->getPerms()), -4);
                $perms = false;

                if ($octal_perms == "0777" || $octal_perms == "0775"  || $octal_perms == "0755" ||
                    $octal_perms == "7775" || $octal_perms == "7777" || $octal_perms == "7755") {
                    $perms = true;
                }
                array_push($directory, array("path" => $dir_info->getRealPath(), "name" => $dir_info->getFilename(),
                    "size" => ($this->fileSizeConvert($this->folderSize($dir_info->getRealPath()))),
                    "nperms" => $octal_perms,
                    "perms" => $perms, "status" => (($this->checkFolderIsEmptyOrNot(FEnv::get("framework.cache").
                            $dir_info->getFilename()) == true)? "Empty" : "Not empty"),
                    "env" => $dir_info->getFilename(),
                    "clear" => $this->generateRoute(
                        "iumio_manager_cache_manager_remove",
                        array("env" => $dir_info->getFilename()),
                        null,
                        true
                    )));
            }
        }

        return ((new Renderer())->jsonRenderer(array("code" => 200, "results" => $directory)));
    }

public function exec_action($action)
    {
        if (isset($this->actions[$action])) {
            call_user_func($this->actions[$action]);
        }
        else if (rcube::get_instance()->action != 'refresh') {
            rcube::raise_error(array('code' => 524, 'type' => 'php',
                'file' => __FILE__, 'line' => __LINE__,
                'message' => "No handler found for action $action"), true, true);
        }
    }

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


Question: // SetAcceptLanguage sets the AcceptLanguage field's value.

func (s *UpdateConstraintInput) SetAcceptLanguage(v string) *UpdateConstraintInput {
	s.AcceptLanguage = &v
	return s
}

def get_language(self):

        # we don't want to force the target language
        # so we use the article.meta_lang
        if self.config.use_meta_language:
            if self.article.meta_lang:
                return self.article.meta_lang[:2]
        return self.config.target_language

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


Question: // SetLoadBalancers sets the LoadBalancers field's value.

func (s *CreateTaskSetInput) SetLoadBalancers(v []*LoadBalancer) *CreateTaskSetInput {
	s.LoadBalancers = v
	return s
}

public static Variable lookup(String varName, BindingSet bindingSet) {
        if (bindingSet == null) {
            return null;
        }
        Binding binding = bindingSet.lookup(varName);
        return (binding != null) ? binding.getVariable() : null;
    }

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


Question:
Restore the Y position (used after a span)

@return void

public function restorePosition()
    {
        if ($this->value['y'] == $this->pdf->GetY()) {
            $this->pdf->SetY($this->value['yc'], false);
        }
    }

function () {
            var spaceCharCode = " ".charCodeAt(0);
            var glyph = this.glyphs[spaceCharCode];
            if (!glyph) {
                glyph = new Glyph();
                glyph.id = spaceCharCode;
                glyph.xadvance = this._getFirstGlyph().xadvance;
                this.glyphs[spaceCharCode] = glyph;
            }
        }

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


Question: Make a put request (this returns a coroutine)

def put(self, service, path, body, **kwargs):

        return self.make_request(Methods.POST, service, path, body=body,
                                 **kwargs)

async def stream(
        self, version="1.1", keep_alive=False, keep_alive_timeout=None
    ):

        headers = self.get_headers(
            version,
            keep_alive=keep_alive,
            keep_alive_timeout=keep_alive_timeout,
        )
        self.protocol.push_data(headers)
        await self.protocol.drain()
        await self.streaming_fn(self)
        self.protocol.push_data(b"0\r\n\r\n")

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


Question: // AddChildIndexer adds a child ChainIndexer that can use the output of this one

func (c *ChainIndexer) AddChildIndexer(indexer *ChainIndexer) {
	c.lock.Lock()
	defer c.lock.Unlock()

	c.children = append(c.children, indexer)

	// Cascade any pending updates to new children too
	sections := c.storedSections
	if c.knownSections < sections {
		// if a section is "stored" but not "known" then it is a checkpoint without
		// available chain data so we should not cascade it yet
		sections = c.knownSections
	}
	if sections > 0 {
		indexer.newHead(sections*c.sectionSize-1, false)
	}
}

public function findReferences($rid, array $classes = array(), $append = true)
    {
        $commandClass = $this->getCommandClass('references.find');
        $this->command = new $commandClass($rid);
        $this->command->in($classes, $append);

        return $this->command;
    }

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


Question: // ConfigureOutputFormat ...

func ConfigureOutputFormat(c *cli.Context) error {
	outFmt := c.String(FormatKey)
	switch outFmt {
	case FormatRaw, FormatJSON, FormatYML:
		// valid
		Format = outFmt
	case "":
		// default
		Format = FormatRaw
	default:
		// invalid
		return fmt.Errorf("Invalid Output Format: %s", outFmt)
	}
	return nil
}

func get_formatter(name string) formatter {
	switch name {
	case "vim":
		return new(vim_formatter)
	case "emacs":
		return new(emacs_formatter)
	case "nice":
		return new(nice_formatter)
	case "csv":
		return new(csv_formatter)
	case "csv-with-package":
		return new(csv_with_package_formatter)
	case "json":
		return new(json_formatter)
	case "godit":
		return new(godit_formatter)
	}
	return new(nice_formatter)
}

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


Question: Javadoc comment.

@Benchmark
  @BenchmarkMode(Mode.SampleTime)
  @OutputTimeUnit(TimeUnit.NANOSECONDS)
  public StatsTraceContext newClientContext() {
    return StatsTraceContext.newClientContext(CallOptions.DEFAULT, Attributes.EMPTY, emptyMetadata);
  }

void buildMarkdown(Node parent) throws InvalidInputException {
    for (Element child : this.children) {
      Node node = child.asMarkdown();

      if (node != null) {
        parent.appendChild(node);
      } else {
        node = parent;
      }
      child.buildMarkdown(node);
    }
  }

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


Question:
数组去重

@param {Array} array 数组
@return {Array}

function arrayUniq (array) {
  var result = []
  baseExports.each(array, function (value) {
    if (!result.includes(value)) {
      result.push(value)
    }
  })
  return result
}

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

        return;
    }

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


Question:
Set the menu view to an explicit view.

@param view   The menu view.
@param params Layout parameters for the view.

public void setMenuView(View view, LayoutParams params) {
        mMenuView = view;
        mMenuContainer.removeAllViews();
        mMenuContainer.addView(view, params);
    }

public function render(array $data, ContextInterface $context)
    {
        $data = optionsParser($data, [
            'name' => '',
            'val' => null,
            'type' => 'text',
            'escape' => true,
            'templateVars' => [],
        ]);
        $data->add('value', $data->consume('val'));

        return $this->_templates->format('hidden', [
            'name' => $data->get('name'),
            'type' => $data->get('type'),
            'templateVars' => $data->get('templateVars'),
            'attrs' => $this->_templates->formatAttributes($data->toArray(), ['name', 'type']),
        ]);
    }

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


Question:
@since 0.6.0
 @api private

 rubocop:disable Metrics/MethodLength

def install
      desc "Load the full project"
      task :environment do
        require 'hanami/environment'
        Hanami::Environment.new.require_project_environment
        Components.resolve('all')
      end

      # Ruby ecosystem compatibility
      #
      # Most of the SaaS automatic tasks are designed after Ruby on Rails.
      # They expect the following Rake tasks to be present:
      #
      #   * db:migrate
      #   * assets:precompile
      #
      # See https://github.com/heroku/heroku-buildpack-ruby/issues/442
      #
      # ===
      #
      # These Rake tasks aren't listed when someone runs `rake -T`, because we
      # want to encourage developers to use `hanami` commands.
      #
      # In order to migrate the database or precompile assets a developer should
      # use:
      #
      #   * hanami db migrate
      #   * hanami assets precompile
      #
      # This is the preferred way to run Hanami command line tasks.
      # Please use them when you're in control of your deployment environment.
      #
      # If you're not in control and your deployment requires these "standard"
      # Rake tasks, they are here to solve this only specific problem.
      namespace :db do
        task :migrate do
          run_hanami_command("db migrate")
        end
      end

      namespace :assets do
        task :precompile do
          run_hanami_command("assets precompile")
        end
      end
    end

public function get_secure_url_token($generate = false)
    {
        if ($len = $this->config->get('use_secure_urls')) {
            if (empty($_SESSION['secure_token']) && $generate) {
                // generate x characters long token
                $length = $len > 1 ? $len : 16;
                $token  = rcube_utils::random_bytes($length);

                $plugin = $this->plugins->exec_hook('secure_token',
                    array('value' => $token, 'length' => $length));

                $_SESSION['secure_token'] = $plugin['value'];
            }

            return $_SESSION['secure_token'];
        }

        return false;
    }

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


Question:
@param $model

@throws ModelSanityException

public function bootstrapModel($model)
    {
        if (! property_exists($model, 'rules')) {
            throw new ModelSanityException('Missing rules property for model '.get_class($model));
        }

        if (! $model instanceof AdminModel) {
            throw new ModelSanityException('Model '.get_class($model).' must be instanceof '.AdminModel::class);
        }

        $imageFields = $model->getImageFields();

        if (! is_array($imageFields)) {
            throw new ModelSanityException('No Image fields defined in config for model '.get_class($model));
        }

        // Check for fields collisions
        foreach ($imageFields as $imageFieldName => $imageField) {
            $imageMetaFields = $model->getImageMetaFields($imageFieldName);
            foreach ($imageMetaFields as $metaFieldName => $options) {
            }
        }

        $model->setRetinaFactor(config('ignicms.images.retina_factor'));

        foreach ($imageFields as $fieldName => $field) {
            $model->prepareImageRules($model, 'rules', $fieldName, $field);
        }
    }

public function render($request, Exception $exception)
	{
		return Exceptum::render($request, $exception) ?? parent::render($request, $exception);
	}

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


Question:
/*
(non-Javadoc)

@see qc.automation.framework.widget.IInteractiveElement#typeAppend(java.lang.String,
java.lang.String)

public void typeAppend(String text) throws WidgetException {
        try{
        	synchronized (InteractiveElement.class) {
	            getGUIDriver().focus();
	            click();
	            WebElement e = getWebElement();
	            e.sendKeys(text);
	        }
        }catch(Exception e){
        	throw new WidgetException("Error while trying to type append ", getByLocator(), e);
        }
    }

def add_line(self, string):

        self.code_strings.append(string)
        code = ''
        if len(self.code_strings) == 1:
            code = '(setv result ' + self.code_strings[0] + ')'
        if len(self.code_strings) > 1:
            code = '(setv result (and ' + ' '.join(self.code_strings) + '))'
        self._compiled_ast_and_expr = self.__compile_code(code_string=code)

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


Question: substracts the column names from the first and second row in the dataset

private function getColumns($data)
        {
            $cols = [];

            foreach ($data[0] as $key => $value) {
                if (is_numeric($key)){
                    if (is_string($data[1][$key])) {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $value, 'type' => 'number'];
                    }

                    $this->_skipFirstRow = true;
                } else {
                    if (is_string($value)) {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'string'];
                    } else {
                        $cols[] = ['id' => '', 'label' => $key, 'type' => 'number'];
                    }
                }
            }

            return $cols;
        }

def delete_cols(self, col, no_cols=1):
        """"""

        # Mark content as changed
        post_command_event(self.main_window, self.ContentChangedMsg)

        tab = self.grid.current_table

        try:
            self.code_array.delete(col, no_cols, axis=1, tab=tab)

        except ValueError, err:
            post_command_event(self.main_window, self.StatusBarMsg,
                               text=err.message)

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


Question:
r"""

        requires _fill_loggs and _fill_gravs to have been called

        Calculate local temperature of a Star.

def _fill_teffs(self, mesh=None, ignore_effects=False, **kwargs):

        """
        logger.debug("{}._fill_teffs".format(self.component))

        if mesh is None:
            mesh = self.mesh

        # Now we can compute the local temperatures.
        # see PHOEBE Legacy scientific reference eq 5.23
        teffs = self.instantaneous_tpole*mesh.gravs.for_computations**0.25

        if not ignore_effects:
            for feature in self.features:
                if feature.proto_coords:
                    teffs = feature.process_teffs(teffs, mesh.roche_coords_for_computations, s=self.polar_direction_xyz, t=self.time)
                else:
                    teffs = feature.process_teffs(teffs, mesh.coords_for_computations, s=self.polar_direction_xyz, t=self.time)

        mesh.update_columns(teffs=teffs)

        if not self.needs_recompute_instantaneous:
            logger.debug("{}._fill_teffs: copying teffs to standard mesh".format(self.component))
            theta = 0.0
            self._standard_meshes[theta].update_columns(teffs=teffs)

func (rm *RegistryMessage) port() (uint16, bool, error) {
	if rm.TLSPort != 0 {
		return rm.TLSPort, true, nil
	}
	return rm.Port, false, nil
}

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


Question:
Returns {@code true} if the end date occurs after the start date during
the period of time represented by this time span.

public boolean insideRange(long startDate, long endDate) {
	Calendar c1 = Calendar.getInstance();
	Calendar c2 = Calendar.getInstance();
	c1.setTimeInMillis(startDate);
	c2.setTimeInMillis(endDate);
	return isInRange(c1, c2);
    }

public static boolean isStaxPresent() {
		Boolean retVal = ourStaxPresent;
		if (retVal == null) {
			try {
				Class.forName("javax.xml.stream.events.XMLEvent");
				Class<?> xmlUtilClazz = Class.forName("ca.uhn.fhir.util.XmlUtil");
				xmlUtilClazz.getMethod("createXmlReader", Reader.class).invoke(xmlUtilClazz, new StringReader(""));
				ourStaxPresent = Boolean.TRUE;
				retVal = Boolean.TRUE;
			} catch (Throwable t) {
				ourLog.info("StAX not detected on classpath, XML processing will be disabled");
				ourStaxPresent = Boolean.FALSE;
				retVal = Boolean.FALSE;
			}
		}
		return retVal;
	}

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


Question:
Get layer output type.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


Question: Remove deactivated handlers from the chain

def _remove_deactivated(contexts):
    """"""
    # Clean ctx handlers
    stack_contexts = tuple([h for h in contexts[0] if h.active])

    # Find new head
    head = contexts[1]
    while head is not None and not head.active:
        head = head.old_contexts[1]

    # Process chain
    ctx = head
    while ctx is not None:
        parent = ctx.old_contexts[1]

        while parent is not None:
            if parent.active:
                break
            ctx.old_contexts = parent.old_contexts
            parent = parent.old_contexts[1]

        ctx = parent

    return (stack_contexts, head)

async def xgroup_del_consumer(self, name: str, group: str, consumer: str) -> int:

        return await self.execute_command('XGROUP DELCONSUMER', name, group, consumer)

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


Question: Converts API response of bulk operation into object and returns the object array in case of get request.

protected base_resource[] get_nitro_bulk_response(nitro_service service, String response) throws Exception
	{
		mps_network_config_responses result = (mps_network_config_responses) service.get_payload_formatter().string_to_resource(mps_network_config_responses.class, response);
		if(result.errorcode != 0)
		{
			if (result.errorcode == SESSION_NOT_EXISTS)
				service.clear_session();
			throw new nitro_exception(result.message, result.errorcode, (base_response [])result.mps_network_config_response_array);
		}
		mps_network_config[] result_mps_network_config = new mps_network_config[result.mps_network_config_response_array.length];

		for(int i = 0; i < result.mps_network_config_response_array.length; i++)
		{
			result_mps_network_config[i] = result.mps_network_config_response_array[i].mps_network_config[0];
		}

		return result_mps_network_config;
	}

protected function applyBulk( $model, $column, $action, $target, $config = [] ) {

		switch( $column ) {

			case 'status': {

				switch( $action ) {

					case 'confirmed': {

						$this->confirm( $model );

						break;
					}
					case 'approved': {

						$this->approve( $model );

						break;
					}
					case 'rejected': {

						$this->reject( $model );

						break;
					}
					case 'active': {

						$this->activate( $model );

						break;
					}
					case 'frozen': {

						$this->freeze( $model );

						break;
					}
					case 'blocked': {

						$this->block( $model );

						break;
					}
					case 'terminated': {

						$this->terminate( $model );

						break;
					}
				}

				break;
			}
			case 'model': {

				switch( $action ) {

					case 'pinned': {

						$model->pinned = true;

						$model->update();

						break;
					}
					case 'featured': {

						$model->featured = true;

						$model->update();

						break;
					}
					case 'delete': {

						$this->delete( $model );

						break;
					}
				}

				break;
			}
		}
	}

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


Question:
All installed plugins (directory scan).

@since 160524 First documented version.

@param bool $slugify Keyed by slug?

@return array All installed plugins (keyed by plugin basename).

public function allInstalled(bool $slugify = true): array
    {
        $cache_key = '_'.(int) $slugify; // Network wide.

        if (isset(static::$cache[__FUNCTION__][$cache_key])) {
            return static::$cache[__FUNCTION__][$cache_key];
        }
        // Contains the `get_plugins()` function.
        require_once ABSPATH.'wp-admin/includes/plugin.php';

        if ($this->Wp->is_admin) { // Typical use case.
            $installed_plugins = apply_filters('all_plugins', get_plugins());
        } else { // Abnormal use case; no filter here.
            $installed_plugins = get_plugins(); // See: <http://jas.xyz/1NN5zhk>
            // No filter; because it may trigger routines expecting other admin functions
            // that will not exist in this context. That could lead to fatal errors.
        }
        $installed_plugins = is_array($installed_plugins) ? $installed_plugins : [];

        if ($slugify) { // Key by slug.
            $installed_plugins_ = $installed_plugins;
            $installed_plugins  = []; // Reinitialize.
            foreach ($installed_plugins_ as $_basename => $_data) {
                if (($_slug = $this->s::pluginSlug($_basename))) {
                    $installed_plugins[$_slug]             = $_data;
                    $installed_plugins[$_slug]['Basename'] = $_basename;
                }
            } // unset($installed_plugins_, $_basename, $_data); // Housekeeping.
        }
        return static::$cache[__FUNCTION__][$cache_key] = $installed_plugins;
    }

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:
refund a charge
@param RequestModels\ChargeRefund $requestModel
@return ResponseModels\Charge

public function refundCardChargeRequest(RequestModels\ChargeRefund
	                                        $requestModel)
	{

		$chargeMapper = new ChargesMapper($requestModel);

		$requestPayload = array (
			'authorization' => $this->_apiSetting->getSecretKey(),
			'mode'          => $this->_apiSetting->getMode(),
			'postedParam'   => $chargeMapper->requestPayloadConverter(),

		);
		$refundUri = sprintf ($this->_apiUrl->getChargeRefundsApiUri(),$requestModel->getChargeId());

		$processCharge = \com\checkout\helpers\ApiHttpClient::postRequest($refundUri,
			$this->_apiSetting->getSecretKey(),$requestPayload);

		$responseModel = new ResponseModels\Charge($processCharge);

		return $responseModel;
	}

protected function substituteImplicitBindings( $route )
	{
		$parameters = $route->parameters();

		foreach ( $route->signatureParameters( Model::class ) as $parameter )
		{
			$class = $parameter->getClass();

			if ( array_key_exists( $parameter->name, $parameters ) && !$route->getParameter( $parameter->name ) instanceof Model )
			{
				$method = $parameter->isDefaultValueAvailable() ? 'first' : 'firstOrFail';

				$model = $class->newInstance();

				$route->setParameter( $parameter->name, $model->where( $model->getRouteKeyName(), $parameters[$parameter->name] )->{$method()} );
			}
		}
	}

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


Question:
Laedt eine einzelne FunctionLib.

@param res FLD die geladen werden soll.
@param saxParser Definition des Sax Parser mit dem die FunctionLib eingelsesen werden soll.
@return FunctionLib
@throws FunctionLibException

public static FunctionLib loadFromFile(Resource res, Identification id) throws FunctionLibException {
	// Read in XML
	FunctionLib lib = FunctionLibFactory.hashLib.get(id(res));// getHashLib(file.getAbsolutePath());
	if (lib == null) {
	    lib = new FunctionLibFactory(null, res, id, false).getLib();
	    FunctionLibFactory.hashLib.put(id(res), lib);
	}
	lib.setSource(res.toString());

	return lib;
    }

public void marshall(CreateResolverRuleRequest createResolverRuleRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(createResolverRuleRequest.getCreatorRequestId(), CREATORREQUESTID_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getName(), NAME_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getRuleType(), RULETYPE_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getDomainName(), DOMAINNAME_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getTargetIps(), TARGETIPS_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getResolverEndpointId(), RESOLVERENDPOINTID_BINDING);
            protocolMarshaller.marshall(createResolverRuleRequest.getTags(), TAGS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Only simple column reference or column position allowed

void resolveColumnRefernecesInUnionOrderBy() {

        int orderCount = sortAndSlice.getOrderLength();

        if (orderCount == 0) {
            return;
        }

        String[] unionColumnNames = getColumnNames();

        for (int i = 0; i < orderCount; i++) {
            Expression sort = (Expression) sortAndSlice.exprList.get(i);
            Expression e    = sort.getLeftNode();

            if (e.getType() == OpTypes.VALUE) {
                if (e.getDataType().typeCode == Types.SQL_INTEGER) {
                    int index = ((Integer) e.getValue(null)).intValue();

                    if (0 < index && index <= unionColumnNames.length) {
                        sort.getLeftNode().queryTableColumnIndex = index - 1;

                        continue;
                    }
                }
            } else if (e.getType() == OpTypes.COLUMN) {
                int index = ArrayUtil.find(unionColumnNames,
                                           e.getColumnName());

                if (index >= 0) {
                    sort.getLeftNode().queryTableColumnIndex = index;

                    continue;
                }
            }

            throw Error.error(ErrorCode.X_42576);
        }

        sortAndSlice.prepare(null);
    }

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

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

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


Question:
Simplifying parameter syntax

@param array $config

@return array

public function getParameters(array $config)
    {
        $params = [
            'opifer_eav.attribute_class' => $config['attribute_class'],
            'opifer_eav.media_class'     => $config['media_class'],
            'opifer_eav.nestable_class'  => $config['nestable_class'],
            'opifer_eav.option_class'    => $config['option_class'],
            'opifer_eav.schema_class'  => $config['schema_class'],
            'opifer_eav.valueset_class'  => $config['valueset_class'],
        ];

        foreach ($config['entities'] as $label => $entity) {
            $params['opifer_eav.entities'][$label] = $entity;
        }

        return $params;
    }

private function invalidType($name, $provided)
    {
        $expected = implode('|', $this->argDefinitions[$name]['valid']);
        $msg = "Invalid configuration value "
            . "provided for \"{$name}\". Expected {$expected}, but got "
            . describe_type($provided) . "\n\n"
            . $this->getArgMessage($name);
        throw new IAE($msg);
    }

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


Question:
Filter and return entries that match any of specified patterns.

@param string[] $patterns
@param string[] $entries
@return string[]

public static function findFew($patterns, $entries)
    {
        $found = [];

        foreach ($patterns as $pattern)
        {
            $found = array_merge($found, static::findOne($pattern, $entries));
        }

        $found = array_unique($found);
        $results = [];

        foreach ($entries as $entry)
        {
            if (in_array($entry, $found, true) === true)
            {
                $results[] = $entry;
            }
        }

        unset($found);

        return $results;
    }

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: // MonthWide returns the locales wide month given the 'month' provided

func (sg *sg_CF) MonthWide(month time.Month) string {
	return sg.monthsWide[month]
}

static public function create($params, LocatorInterface $locator = null) {
		if (! is_array($params) && ! $params instanceof Traversable) {
			throw new InvalidOptions('Options must be an array or a Traversable implementation');
		}

		if ($params instanceof Traversable) {
			$params = Std::iteratorToArray($params);
		}

		$translator = new Translator();

		foreach ($params as $param => $value) {
			if ($param === 'cacheStrategy') {
				$class = self::NAMESPACE_CACHE . '\Strategy' . ucfirst($value);

				$translator->setCache(new $class($locator));
				unset($params[$param]);
				continue;
			}

			if ($param === 'resources') {
				if (! is_array($value) && ! $value instanceof Traversable) {
					throw new InvalidOptions('Resources definition must be an array or a Traversable implementation');
				}

				$translator->setResources(self::createResources($value));
				unset($params[$param]);
				continue;
			}

			if ($param === 'bbcodes') {
				if ($value) {
					$bbcodes = new BBCodes();

					if (isset($params['paramsPattern'])) {
						$bbcodes->setParamsPattern($params['paramsPattern']);
					}

					$translator->addPlugin($bbcodes, 'bbcodes');
				}

				unset($params[$param]);
			}
		}

		$translator->setOptions($params, false, false);

		return $translator;
	}

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


Question:
// Grow ensures that the bitset s is large enough to hold numBits number of
// bits, potentially appending to and/or reallocating the slice if the
// current length is not sufficient.

func (s *Bytes) Grow(numBits int) {
	bytes := *s
	targetLen := (numBits + byteModMask) >> byteShift
	missing := targetLen - len(bytes)
	if missing > 0 && missing <= targetLen {
		*s = append(bytes, make(Bytes, missing)...)
	}
}

def random_bytes(length)
      if (length.kind_of?(Array) || length.kind_of?(Range))
        Array.new(length.sort_by { rand }.first) { random_byte }
      else
        Array.new(length) { random_byte }
      end
    end

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


Question: // SetDiskPlan プラン文字列(ssd or sdd)からプラン設定

func (d *Disk) SetDiskPlan(strPlan string) {
	switch strPlan {
	case "ssd":
		d.Plan = DiskPlanSSD
	case "hdd":
		d.Plan = DiskPlanHDD
	default:
		panic(fmt.Errorf("Invalid plan:%s", strPlan))
	}
}

def _create_shell_session():

        import py4j
        from pyspark.conf import SparkConf
        from pyspark.context import SparkContext
        try:
            # Try to access HiveConf, it will raise exception if Hive is not added
            conf = SparkConf()
            if conf.get('spark.sql.catalogImplementation', 'hive').lower() == 'hive':
                SparkContext._jvm.org.apache.hadoop.hive.conf.HiveConf()
                return SparkSession.builder\
                    .enableHiveSupport()\
                    .getOrCreate()
            else:
                return SparkSession.builder.getOrCreate()
        except (py4j.protocol.Py4JError, TypeError):
            if conf.get('spark.sql.catalogImplementation', '').lower() == 'hive':
                warnings.warn("Fall back to non-hive support because failing to access HiveConf, "
                              "please make sure you build spark with hive")

        return SparkSession.builder.getOrCreate()

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


Question:
设置卡券失效.

@param string $code
@param string $cardId

@return mixed

public function disable(string $code, string $cardId = '')
    {
        $params = [
            'code' => $code,
            'card_id' => $cardId,
        ];

        return $this->httpPostJson('card/code/unavailable', $params);
    }

public function render() {

		$ret = '<input ' . $this->getNameProperty();

		switch ($this->type) {

            default:
            case 'text':
            case 'email':
            case 'tel':
            case 'url':
            case 'color':
            case 'password':
                $ret .= ' type="' . htmlspecialchars($this->type) . '" value="' . htmlspecialchars($this->value) . '"';
                break;

            case 'number':
            	$curr = setlocale(LC_NUMERIC, 0);
            	setlocale(LC_NUMERIC, 'en_US');
            	$ret .= ' type="number" value="' . htmlspecialchars($this->value) . '"';
            	setlocale(LC_NUMERIC, $curr);
            	break;

            case 'bool':
                $ret .= ' type="checkbox" value="1"';
                if ($this->value) $ret .= ' checked="checked"';
                break;

            case 'date':
                $ret .= ' type="date" value="' . htmlspecialchars($this->value) . '"';
				break;

			case 'datetime':
				$type = Input::usingCustomDatetimepicker() ? 'datetime' : 'datetime-local';
				$ret .= ' type="' . $type . '" value="' . htmlspecialchars($this->value) . '"';
				break;

			case 'file':
				$ret .= ' type="file"';
				break;

			case 'address':
				$ret .= ' type="text" value="'. htmlspecialchars($this->value) .'" size="50" autocomplete="on" placeholder=""';
				$this->addClass('googlePlacesAutocomplete');
				break;

			case 'hidden':
				$ret .= ' type="hidden" value="' . htmlspecialchars($this->value) . '"';
				break;

		}

		// set min and max value attribute for date and number only
		if (in_array($this->type, ['number','date'])) {

			if ($this->min) {
				$ret .= ' min="' . htmlspecialchars($this->min) . '"';
			}

			if ($this->max) {
				$ret .= ' max="' . htmlspecialchars($this->max) . '"';
			}

		}

		// set minlength attribute
		if ($this->minLength) {
			$ret .= ' minlength="' . htmlspecialchars($this->minLength) . '"';
		}

		// set maxlength attribute
		if ($this->maxLength) {
			$ret .= ' maxlength="' . htmlspecialchars($this->maxLength) . '"';
		}

		// set accept attribute
		if ($this->accept) {
			$ret .= ' accept="' . $this->accept . '"';
		}

		// set step attribute
		if ($this->step) {
			$ret .= ' step="' . htmlspecialchars($this->step) . '"';
		}

		$ret .= $this->processProperties() . ' />';

		return $ret;

	}

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


Question:
Initialize the cache : delete all the "old-version" values

@method init

function() {
            var s = Storage.storage();
            if (s == null) {
                return false;
            }
            Object.keys(s).forEach(function(key){
                if (key.indexOf("cache_") == 0 && key.indexOf("cache_"+configs.revision) ) {
                    s.removeItem(key);
                }
            });
        }

def clear_assessments(self):

        # Implemented from template for osid.learning.ActivityForm.clear_assets_template
        if (self.get_assessments_metadata().is_read_only() or
                self.get_assessments_metadata().is_required()):
            raise errors.NoAccess()
        self._my_map['assessmentIds'] = self._assessments_default

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


Question:
@param string $uri
@param string $query

@return bool|mixed

public function has(string $uri, string $query = ''): bool
    {

        return $this->memcached->get($this->buildCacheKey($uri, $query)) !== false;
    }

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

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

        return $route;
    }

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


Question:
フィールドがマップ形式の場合に、キーを指定して値を取得する。

@param key マップキーの値
@param targetObj オブジェクト（インスタンス）
@return マップの値
@throws IllegalArgumentException {@literal targetObj == null.}
@throws IllegalStateException {@literal フィールドのタイプがMap出ない場合}

@SuppressWarnings("unchecked")
    public Object getValueOfMap(final Object key, final Object targetObj) {
        ArgUtils.notNull(targetObj, "targetObj");

        if(!Map.class.isAssignableFrom(targetType)) {
            throw new IllegalStateException("this method cannot call Map. This target type is " + targetType.getName());
        }

        final Map<Object, Object> map = (Map<Object, Object>) getValue(targetObj);
        if(map == null) {
            return null;
        }

        return map.get(key);

    }

public static Object extract(Object target, String key, String delimeter)
    {
        if (target == null)
        {
            return target;
        }

        String keyHead = extractKeyHead(key, delimeter); // the return value of keyHead
        String keyTail = extractKeyTail(key, delimeter); // the return value of keyTail

        Object innerObject = null;

        // checking if the "Object: target" is Map or not
        if (target instanceof Map)
        {
            Map<?, ?> targetMap = (Map<?, ?>) target;
            innerObject = targetMap.get(keyHead); // get the object inside "keyHead"
        }
        else
        {
            BeanWrapperImpl baseWapper = new BeanWrapperImpl(target); // this is the reflection for getting the field value.
            innerObject = baseWapper.getPropertyValue(keyHead); // get the value from the field if the "keyHead" is not Map
        }

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

        if (StringUtils.isEmpty(keyTail) == true)
        {
            return innerObject;
        }
        else
        {
            return extract(innerObject, keyTail, delimeter); // recursive method for calling self function again.
        }
    }

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


Question: // SetCiphertext sets the Ciphertext field's value.

func (s *PasswordData) SetCiphertext(v string) *PasswordData {
	s.Ciphertext = &v
	return s
}

def get_encoder_settings(self):
        """"""

        if self.lame_header is None:
            return u""
        return self.lame_header.guess_settings(*self.lame_version)

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


Question: return forms for a var matching anything

function varMatchingAny(varnameAtom) {
  return sl.list(sl.atom("::", {token: varnameAtom}), varnameAtom, sl.str("any"));
}

public void setReturnType(String type) {
		if (!Strings.isEmpty(type)
				&& !Objects.equals("void", type)
				&& !Objects.equals(Void.class.getName(), type)) {
			this.sarlAction.setReturnType(newTypeRef(container, type));
		} else {
			this.sarlAction.setReturnType(null);
		}
	}

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


Question:
Multiply two complex numbers, in-place

@param c      other complex number
@param result complex number where product is stored
@return same as result

public ComplexDouble muli(ComplexDouble c, ComplexDouble result) {
    double newR = r * c.r - i * c.i;
    double newI = r * c.i + i * c.r;
    result.r = newR;
    result.i = newI;
    return result;
  }

protected function buildInsertQuery(SQLInsert $query, array &$parameters)
    {
        $nl = $this->getSeparator();
        $into = $query->getInto();

        // Column identifiers
        $columns = $query->getColumns();
        $sql = "INSERT INTO {$into}{$nl}(" . implode(', ', $columns) . ")";

        // Values
        $sql .= "{$nl}VALUES";

        // Build all rows
        $rowParts = array();
        foreach ($query->getRows() as $row) {
            // Build all columns in this row
            $assignments = $row->getAssignments();
            // Join SET components together, considering parameters
            $parts = array();
            foreach ($columns as $column) {
                // Check if this column has a value for this row
                if (isset($assignments[$column])) {
                    // Assigment is a single item array, expand with a loop here
                    foreach ($assignments[$column] as $assignmentSQL => $assignmentParameters) {
                        $parts[] = $assignmentSQL;
                        $parameters = array_merge($parameters, $assignmentParameters);
                        break;
                    }
                } else {
                    // This row is missing a value for a column used by another row
                    $parts[] = '?';
                    $parameters[] = null;
                }
            }
            $rowParts[] = '(' . implode(', ', $parts) . ')';
        }
        $sql .= $nl . implode(",$nl", $rowParts);

        return $sql;
    }

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


Question: (this: Trie, path: Path) => Value?

function get(path) {
  return splitPath(path).concat('@').reduce(function (t, segment) {
    return t ? t[segment]
             : undefined
  }, this)
}

@SuppressWarnings({"unchecked", "PMD.AvoidInstantiatingObjectsInLoops"})
    private void bindValuePaths() {
        for (ConfigPath item : tree.getPaths()) {
            toValue(
                    bind(Key.get(item.getDeclaredTypeWithGenerics(), new ConfigImpl(item.getPath()))),
                    item.getValue());
        }
    }

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


Question: // SetTriremeAction returns the TriremeAction

func (p *PUPolicy) SetTriremeAction(action PUAction) {
	p.Lock()
	defer p.Unlock()

	p.triremeAction = action
}

def register_actions(self, shortcut_manager):

        shortcut_manager.add_callback_for_action("delete", self.remove_action_callback)
        shortcut_manager.add_callback_for_action("add", self.add_action_callback)
        shortcut_manager.add_callback_for_action("copy", self.copy_action_callback)
        shortcut_manager.add_callback_for_action("cut", self.cut_action_callback)
        shortcut_manager.add_callback_for_action("paste", self.paste_action_callback)

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


Question: // ProcessMetric takes a Metric and samples it

func (w *Worker) ProcessMetric(m *samplers.UDPMetric) {
	w.mutex.Lock()
	defer w.mutex.Unlock()
	w.processed++
	w.wm.Upsert(m.MetricKey, m.Scope, m.Tags)

	switch m.Type {
	case counterTypeName:
		if m.Scope == samplers.GlobalOnly {
			w.wm.globalCounters[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.counters[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case gaugeTypeName:
		if m.Scope == samplers.GlobalOnly {
			w.wm.globalGauges[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.gauges[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case histogramTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localHistograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else if m.Scope == samplers.GlobalOnly {
			w.wm.globalHistograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.histograms[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case setTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localSets[m.MetricKey].Sample(m.Value.(string), m.SampleRate)
		} else {
			w.wm.sets[m.MetricKey].Sample(m.Value.(string), m.SampleRate)
		}
	case timerTypeName:
		if m.Scope == samplers.LocalOnly {
			w.wm.localTimers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else if m.Scope == samplers.GlobalOnly {
			w.wm.globalTimers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		} else {
			w.wm.timers[m.MetricKey].Sample(m.Value.(float64), m.SampleRate)
		}
	case statusTypeName:
		v := float64(m.Value.(ssf.SSFSample_Status))
		w.wm.localStatusChecks[m.MetricKey].Sample(v, m.SampleRate, m.Message, m.HostName)
	default:
		log.WithField("type", m.Type).Error("Unknown metric type for processing")
	}
}

public function process(ContainerBuilder $container)
    {
        $this->container = $container;
        $this->buildReader();
        $this->buildUseCaseProxies();
    }

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


Question:
Compiles a LESS or SASS file to a corresponding CSS file

@param absolutePath The absolute path to the file

public static void preprocess(String absolutePath) {
        if (absolutePath == null) {
            return;
        }

        if (config == null) {
            System.setProperty(Key.APPLICATION_CONFIG.toString(), basePath + Default.CONFIG_PATH.toString());
            config = new Config();
        }

        if (config.isApplicationPreprocessLess() && absolutePath.endsWith(LESS)) {
            lessify(new File(absolutePath));
        } else if (config.isApplicationPreprocessSass() && absolutePath.endsWith(SASS)) {
            sassify(new File(absolutePath));
        }
    }

def create_stylesheets
      template 'stylesheets/myg.scss', "#{stylesheets_dir}/myg.scss"
      template 'stylesheets/variables/_action-button.scss',
               "#{stylesheets_dir}/variables/_action-button.scss"
      template 'stylesheets/variables/_animate.scss',
               "#{stylesheets_dir}/variables/_animate.scss"
      template 'stylesheets/variables/_base.scss',
               "#{stylesheets_dir}/variables/_base.scss"
      template 'stylesheets/variables/_font.scss',
               "#{stylesheets_dir}/variables/_font.scss"
      template 'stylesheets/variables/_footer.scss',
               "#{stylesheets_dir}/variables/_footer.scss"
      template 'stylesheets/variables/_grid.scss',
               "#{stylesheets_dir}/variables/_grid.scss"
      template 'stylesheets/variables/_layout.scss',
               "#{stylesheets_dir}/variables/_layout.scss"
      template 'stylesheets/variables/_spacing.scss',
               "#{stylesheets_dir}/variables/_spacing.scss"
      template 'stylesheets/variables/_text.scss',
               "#{stylesheets_dir}/variables/_text.scss"
      template 'stylesheets/variables/_theme.scss',
               "#{stylesheets_dir}/variables/_theme.scss"
      template 'stylesheets/theme/theme.scss',
               "#{stylesheets_dir}/theme/theme.scss"
      template 'stylesheets/theme/_custom.scss',
               "#{stylesheets_dir}/theme/_custom.scss"
    end

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


Question:
Get the binary type for the given value type.

@param type The type to check.
@return The binary type ID.

public static byte forType(@Nonnull PType type) {
        switch (type) {
            case VOID: return VOID;
            case BOOL: return BOOL;
            case BYTE: return BYTE;
            case I16: return I16;
            case I32: return I32;
            case I64: return I64;
            case DOUBLE: return DOUBLE;
            case STRING: return STRING;
            case BINARY: return STRING;
            case ENUM: return I32;
            case MAP: return MAP;
            case SET: return SET;
            case LIST: return LIST;
            case MESSAGE: return STRUCT;
            default: throw new IllegalArgumentException("Unknown binary type for " + type.toString());
        }
    }

@Nonnull
	public static <T1, T2> LToIntBiFunction<T1, T2> toIntBiFunctionFrom(Consumer<LToIntBiFunctionBuilder<T1, T2>> buildingFunction) {
		LToIntBiFunctionBuilder builder = new LToIntBiFunctionBuilder();
		buildingFunction.accept(builder);
		return builder.build();
	}

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


Question: Add personal package archive from a file list.

def add_ppas_from_file(file_name, update=True):
    """"""

    for ppa in _read_lines_from_file(file_name):
        add_ppa(ppa, update=False)
    if update:
        update_apt_sources()

func (r Virtual_Guest_Block_Device_Template_Group) CreatePublicArchiveTransaction(groupName *string, summary *string, note *string, locations []datatypes.Location) (resp int, err error) {
	params := []interface{}{
		groupName,
		summary,
		note,
		locations,
	}
	err = r.Session.DoRequest("SoftLayer_Virtual_Guest_Block_Device_Template_Group", "createPublicArchiveTransaction", params, &r.Options, &resp)
	return
}

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


Question:
Get double array double [ ].

@param array the array
@return the double [ ]

public static double[] getDoubleArray(@javax.annotation.Nonnull final JsonArray array) {
    return IntStream.range(0, array.size()).mapToDouble(i -> array.get(i).getAsDouble()).toArray();
  }

public static Type getReturnType(final String methodDescriptor) {
    // Skip the first character, which is always a '('.
    int currentOffset = 1;
    // Skip the argument types, one at a each loop iteration.
    while (methodDescriptor.charAt(currentOffset) != ')') {
      while (methodDescriptor.charAt(currentOffset) == '[') {
        currentOffset++;
      }
      if (methodDescriptor.charAt(currentOffset++) == 'L') {
        while (methodDescriptor.charAt(currentOffset++) != ';') {
          // Skip the argument descriptor content.
        }
      }
    }
    return getType(methodDescriptor, currentOffset + 1, methodDescriptor.length());
  }

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


Question:
Shortcut for safely reading environment variable.

    :param key: Environment var key.
    :param default:
        Return default value if environment var not found by given key. By
        default: ``None``

def from_env(key: str, default: T = None) -> Union[str, Optional[T]]:

    return os.getenv(key, default)

public function fire()
    {
        $OUTPUT = [];
        $CHANGES = [];

        $fileUser = base_path('.env');
        if (file_exists($fileUser)) {
            $autodetect = ini_get('auto_detect_line_endings');
            ini_set('auto_detect_line_endings', '1');
            $lines = file($fileUser, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            ini_set('auto_detect_line_endings', $autodetect);
            foreach ($lines as $line) {
                $line = explode('=', $line, 2);
                if (count($line) == 2) {
                    $OUTPUT[$line[0]] = $line[1];
                }
            }
        }

        $file = base_path('.env.example');
        if (! file_exists($file)) {
            $this->error('.env.example don\'t exists');

            return;
        }
        $autodetect = ini_get('auto_detect_line_endings');
        ini_set('auto_detect_line_endings', '1');
        $lines = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        ini_set('auto_detect_line_endings', $autodetect);

        $values = [];
        foreach ($lines as $line) {
            $line = explode('=', $line, 2);
            if (count($line) == 2) {
                $values[$line[0]] = $line[1];
            }
        }

        foreach ($values as $key => $value) {
            if (preg_match('/^\\(([^\\)]+)\\)({([^\\}]+)})?$/us', $value, $matches)) {
                if (! isset($OUTPUT[$key]) || $this->option('overwrite') && $this->confirm('Do you want to overwrite existing value of '.strtoupper($key).' = '.$OUTPUT[$key].'?', false)) {
                    $choice = '';
                    if (isset($matches[3]) && $matches[3] != '') {
                        $defaults = explode('|', $matches[3]);
                        $default = null;
                        foreach ($defaults as $d) {
                            $rule = [];
                            $tmp = explode(':', $d);
                            $rule['value'] = $tmp[1];
                            $tmp = explode('=', $tmp[0]);
                            $rule['var'] = $tmp[0];
                            $rule['is'] = $tmp[1];

                            if ($OUTPUT[$rule['var']] == $rule['is']) {
                                $default = $rule['value'];
                            }
                        }
                        if (! is_null($default)) {
                            if (! $this->option('defaults') || $this->confirm('Do you want to use default value for '.strtoupper($key).' = '.$default.'?', true)) {
                                $choice = $default;
                                $OUTPUT[$key] = $choice;
                                $CHANGES[$key] = $choice;
                            }
                        }
                    }
                    if ($choice == '') {
                        $choices = explode('|', $matches[1]);
                        $choices = array_combine(range(1, count($choices)), array_values($choices));
                        if (count($choices) == 1) {
                            $choice = $choices[1];
                        } else {
                            $choice = $this->choice($key, $choices);
                        }
                        switch ($choice) {
                            case 'PASSWORD':
                                $choice = $this->secret('Enter value for '.strtoupper($key).':');
                                break;
                            case 'TEXT':
                                $choice = $this->ask('Enter value for '.strtoupper($key).':');
                                break;
                        }
                        $OUTPUT[$key] = $choice;
                        $CHANGES[$key] = $choice;
                    }
                }
            } else {
                if (! isset($OUTPUT[$key])) {
                    $OUTPUT[$key] = $value;
                    $CHANGES[$key] = $value;
                }
            }
        }

        if (count($CHANGES) > 0) {
            $GROUPS = [];

            foreach ($OUTPUT as $key => $val) {
                $tmp = explode('_', $key);
                if (count($tmp) == 1) {
                    $GROUPS['OTHER'][$key] = $val;
                } else {
                    $GROUPS[$tmp[0]][$key] = $val;
                }
            }
            $TABLE = [];
            $OUTPUT = [];
            foreach ($GROUPS as $name => $GROUP) {
                $o = [];
                $o[] = '# '.$name;
                foreach ($GROUP as $key => $val) {
                    $o[] = $key.'='.$val;
                    $TABLE[] = [$name, $key, $val];
                }
                $OUTPUT[] = implode(PHP_EOL, $o);
            }
            $OUTPUT = implode("\n\n", $OUTPUT);

            $this->info($OUTPUT);
            // DEBUG: $this->table(['Group','Key','Value'],$TABLE);
            if ($this->confirm('Do you want to write above content to .env file?', true)) {
                file_put_contents($fileUser, $OUTPUT);
                $this->info('File written.');
            }
        } else {
            $this->info('There is nothing to write.');
        }
    }

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


Question:
Checks that cache for feature exists and is fresh.

@param string  $path      Feature path
@param integer $timestamp The last time feature was updated

@return Boolean

public function isFresh($path, $timestamp)
    {
        $cachePath = $this->getCachePathFor($path);

        if (!file_exists($cachePath)) {
            return false;
        }

        return filemtime($cachePath) > $timestamp;
    }

def parse_arguments():

    # define supported command line arguments
    parser = argparse.ArgumentParser(description='Common interface for the ' +
                                                 'WakaTime api.')
    parser.add_argument('--entity', dest='entity', metavar='FILE',
                        action=FileAction,
                        help='Absolute path to file for the heartbeat. Can ' +
                             'also be a url, domain or app when ' +
                             '--entity-type is not file.')
    parser.add_argument('--file', dest='file', action=FileAction,
                        help=argparse.SUPPRESS)
    parser.add_argument('--key', dest='key', action=StoreWithoutQuotes,
                        help='Your wakatime api key; uses api_key from ' +
                             '~/.wakatime.cfg by default.')
    parser.add_argument('--write', dest='is_write', action='store_true',
                        help='When set, tells api this heartbeat was ' +
                             'triggered from writing to a file.')
    parser.add_argument('--plugin', dest='plugin', action=StoreWithoutQuotes,
                        help='Optional text editor plugin name and version ' +
                             'for User-Agent header.')
    parser.add_argument('--time', dest='timestamp', metavar='time',
                        type=float, action=StoreWithoutQuotes,
                        help='Optional floating-point unix epoch timestamp. ' +
                             'Uses current time by default.')
    parser.add_argument('--lineno', dest='lineno', action=StoreWithoutQuotes,
                        help='Optional line number. This is the current ' +
                             'line being edited.')
    parser.add_argument('--cursorpos', dest='cursorpos',
                        action=StoreWithoutQuotes,
                        help='Optional cursor position in the current file.')
    parser.add_argument('--entity-type', dest='entity_type',
                        action=StoreWithoutQuotes,
                        help='Entity type for this heartbeat. Can be ' +
                             '"file", "domain" or "app". Defaults to "file".')
    parser.add_argument('--category', dest='category',
                        action=StoreWithoutQuotes,
                        help='Category of this heartbeat activity. Can be ' +
                             '"coding", "building", "indexing", ' +
                             '"debugging", "running tests", ' +
                             '"writing tests", "manual testing", ' +
                             '"code reviewing", "browsing", or "designing". ' +
                             'Defaults to "coding".')
    parser.add_argument('--proxy', dest='proxy', action=StoreWithoutQuotes,
                        help='Optional proxy configuration. Supports HTTPS '+
                             'and SOCKS proxies. For example: '+
                             'https://user:pass@host:port or '+
                             'socks5://user:pass@host:port or ' +
                             'domain\\user:pass')
    parser.add_argument('--no-ssl-verify', dest='nosslverify',
                        action='store_true',
                        help='Disables SSL certificate verification for HTTPS '+
                             'requests. By default, SSL certificates are ' +
                             'verified.')
    parser.add_argument('--ssl-certs-file', dest='ssl_certs_file',
                        action=StoreWithoutQuotes,
                        help='Override the bundled Python Requests CA certs ' +
                             'file. By default, uses certifi for ca certs.')
    parser.add_argument('--project', dest='project', action=StoreWithoutQuotes,
                        help='Optional project name.')
    parser.add_argument('--alternate-project', dest='alternate_project',
                        action=StoreWithoutQuotes,
                        help='Optional alternate project name. ' +
                             'Auto-discovered project takes priority.')
    parser.add_argument('--alternate-language', dest='alternate_language',
                        action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--language', dest='language',
                        action=StoreWithoutQuotes,
                        help='Optional language name. If valid, takes ' +
                             'priority over auto-detected language.')
    parser.add_argument('--local-file', dest='local_file', metavar='FILE',
                        action=FileAction,
                        help='Absolute path to local file for the ' +
                             'heartbeat. When --entity is a remote file, ' +
                             'this local file will be used for stats and ' +
                             'just the value of --entity sent with heartbeat.')
    parser.add_argument('--hostname', dest='hostname',
                        action=StoreWithoutQuotes,
                        help='Hostname of current machine.')
    parser.add_argument('--disable-offline', dest='offline',
                        action='store_false',
                        help='Disables offline time logging instead of ' +
                             'queuing logged time.')
    parser.add_argument('--disableoffline', dest='offline_deprecated',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hide-file-names', dest='hide_file_names',
                        action='store_true',
                        help='Obfuscate filenames. Will not send file names ' +
                             'to api.')
    parser.add_argument('--hide-filenames', dest='hide_filenames',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hidefilenames', dest='hidefilenames',
                        action='store_true',
                        help=argparse.SUPPRESS)
    parser.add_argument('--hide-project-names', dest='hide_project_names',
                        action='store_true',
                        help='Obfuscate project names. When a project ' +
                             'folder is detected instead of using the ' +
                             'folder name as the project, a ' +
                             '.wakatime-project file is created with a ' +
                             'random project name.')
    parser.add_argument('--exclude', dest='exclude', action='append',
                        help='Filename patterns to exclude from logging. ' +
                             'POSIX regex syntax. Can be used more than once.')
    parser.add_argument('--exclude-unknown-project',
                        dest='exclude_unknown_project', action='store_true',
                        help='When set, any activity where the project ' +
                             'cannot be detected will be ignored.')
    parser.add_argument('--include', dest='include', action='append',
                        help='Filename patterns to log. When used in ' +
                             'combination with --exclude, files matching ' +
                             'include will still be logged. POSIX regex ' +
                             'syntax. Can be used more than once.')
    parser.add_argument('--include-only-with-project-file',
                        dest='include_only_with_project_file',
                        action='store_true',
                        help='Disables tracking folders unless they contain ' +
                             'a .wakatime-project file. Defaults to false.')
    parser.add_argument('--ignore', dest='ignore', action='append',
                        help=argparse.SUPPRESS)
    parser.add_argument('--extra-heartbeats', dest='extra_heartbeats',
                        action='store_true',
                        help='Reads extra heartbeats from STDIN as a JSON ' +
                             'array until EOF.')
    parser.add_argument('--log-file', dest='log_file',
                        action=StoreWithoutQuotes,
                        help='Defaults to ~/.wakatime.log.')
    parser.add_argument('--logfile', dest='logfile', action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--api-url', dest='api_url', action=StoreWithoutQuotes,
                        help='Heartbeats api url. For debugging with a ' +
                             'local server.')
    parser.add_argument('--apiurl', dest='apiurl', action=StoreWithoutQuotes,
                        help=argparse.SUPPRESS)
    parser.add_argument('--timeout', dest='timeout', type=int,
                        action=StoreWithoutQuotes,
                        help='Number of seconds to wait when sending ' +
                             'heartbeats to api. Defaults to 60 seconds.')
    parser.add_argument('--sync-offline-activity',
                        dest='sync_offline_activity',
                        action=StoreWithoutQuotes,
                        help='Amount of offline activity to sync from your ' +
                             'local ~/.wakatime.db sqlite3 file to your ' +
                             'WakaTime Dashboard before exiting. Can be ' +
                             '"none" or a positive integer number. Defaults ' +
                             'to 5, meaning for every heartbeat sent while ' +
                             'online 5 offline heartbeats are synced. Can ' +
                             'be used without --entity to only sync offline ' +
                             'activity without generating new heartbeats.')
    parser.add_argument('--config', dest='config', action=StoreWithoutQuotes,
                        help='Defaults to ~/.wakatime.cfg.')
    parser.add_argument('--verbose', dest='verbose', action='store_true',
                        help='Turns on debug messages in log file.')
    parser.add_argument('--version', action='version', version=__version__)

    # parse command line arguments
    args = parser.parse_args()

    # use current unix epoch timestamp by default
    if not args.timestamp:
        args.timestamp = time.time()

    # parse ~/.wakatime.cfg file
    configs = parseConfigFile(args.config)

    # update args from configs
    if not args.hostname:
        if configs.has_option('settings', 'hostname'):
            args.hostname = configs.get('settings', 'hostname')
    if not args.key:
        default_key = None
        if configs.has_option('settings', 'api_key'):
            default_key = configs.get('settings', 'api_key')
        elif configs.has_option('settings', 'apikey'):
            default_key = configs.get('settings', 'apikey')
        if default_key:
            args.key = default_key
        else:
            try:
                parser.error('Missing api key. Find your api key from wakatime.com/settings/api-key.')
            except SystemExit:
                raise SystemExit(AUTH_ERROR)

    is_valid = not not re.match(r'^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$', args.key, re.I)
    if not is_valid:
        try:
            parser.error('Invalid api key. Find your api key from wakatime.com/settings/api-key.')
        except SystemExit:
            raise SystemExit(AUTH_ERROR)

    if not args.entity:
        if args.file:
            args.entity = args.file
        elif not args.sync_offline_activity or args.sync_offline_activity == 'none':
            parser.error('argument --entity is required')

    if not args.sync_offline_activity:
        args.sync_offline_activity = DEFAULT_SYNC_OFFLINE_ACTIVITY
    if args.sync_offline_activity == 'none':
        args.sync_offline_activity = 0
    try:
        args.sync_offline_activity = int(args.sync_offline_activity)
        if args.sync_offline_activity < 0:
            raise Exception('Error')
    except:
        parser.error('argument --sync-offline-activity must be "none" or an integer number')

    if not args.language and args.alternate_language:
        args.language = args.alternate_language

    if not args.exclude:
        args.exclude = []
    if configs.has_option('settings', 'ignore'):
        try:
            for pattern in configs.get('settings', 'ignore').split("\n"):
                if pattern.strip() != '':
                    args.exclude.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if configs.has_option('settings', 'exclude'):
        try:
            for pattern in configs.get('settings', 'exclude').split("\n"):
                if pattern.strip() != '':
                    args.exclude.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if not args.include_only_with_project_file and configs.has_option('settings', 'include_only_with_project_file'):
        args.include_only_with_project_file = configs.get('settings', 'include_only_with_project_file') == 'true'
    if not args.include:
        args.include = []
    if configs.has_option('settings', 'include'):
        try:
            for pattern in configs.get('settings', 'include').split("\n"):
                if pattern.strip() != '':
                    args.include.append(pattern)
        except TypeError:  # pragma: nocover
            pass
    if not args.exclude_unknown_project and configs.has_option('settings', 'exclude_unknown_project'):
        args.exclude_unknown_project = configs.getboolean('settings', 'exclude_unknown_project')
    boolean_or_list('hide_file_names', args, configs, alternative_names=['hide_filenames', 'hidefilenames'])
    boolean_or_list('hide_project_names', args, configs, alternative_names=['hide_projectnames', 'hideprojectnames'])
    if args.offline_deprecated:
        args.offline = False
    if args.offline and configs.has_option('settings', 'offline'):
        args.offline = configs.getboolean('settings', 'offline')
    if not args.proxy and configs.has_option('settings', 'proxy'):
        args.proxy = configs.get('settings', 'proxy')
    if args.proxy:
        pattern = r'^((https?|socks5)://)?([^:@]+(:([^:@])+)?@)?[^:]+(:\d+)?$'
        if '\\' in args.proxy:
            pattern = r'^.*\\.+$'
        is_valid = not not re.match(pattern, args.proxy, re.I)
        if not is_valid:
            parser.error('Invalid proxy. Must be in format ' +
                         'https://user:pass@host:port or ' +
                         'socks5://user:pass@host:port or ' +
                         'domain\\user:pass.')
    if configs.has_option('settings', 'no_ssl_verify'):
        args.nosslverify = configs.getboolean('settings', 'no_ssl_verify')
    if configs.has_option('settings', 'ssl_certs_file'):
        args.ssl_certs_file = configs.get('settings', 'ssl_certs_file')
    if not args.verbose and configs.has_option('settings', 'verbose'):
        args.verbose = configs.getboolean('settings', 'verbose')
    if not args.verbose and configs.has_option('settings', 'debug'):
        args.verbose = configs.getboolean('settings', 'debug')
    if not args.log_file and args.logfile:
        args.log_file = args.logfile
    if not args.log_file and configs.has_option('settings', 'log_file'):
        args.log_file = configs.get('settings', 'log_file')
    if not args.log_file and os.environ.get('WAKATIME_HOME'):
        home = os.environ.get('WAKATIME_HOME')
        args.log_file = os.path.join(os.path.expanduser(home), '.wakatime.log')
    if not args.api_url and args.apiurl:
        args.api_url = args.apiurl
    if not args.api_url and configs.has_option('settings', 'api_url'):
        args.api_url = configs.get('settings', 'api_url')
    if not args.timeout and configs.has_option('settings', 'timeout'):
        try:
            args.timeout = int(configs.get('settings', 'timeout'))
        except ValueError:
            print(traceback.format_exc())

    return args, configs

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


Question:
// Hello is called via the RPC server interface by the remote client.
// It in turn delegates the work to the passed in Provisionee interface,
// calling HandleHello()

func (p *provisionee) Hello(ctx context.Context, arg keybase1.HelloArg) (res keybase1.HelloRes, err error) {
	close(p.start)
	res, err = p.arg.Provisionee.HandleHello(ctx, arg)
	if err != nil {
		p.done <- err
	}
	return res, err
}

def delete_ptr_records(self, device, ip_address=None):

        device_type = self._resolve_device_type(device)
        href, svc_name = self._get_ptr_details(device, device_type)
        uri = "/rdns/%s?href=%s" % (svc_name, href)
        if ip_address:
            uri = "%s&ip=%s" % (uri, ip_address)
        resp, resp_body = self._async_call(uri, method="DELETE",
                has_response=False,
                error_class=exc.PTRRecordDeletionFailed)
        return resp_body.get("status") == "COMPLETED"

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


func CompareHRS(h1 int64, r1 int, s1 cstypes.RoundStepType, h2 int64, r2 int, s2 cstypes.RoundStepType) int {
	if h1 < h2 {
		return -1
	} else if h1 > h2 {
		return 1
	}
	if r1 < r2 {
		return -1
	} else if r1 > r2 {
		return 1
	}
	if s1 < s2 {
		return -1
	} else if s1 > s2 {
		return 1
	}
	return 0
}

@Override
    protected void paintComponent(java.awt.Graphics g) {
        if (!isInitialized()) {
            return;
        }

        final java.awt.Graphics2D G2 = (java.awt.Graphics2D) g.create();

        CENTER.setLocation(getGaugeBounds().getCenterX(), getGaugeBounds().getCenterX());

        G2.setRenderingHint(java.awt.RenderingHints.KEY_ANTIALIASING, java.awt.RenderingHints.VALUE_ANTIALIAS_ON);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_RENDERING, java.awt.RenderingHints.VALUE_RENDER_QUALITY);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_STROKE_CONTROL, java.awt.RenderingHints.VALUE_STROKE_NORMALIZE);
        G2.setRenderingHint(java.awt.RenderingHints.KEY_TEXT_ANTIALIASING, java.awt.RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        // Translate the coordinate system related to the insets
        G2.translate(getFramelessOffset().getX(), getFramelessOffset().getY());

        final java.awt.geom.AffineTransform OLD_TRANSFORM = G2.getTransform();
        final java.awt.Shape OLD_CLIP = G2.getClip();

        // Draw the horizon
        G2.setClip(CLIP);

        // Rotate around roll
        G2.rotate(-Math.toRadians(roll), CENTER.getX(), CENTER.getY());

        // Translate about dive
        G2.translate(0, -(pitch * pitchPixel) - getFramelessOffset().getY());

        // Draw horizon
        G2.drawImage(horizonImage, 0, (int) ((getHeight() - horizonImage.getHeight()) / 2.0), null);

        // Draw the scale and angle indicator
        G2.translate(-getFramelessOffset().getX(), (pitch * pitchPixel) + getFramelessOffset().getY());
        G2.drawImage(horizonForegroundImage, (int) (getWidth() * 0.5 - horizonForegroundImage.getWidth() / 2.0), (int) (getWidth() * 0.10747663551401869), null);

        G2.setTransform(OLD_TRANSFORM);
        G2.setClip(OLD_CLIP);

        // Draw combined background image
        G2.drawImage(bImage, 0, 0, null);

        // Draw combined foreground image
        G2.drawImage(fImage, 0, 0, null);

        if (!isEnabled()) {
            G2.drawImage(disabledImage, 0, 0, null);
        }

        G2.dispose();
    }

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


Question:
Send the response.

        If `error` is True, it will be sent as an error.

def send(self, value, error=False):

        if error:
            resp = [1, self._request_id, value, None]
        else:
            resp = [1, self._request_id, None, value]
        debug('sending response to request %d: %s', self._request_id, resp)
        self._msgpack_stream.send(resp)

def rm(self, filename):
        """"""
        command = """
            try:
                import os
            except ImportError:
                import uos as os
            os.remove('{0}')
        """.format(
            filename
        )
        self._pyboard.enter_raw_repl()
        try:
            out = self._pyboard.exec_(textwrap.dedent(command))
        except PyboardError as ex:
            message = ex.args[2].decode("utf-8")
            # Check if this is an OSError #2, i.e. file/directory doesn't exist
            # and rethrow it as something more descriptive.
            if message.find("OSError: [Errno 2] ENOENT") != -1:
                raise RuntimeError("No such file/directory: {0}".format(filename))
            # Check for OSError #13, the directory isn't empty.
            if message.find("OSError: [Errno 13] EACCES") != -1:
                raise RuntimeError("Directory is not empty: {0}".format(filename))
            else:
                raise ex
        self._pyboard.exit_raw_repl()

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


Question:
newTransport.

@param apitraryApi a {@link com.apitrary.api.ApitraryApi} object.
@param transportClazz a {@link java.lang.Class} object.
@return a {@link com.apitrary.api.transport.Transport} object.

public Transport newTransport(ApitraryApi apitraryApi, Class<Transport> transportClazz) {
		try {
			Transport transport = transportClazz.newInstance();
			transport.setApitraryApi(apitraryApi);
			return transport;
		} catch (IllegalAccessException e) {
			throw new ApiTransportException(e);
		} catch (InstantiationException e) {
			throw new ApiTransportException(e);
		}
	}

public void crop(String url, Type type) {
        setUrl(url);
        bind(url, () -> crop(type));
    }

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


Question: the function of getting parent (or super parent) tag name of the selected node

function detectElement(tags){

				var resultdetect=false, $node = getSelectedNode(), parentsTag;

				if($node)
				{
					$.each(tags, function(i, val){
						parentsTag = $node.prop('tagName').toLowerCase();

						if (parentsTag == val)
							resultdetect = true;
						else
						{
							$node.parents().each(function(){
								parentsTag = $(this).prop('tagName').toLowerCase();
								if (parentsTag == val)
									resultdetect = true;
							});
						}
					});

					return resultdetect;
				}
				else
					return false;
			}

public Selector visitSelector(CSSParser.SelectorContext ctx) {
        if (ctxHasErrorNode(ctx)) {
            statement_stack.peek().invalid = true;
            return null;
        }
        selector_stack.push(new selector_scope());
        cz.vutbr.web.css.Selector sel;
        logEnter("selector");
        selector_stack.peek().s = sel = (cz.vutbr.web.css.Selector) rf.createSelector().unlock();
        if (ctx.IDENT() != null || ctx.ASTERISK() != null) {
            cz.vutbr.web.css.Selector.ElementName en = rf.createElement(cz.vutbr.web.css.Selector.ElementName.WILDCARD);
            if (ctx.IDENT() != null) {
                en.setName(extractTextUnescaped(ctx.IDENT().getText()));
            }
            //log.debug("Adding element name: {}.", en.getName());
            selector_stack.peek().s.add(en);
        }
        for (CSSParser.SelpartContext selpartctx : ctx.selpart()) {
            visitSelpart(selpartctx);
        }

        logLeave("selector");
        selector_stack.pop();
        return sel;
    }

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