Question: // ListServiceUsageEventsByQuery lists all events matching the provided query.

func (c *Client) ListServiceUsageEventsByQuery(query url.Values) ([]ServiceUsageEvent, error) {
	var serviceUsageEvents []ServiceUsageEvent
	requestURL := fmt.Sprintf("/v2/service_usage_events?%s", query.Encode())
	for {
		var serviceUsageEventsResponse ServiceUsageEventsResponse
		r := c.NewRequest("GET", requestURL)
		resp, err := c.DoRequest(r)
		if err != nil {
			return nil, errors.Wrap(err, "error requesting events")
		}
		defer resp.Body.Close()
		if err := json.NewDecoder(resp.Body).Decode(&serviceUsageEventsResponse); err != nil {
			return nil, errors.Wrap(err, "error unmarshaling events")
		}
		for _, e := range serviceUsageEventsResponse.Resources {
			e.Entity.GUID = e.Meta.Guid
			e.Entity.CreatedAt = e.Meta.CreatedAt
			e.Entity.c = c
			serviceUsageEvents = append(serviceUsageEvents, e.Entity)
		}
		requestURL = serviceUsageEventsResponse.NextURL
		if requestURL == "" {
			break
		}
	}
	return serviceUsageEvents, nil
}

public function filter(array $phpNames)
    {
        $fileUseOccurances = array_flip(
            array_map(
                function ($useOccurance) {
                    return $useOccurance->name()->fullyQualifiedName();
                },
                array_filter(
                    $phpNames,
                    function ($occurance) {
                        return $occurance->name()->type() === PhpName::TYPE_USE;
                    }
                )
            )
        );

        return array_filter(
            $phpNames,
            function ($occurance) use ($fileUseOccurances) {
                return (
                    $occurance->name()->type() !== PhpName::TYPE_USAGE ||
                    !isset($fileUseOccurances[$occurance->name()->fullyQualifiedName()])
                );
            }
        );
    }

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


Question: // SetAuthenticationToken sets the AuthenticationToken field's value.

func (s *DescribeCommentsInput) SetAuthenticationToken(v string) *DescribeCommentsInput {
	s.AuthenticationToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question:
Adds Image Concepts to Image Data

@param array $data
@param array $concepts

@return array

public function addImageConcepts(array $data, array $concepts)
    {
        $data['concepts'] = [];

        foreach ($concepts as $concept) {
            $data['concepts'][] = [
                'id' => $concept->getId(),
                'value' => $concept->getValue(),
            ];
        }

        return $data;
    }

public function execute(TransactionData $transactionData, $argument = null)
    {
        foreach ($this->expectationBackup->listExpectations() as $expectation) {
            $this->expectationStorage->addExpectation($expectation);
        }
        $this->logger->debug('Pre-defined expectations are restored, scenarios and requests history are cleared.');

        $transactionData->setResponse(
            $transactionData->getResponse()->withStatus(200)
        );
    }

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


Question: return a single fixer found in the lib2to3 library

def get_single_fixer(fixname):
    ''''''
    fixer_dirname = fixer_dir.__path__[0]
    for name in sorted(os.listdir(fixer_dirname)):
        if (name.startswith("fix_") and name.endswith(".py")
            and fixname == name[4:-3]):
            return "lib2to3.fixes." + name[:-3]

def update_function_configuration(self, vpc_config):

        LOG.info('Updating configuration for lambda function: %s', self.app_name)

        try:
            self.lambda_client.update_function_configuration(
                Environment=self.lambda_environment,
                FunctionName=self.app_name,
                Runtime=self.runtime,
                Role=self.role_arn,
                Handler=self.handler,
                Description=self.description,
                Timeout=int(self.timeout),
                MemorySize=int(self.memory),
                VpcConfig=vpc_config)

            if self.concurrency_limit:
                self.lambda_client.put_function_concurrency(
                    FunctionName=self.app_name,
                    ReservedConcurrentExecutions=self.concurrency_limit
                )
            else:
                self.lambda_client.delete_function_concurrency(FunctionName=self.app_name)

        except boto3.exceptions.botocore.exceptions.ClientError as error:
            if 'CreateNetworkInterface' in error.response['Error']['Message']:
                message = '{0} is missing "ec2:CreateNetworkInterface"'.format(self.role_arn)
                LOG.debug(message)
                raise SystemExit(message)

            raise
        LOG.info('Updating Lambda function tags')

        lambda_arn = get_lambda_arn(self.app_name, self.env, self.region)
        self.lambda_client.tag_resource(Resource=lambda_arn, Tags={'app_group': self.group, 'app_name': self.app_name})

        LOG.info("Successfully updated Lambda configuration.")

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


Question:
Set the "everyWorkingDay" flag.
@param isEveryWorkingDay flag, indicating if the event should take place every working day.

public void setEveryWorkingDay(final boolean isEveryWorkingDay) {

        if (m_model.isEveryWorkingDay() != isEveryWorkingDay) {
            removeExceptionsOnChange(new Command() {

                public void execute() {

                    m_model.setEveryWorkingDay(Boolean.valueOf(isEveryWorkingDay));
                    m_model.setInterval(getPatternDefaultValues().getInterval());
                    onValueChange();
                }
            });
        }
    }

def schedule_cycles(minutes,location_id,conditions = {})

			products = Auth.configuration.product_class.constantize.all if conditions.blank?

			products = Auth.configuration.product_class.constantize.where(conditions) if !conditions.blank?

			minutes.keys.each do |epoch|

				products.each do |product|

					all_cycles_valid = true
					product.cycles.each do |cycle|

						all_cycles_valid = cycle.requirements_satisfied(epoch + cycle.time_since_prev_cycle.minutes*60,location_id)

					end

					## just because the cycles are valid, it means we have workers, but how many?
					## that also has to be returned by the cycle validity statements

					if all_cycles_valid == true
						cycle_chain = []
						product.cycles.each do |cycle|
							epoch_at_which_to_add = epoch + cycle.time_since_prev_cycle.minutes*60
							cycle_to_add = cycle.dup
							cycle_to_add.start_time = epoch_at_which_to_add
							cycle_to_add.end_time = cycle_to_add.start_time + cycle_to_add.duration
							cycle_to_add.cycle_chain = cycle_chain
							if minutes[epoch_at_which_to_add]

								add_to_previous_rolling_n_minutes(minutes,epoch_at_which_to_add,cycle_to_add)

								minutes[epoch_at_which_to_add].cycles << cycle_to_add

								cycle_chain << cycle_to_add.id.to_s
							else
								#raise "necessary minute not in range."
							end
						end
					end
				end
			end
			minutes
		end

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


Question: Query for TextLogErrorMatches identical to matches of the given TextLogError.

def precise_matcher(text_log_error):
    """"""
    failure_line = text_log_error.metadata.failure_line
    logger.debug("Looking for test match in failure %d", failure_line.id)

    if failure_line.action != "test_result" or failure_line.message is None:
        return

    f = {
        'text_log_error___metadata__failure_line__action': 'test_result',
        'text_log_error___metadata__failure_line__test': failure_line.test,
        'text_log_error___metadata__failure_line__subtest': failure_line.subtest,
        'text_log_error___metadata__failure_line__status': failure_line.status,
        'text_log_error___metadata__failure_line__expected': failure_line.expected,
        'text_log_error___metadata__failure_line__message': failure_line.message
    }
    qwargs = (
        Q(text_log_error___metadata__best_classification=None)
        & (Q(text_log_error___metadata__best_is_verified=True)
           | Q(text_log_error__step__job=text_log_error.step.job))
    )
    qs = (TextLogErrorMatch.objects.filter(**f)
                                   .exclude(qwargs)
                                   .order_by('-score', '-classified_failure'))

    if not qs:
        return

    # chunk through the QuerySet because it could potentially be very large
    # time bound each call to the scoring function to avoid job timeouts
    # returns an iterable of (score, classified_failure_id) tuples
    chunks = chunked_qs_reverse(qs, chunk_size=20000)
    return chain.from_iterable(time_boxed(score_matches, chunks, time_budget=500))

def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id):
    '''  '''
    try:
        frame = dbg.find_frame(thread_id, frame_id)
        if frame is not None:
            code = frame.f_code
            xml = "<xml>"
            if hasattr(code, 'co_lnotab'):
                lineno = code.co_firstlineno
                lnotab = code.co_lnotab
                for i in itertools.islice(lnotab, 1, len(lnotab), 2):
                    if isinstance(i, int):
                        lineno = lineno + i
                    else:
                        # in python 2 elements in co_lnotab are of type str
                        lineno = lineno + ord(i)
                    xml += "<line>%d</line>" % (lineno,)
            else:
                xml += "<line>%d</line>" % (frame.f_lineno,)
            del frame
            xml += "</xml>"
            cmd = dbg.cmd_factory.make_get_next_statement_targets_message(seq, xml)
            dbg.writer.add_command(cmd)
        else:
            cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
            dbg.writer.add_command(cmd)
    except:
        cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id))
        dbg.writer.add_command(cmd)

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


Question:
Get a line between two points in a shape

@param shape The shape
@param sx The x coordinate of the start point
@param sy The y coordinate of the start point
@param e The index of the end point
@return The line between the two points

public Line getLine(Shape shape, float sx, float sy, int e) {
		float[] end = shape.getPoint(e);

		Line line = new Line(sx,sy,end[0],end[1]);
		return line;
	}

function toGradientData(v1, v2, v3, v4, v5) {
    var startColor, endColor, type, rotation, spread, d;
    var data = {};

    if (arguments.length === 1) { // The argument is a dictionary or undefined.
        d = v1 || {};
        startColor = d.startColor;
        endColor = d.endColor;
        type = d.type;
        rotation = d.rotation;
        spread = d.spread;
    } else if (arguments.length >= 2) { // The first two arguments are a start color and an end color.
        startColor = v1;
        endColor = v2;
        type = 'linear';
        rotation = 0;
        spread = 0;
        if (arguments.length === 3) {
            if (typeof v3 === 'string') { // The type can be either linear or radial.
                type = v3;
            } else if (typeof v3 === 'number') { // The type is implicitly linear and the third argument is the rotation angle.
                rotation = v3;
            }
        } else if (arguments.length === 4) {
            if (typeof v3 === 'number') { // The type is implicitly linear and the third/forth arguments are the rotation angle and gradient spread.
                rotation = v3;
                spread = v4;
            } else if (v3 === 'linear') { // The type is explicitly linear and the forth argument is the rotation angle.
                rotation = v4;
            } else if (v3 === 'radial') { // The type is explicitly radial and the forth argument is the gradient spread.
                type = v3;
                spread = v4;
            } else {
                throw new Error('Wrong argument provided: ' + v3);
            }
        } else if (arguments.length === 5) { // Type, rotation (unused in case of radial type gradient), and gradient spread.
            type = v3;
            rotation = v4;
            spread = v5;
        }
    }

    if (!startColor && startColor !== 0) {
        throw new Error('No startColor was given.');
    }
    if (!endColor && endColor !== 0) {
        throw new Error('No endColor was given.');
    }

    try {
        data.startColor = toColor(startColor);
    } catch (e1) {
        throw new Error('startColor is not a valid color: ' + startColor);
    }

    try {
        data.endColor = toColor(endColor);
    } catch (e2) {
        throw new Error('endColor is not a valid color: ' + endColor);
    }

    if (type === undefined) {
        type = 'linear';
    }
    if (type !== 'linear' && type !== 'radial') {
        throw new Error('Unknown gradient type: ' + type);
    }

    data.type = type;

    if (spread === undefined) {
        spread = 0;
    }
    if (typeof spread !== 'number') {
        throw new Error('Spread value is not a number: ' + spread);
    }

    if (type === 'linear') {
        if (rotation === undefined) {
            rotation = 0;
        }
        if (typeof rotation !== 'number') {
            throw new Error('Rotation value is not a number: ' + rotation);
        }
        data.rotation = rotation;
    }

    data.spread = clamp(spread, 0, 0.99);

    return data;
}

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


Question:
Returns a list of matching points on the first image.

@return The list of matching points on the first image.

public List<Point> getPoints1() {
        verifyPropertyPresence(POINTS1);
        //noinspection unchecked
        return ((List<Map<String, Object>>) getCommandResult().get(POINTS1)).stream()
                .map(ComparisonResult::mapToPoint)
                .collect(Collectors.toList());
    }

def get_func_lno(self, funcname):
        """"""

        class FuncLineno(ast.NodeVisitor):
            def __init__(self):
                self.clss = []

            def generic_visit(self, node):
                for child in ast.iter_child_nodes(node):
                    for item in self.visit(child):
                        yield item

            def visit_ClassDef(self, node):
                self.clss.append(node.name)
                for item in self.generic_visit(node):
                    yield item
                self.clss.pop()

            def visit_FunctionDef(self, node):
                # Only allow non nested function definitions.
                name = '.'.join(itertools.chain(self.clss, [node.name]))
                yield name, node.lineno

        if self.functions_firstlno is None:
            self.functions_firstlno = {}
            for name, lineno in FuncLineno().visit(self.node):
                if (name not in self.functions_firstlno or
                        self.functions_firstlno[name] < lineno):
                    self.functions_firstlno[name] = lineno
        try:
            return self.functions_firstlno[funcname]
        except KeyError:
            raise BdbSourceError('{}: function "{}" not found.'.format(
                self.filename, funcname))

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


Question:
Imports a set of classes from a given module.

    Usage::

        get_classes('forum.models', ['Forum', 'ForumReadTrack', ])

def get_classes(module_label, classnames):

    app_label = module_label.split('.')[0]

    app_module_path = _get_app_module_path(module_label)
    if not app_module_path:
        raise AppNotFoundError('No app found matching \'{}\''.format(module_label))

    # Determines the full module path by appending the module label
    # to the base package path of the considered application.
    module_path = app_module_path
    if '.' in app_module_path:
        base_package = app_module_path.rsplit('.' + app_label, 1)[0]
        module_path = '{}.{}'.format(base_package, module_label)

    # Try to import this module from the related app that is specified
    # in the Django settings.
    local_imported_module = _import_module(module_path, classnames)

    # If the module we tried to import is not located inside the machina
    # vanilla apps, try to import it from the corresponding machina app.
    machina_imported_module = None
    if not app_module_path.startswith('machina.apps'):
        machina_imported_module = _import_module(
            '{}.{}'.format('machina.apps', module_label), classnames,
        )

    if local_imported_module is None and machina_imported_module is None:
        raise AppNotFoundError('Error importing \'{}\''.format(module_path))

    # Any local module is prioritized over the corresponding machina module
    imported_modules = [
        m for m in (local_imported_module, machina_imported_module) if m is not None
    ]
    return _pick_up_classes(imported_modules, classnames)

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

        path = {}
        data = {}
        params = {}

        # REQUIRED - PATH - course_id
        """ID"""
        path["course_id"] = course_id

        # REQUIRED - PATH - quiz_id
        """ID"""
        path["quiz_id"] = quiz_id

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

        self.logger.debug("GET /api/v1/courses/{course_id}/quizzes/{quiz_id}/reports with query params: {params} and form data: {data}".format(params=params, data=data, **path))
        return self.generic_request("GET", "/api/v1/courses/{course_id}/quizzes/{quiz_id}/reports".format(**path), data=data, params=params, all_pages=True)

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


Question:
@param {Object} db
@param {Function} db.model

@throws {Error}
@returns {*}

function ( db ) {
          try {
            if ( Array.isArray( options.schemas ) ) {
              options.schemas.forEach(
                function ( schema ) {
                  var keys = Object.keys( schema );

                  db.model( keys[ 0 ], schema[ keys[ 0 ] ] );
                }
              );
            }

            return db;
          } catch ( err ) {
            throw err;
          }
        }

public function select(Select $select, ResultSet\ResultSetInterface $resultSet = null)
    {
        $stmt = $this->getSql()->prepareStatementForSqlObject($select);

        $resultSet = $resultSet ?: new ResultSet\ResultSet(ResultSet\ResultSet::TYPE_ARRAY);
        $resultSet->initialize($stmt->execute());

        return $resultSet;
    }

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


Question: // Get the patches field of the given host.

func (_class HostClass) GetPatches(sessionID SessionRef, self HostRef) (_retval []HostPatchRef, _err error) {
	_method := "host.get_patches"
	_sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID)
	if _err != nil {
		return
	}
	_selfArg, _err := convertHostRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self)
	if _err != nil {
		return
	}
	_result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg)
	if _err != nil {
		return
	}
	_retval, _err = convertHostPatchRefSetToGo(_method + " -> ", _result.Value)
	return
}

static public function appendPatchVersion($version)
    {
        $shortKnownVersions = array('2.0', '2.1', '2.2');
        if (in_array($version, $shortKnownVersions) === true) {
            $version = $version . '.0';
        }

        return $version;
    }

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


Question:
Custom attribute writer method checking allowed values (enum).
 @param [Object] auth_second_factor_type Object to be assigned

def auth_second_factor_type=(auth_second_factor_type)
      validator = EnumAttributeValidator.new('String', ['none', 'phone_number', 'totp', 'mobile_push', 'security_key', 'fingerprint'])
      unless validator.valid?(auth_second_factor_type)
        fail ArgumentError, 'invalid value for "auth_second_factor_type", must be one of #{validator.allowable_values}.'
      end
      @auth_second_factor_type = auth_second_factor_type
    end

public void marshall(EC2InstanceLimit eC2InstanceLimit, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(eC2InstanceLimit.getEC2InstanceType(), EC2INSTANCETYPE_BINDING);
            protocolMarshaller.marshall(eC2InstanceLimit.getCurrentInstances(), CURRENTINSTANCES_BINDING);
            protocolMarshaller.marshall(eC2InstanceLimit.getInstanceLimit(), INSTANCELIMIT_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:
Store an updated Location
@param  \Illuminate\Http\Request $request current Request object
@param string $id UUID of Location to update
@return \Illuminate\Http\Response JSON object of updated Location

public function update(Request $request, $id)
    {
        /** @noinspection PhpUndefinedMethodInspection */
        $request->validate(['name' => 'required|max:128']);
        /** @noinspection PhpUndefinedMethodInspection */
        $location = Location::findOrFail($id);
        $location->name = $request->name;
        $this->authorize('update', $location);
        /** @noinspection PhpUndefinedMethodInspection */
        $location->save();
        return fractal($location, new LocationTransformer())
            ->withResourceName('location')
            ->respond();

    }

def _update_requires_resolution_inputs(self):

        input_paths = [quad[1] for quad in self.requires_resolution]
        results = resolve_multiple_existing_paths(input_paths)
        for input_name, input_value, input_class, input_index in self.requires_resolution:
            project = results[input_value]['project']
            folderpath = results[input_value]['folder']
            entity_result = results[input_value]['name']
            if input_class is None:
                if entity_result is not None:
                    if isinstance(entity_result, basestring):
                        # Case: -ifoo=job-012301230123012301230123
                        # Case: -ifoo=analysis-012301230123012301230123
                        assert(is_job_id(entity_result) or
                               (is_analysis_id(entity_result)))
                        input_value = entity_result
                    elif is_hashid(input_value):
                        input_value = {'$dnanexus_link': entity_result['id']}
                    elif 'describe' in entity_result:
                        # Then findDataObjects was called (returned describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['describe']['project'],
                                                          "id": entity_result['id']}}
                    else:
                        # Then resolveDataObjects was called in a batch (no describe hash)
                        input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                          "id": entity_result['id']}}
                if input_index >= 0:
                    if self.inputs[input_name][input_index] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name][input_index] = input_value
                else:
                    if self.inputs[input_name] is not None:
                        raise AssertionError("Expected 'self.inputs' to have saved a spot for 'input_value'.")
                    self.inputs[input_name] = input_value
            else:
                msg = 'Value provided for input field "' + input_name + '" could not be parsed as ' + \
                      input_class + ': '
                if input_value == '':
                    raise DXCLIError(msg + 'empty string cannot be resolved')
                if entity_result is None:
                    raise DXCLIError(msg + 'could not resolve \"' + input_value + '\" to a name or ID')
                try:
                    dxpy.bindings.verify_string_dxid(entity_result['id'], input_class)
                except DXError as details:
                    raise DXCLIError(msg + str(details))
                if is_hashid(input_value):
                    input_value = {'$dnanexus_link': entity_result['id']}
                elif 'describe' in entity_result:
                    # Then findDataObjects was called (returned describe hash)
                    input_value = {'$dnanexus_link': {"project": entity_result['describe']['project'],
                                                      "id": entity_result['id']}}
                else:
                    # Then resolveDataObjects was called in a batch (no describe hash)
                    input_value = {"$dnanexus_link": {"project": entity_result['project'],
                                                      "id": entity_result['id']}}
                if input_index != -1:
                    # The class is an array, so append the resolved value
                    self.inputs[input_name].append(input_value)
                else:
                    self.inputs[input_name] = input_value

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


Question: Poor-man's mustache

function renderTmpl (path, vars, callback) {
    fs.readFile(path, 'utf8', function (err, file) {
        if (err) {
            return callback(err);
        }
        var out = file.replace(/\{\{([a-z]+)\}\}/ig, function (all, name) {
            return vars[name];
        });
        callback(null, out);
    });
}

private void showLinkError() {
        Toast.makeText(mContext, mContext.getString(R.string.wings_dropbox__error_link), Toast.LENGTH_SHORT).show();
    }

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


Question:
Receive a list of all pages

@link   https://help.shopify.com/api/reference/page#index
@param  array $params
@return Page[]

public function all(array $params = array())
    {
        $endpoint = '/admin/pages.json';
        $response = $this->request($endpoint, 'GET', $params);
        return $this->createCollection(Page::class, $response['pages']);
    }

def respond(self, request, view, newsitems, extra_context={}):
        """"""
        context = self.get_context(request, view=view)
        context.update(self.paginate_newsitems(request, newsitems))
        context.update(extra_context)
        template = self.get_template(request, view=view)
        return TemplateResponse(request, template, context)

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


Question: generates pdf on-the-fly

private function generateTermsOfUsePdf($customer)
    {
        $this->set('customer', $customer);
        $this->set('saveParam', 'I');
        $this->RequestHandler->renderAs($this, 'pdf');
        return $this->render('generateTermsOfUsePdf');
    }

public function render_assign_files(assign_files $tree) {
        $this->htmlid = html_writer::random_id('assign_files_tree');
        $this->page->requires->js_init_call('M.mod_assign.init_tree', array(true, $this->htmlid));
        $html = '
htmlid.'">';
        $html .= $this->htmllize_tree($tree, $tree->dir);
        $html .= '
';

        if ($tree->portfolioform) {
            $html .= $tree->portfolioform;
        }
        return $html;
    }

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


Question:
Add a new element to 'ServiceDetailsDocuments'

@param \AgentSIB\Diadoc\Api\Proto\Events\ServiceDetailsAttachment $value

public function addServiceDetailsDocuments(\AgentSIB\Diadoc\Api\Proto\Events\ServiceDetailsAttachment $value)
    {
        if ($this->ServiceDetailsDocuments === null) {
            $this->ServiceDetailsDocuments = new \Protobuf\MessageCollection();
        }

        $this->ServiceDetailsDocuments->add($value);
    }

func tagAppendParser(doc *p2.Parser, start *p2.Token, arguments *p2.Parser) (p2.INodeTag, *p2.Error) {
	var name string
	var isPublic bool
	// Parse variable name
	typeToken := arguments.MatchType(p2.TokenIdentifier)
	if typeToken != nil {
		name = typeToken.Val
	} else if sToken := arguments.MatchType(p2.TokenString); nil != sToken {
		name = sToken.Val
	} else {
		return nil, arguments.Error("Expected an identifier or string.", nil)
	}

	evals := []p2.IEvaluator{}
	for arguments.Remaining() > 0 {
		expr, err := arguments.ParseExpression()
		if err != nil {
			return nil, err
		}
		evals = append(evals, expr)
	}

	return &INodeImplied{Exec: func(ctx *p2.ExecutionContext, w p2.TemplateWriter) *p2.Error {

		node := &tagAppendNode{isPublic, name, evals}
		return node.Execute(ctx, w)
	}}, nil

}

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


Question:
/*
Function to validate AST structures

function runValidator(param, paramName) {
  if (!validator(param)) {
    console.log('Error message from validator: ' + validator.errors[0].message);
    console.log('Error message from validator: ', validator.errors[0]);
    throw new error.MalformedAstError(
      paramName +
        ' must be well-defined and follow the AST schema. ' +
        'Object: ' +
        JSON.stringify(param)
    );
  }
}

def assert_wildtype_matches(self, mutation):
        ''''''
        readwt = self.getAminoAcid(self.getAtomLine(mutation.Chain, mutation.ResidueID))
        assert(mutation.WildTypeAA == residue_type_3to1_map[readwt])

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


Question:
// Recv receives a message.  For AF_SP_RAW messages the header data will
// be included at he start of the returned byte slice (otherwise it will
// be stripped).  At this time no flags are supported.

func (s *Socket) Recv(flags int) ([]byte, error) {
	var b []byte
	var m *mangos.Message
	var err error

	if flags != 0 {
		return nil, errNoFlag
	}

	// Legacy nanomsg uses the opposite semantic for negative and
	// zero values than mangos.  A bit unfortunate.
	switch {
	case s.rto > 0:
		s.sock.SetOption(mangos.OptionRecvDeadline, s.rto)
	case s.rto == 0:
		s.sock.SetOption(mangos.OptionRecvDeadline, -1)
	case s.rto < 0:
		s.sock.SetOption(mangos.OptionRecvDeadline, 0)
	}

	if m, err = s.sock.RecvMsg(); err != nil {
		return nil, err
	}

	if s.dom == AF_SP_RAW {
		b = make([]byte, 0, len(m.Body)+len(m.Header))
		b = append(b, m.Header...)
		b = append(b, m.Body...)
	} else {
		b = make([]byte, 0, len(m.Body))
		b = append(b, m.Body...)
	}
	m.Free()
	return b, nil
}

def capture_setting(self, sbp_msg, **metadata):

        if sbp_msg.msg_type == SBP_MSG_SETTINGS_READ_RESP:
            section, setting, value = sbp_msg.payload.split(b'\0')[:3]
            self.settings.append((section, setting, value))

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


Question:
/*
/////////////////////////////////////////////////////////////////////
Public API, DOM manipulation
/////////////////////////////////////////////////////////////////////

protected void appendNode(Node n)
    {
        if (mRootNode != null) {
            mRootNode.appendChild(n);
        } else {
            mElement.appendChild(n);
        }
    }

private function minifyHtmlDom($html, $decodeUtf8Specials): string
    {
        // init dom
        $dom = new HtmlDomParser();
        /** @noinspection UnusedFunctionResultInspection */
        $dom->useKeepBrokenHtml($this->keepBrokenHtml);

        $dom->getDocument()->preserveWhiteSpace = false; // remove redundant white space
        $dom->getDocument()->formatOutput = false; // do not formats output with indentation

        // load dom
        /** @noinspection UnusedFunctionResultInspection */
        $dom->loadHtml($html);

        $this->withDocType = (\stripos(\ltrim($html), '<!DOCTYPE') === 0);

        foreach ($dom->find('*') as $element) {
            $this->notifyObserversAboutDomElementBeforeMinification($element);
        }

        // -------------------------------------------------------------------------
        // Protect HTML tags and conditional comments.
        // -------------------------------------------------------------------------

        $dom = $this->protectTags($dom);

        // -------------------------------------------------------------------------
        // Remove default HTML comments. [protected html is still protected]
        // -------------------------------------------------------------------------

        if ($this->doRemoveComments) {
            $dom = $this->removeComments($dom);
        }

        // -------------------------------------------------------------------------
        // Sum-Up extra whitespace from the Dom. [protected html is still protected]
        // -------------------------------------------------------------------------

        if ($this->doSumUpWhitespace) {
            $dom = $this->sumUpWhitespace($dom);
        }

        foreach ($dom->find('*') as $element) {

            // -------------------------------------------------------------------------
            // Remove whitespace around tags. [protected html is still protected]
            // -------------------------------------------------------------------------

            if ($this->doRemoveWhitespaceAroundTags) {
                $this->removeWhitespaceAroundTags($element);
            }

            $this->notifyObserversAboutDomElementAfterMinification($element);
        }

        // -------------------------------------------------------------------------
        // Convert the Dom into a string.
        // -------------------------------------------------------------------------

        return $dom->fixHtmlOutput(
            $this->domNodeToString($dom->getDocument()),
            $decodeUtf8Specials
        );
    }

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


Question: // SetAuthenticationToken sets the AuthenticationToken field's value.

func (s *DeleteCommentInput) SetAuthenticationToken(v string) *DeleteCommentInput {
	s.AuthenticationToken = &v
	return s
}

def _get_token_from_query_string(self, request, refresh_token):

        if refresh_token:
            query_string_token_name_key = "query_string_refresh_token_name"
        else:
            query_string_token_name_key = "query_string_access_token_name"
        query_string_token_name = getattr(
            self.config, query_string_token_name_key
        )
        return request.args.get(query_string_token_name(), None)

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


Question:
Main method of the Command-line interface (CLI)

@param args
command-line arguments
@throws Throwable

public static void main(String[] args) throws Throwable {
		CliArguments arguments = CliArguments.parse(args);
		if (arguments.isSet() && !arguments.isUsageMode()) {
			CliRunner runner = new CliRunner(arguments);
			try {
				runner.run();
			} finally {
				runner.close();
			}
		} else {
			PrintWriter out = new PrintWriter(System.out);
			printUsage(out);
			FileHelper.safeClose(out);
		}
	}

public function buildCommand(string $name, array $definition): CommandInterface
    {
        $command = new Command($name);
        $command->setExecutable($definition[static::CONFIG_COMMAND]);

        $this->setExcluded($command, $definition);
        $this->setGroups($command, $definition);
        $this->setEnv($command, $definition);
        $this->setIsStoreAware($command, $definition);
        $this->setStores($command, $definition);
        $this->addCommandConditions($command, $definition);
        $this->setPreCommand($command, $definition);
        $this->setPostCommand($command, $definition);
        $this->setBreakOnFailure($command, $definition);
        $this->setTimeout($command, $definition);

        return $command;
    }

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


Question:
Method: parseKmlColor
Parses a kml color (in 'aabbggrr' format) and returns the corresponding
color and opacity or null if the color is invalid.

Parameters:
kmlColor - {String} a kml formated color

Returns:
{Object}

function(kmlColor) {
        var color = null;
        if (kmlColor) {
            var matches = kmlColor.match(this.regExes.kmlColor);
            if (matches) {
                color = {
                    color: '#' + matches[4] + matches[3] + matches[2],
                    opacity: parseInt(matches[1], 16) / 255
                };
            }
        }
        return color;
    }

public void marshall(Tape tape, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(tape.getTapeARN(), TAPEARN_BINDING);
            protocolMarshaller.marshall(tape.getTapeBarcode(), TAPEBARCODE_BINDING);
            protocolMarshaller.marshall(tape.getTapeCreatedDate(), TAPECREATEDDATE_BINDING);
            protocolMarshaller.marshall(tape.getTapeSizeInBytes(), TAPESIZEINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getTapeStatus(), TAPESTATUS_BINDING);
            protocolMarshaller.marshall(tape.getVTLDevice(), VTLDEVICE_BINDING);
            protocolMarshaller.marshall(tape.getProgress(), PROGRESS_BINDING);
            protocolMarshaller.marshall(tape.getTapeUsedInBytes(), TAPEUSEDINBYTES_BINDING);
            protocolMarshaller.marshall(tape.getKMSKey(), KMSKEY_BINDING);
            protocolMarshaller.marshall(tape.getPoolId(), POOLID_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: // RoundTrip implementation

func (a AWSTransport) RoundTrip(req *http.Request) (*http.Response, error) {
	awsauth.Sign4(req, a.Credentials)
	return a.transport.RoundTrip(req)
}

def set_circulating(self, param):

        if param == 0:
            self.is_circulating = param
            self.circulate_commanded = False
        elif param == 1:
            self.is_circulating = param
            self.circulate_commanded = True
        return ""

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


Question:
This method build a array that will contain the string
        representation of the current object. Every lines could be
        prefixed and suffixed.

def get_representation(self, prefix="", suffix="\n"):

        res = []
        if self.hidden:
            res.append(prefix + " - " + str(self._name)
                       + " : xxxxxxxx" + suffix)
        else:
            default = self.default
            if default is None:
                default = " - "
            a = prefix + " - "
            a += str(self._name) + " : "
            if isinstance(default, types.UnicodeType):
                a += default
            else:
                a += str(default)
            a += suffix
            res.append(a)
        return res

public function getNamesFromRights($rights)
    {
        $names = [];
        foreach ($this->rights as $name => $value) {
            if ($this->check($rights, $name)) {
                $names[] = $name;
            }
        }
        return $names;
    }

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


Question:
Add the security identities of reachable roles.

@param TokenInterface              $token The token
@param SecurityIdentityInterface[] $sids  The security identities

@return SecurityIdentityInterface[]

protected function addReachableRoles(TokenInterface $token, array $sids)
    {
        foreach ($this->roleHierarchy->getReachableRoles($token->getRoles()) as $role) {
            $sids[] = RoleSecurityIdentity::fromAccount(RoleUtil::formatName($role));
        }

        return $sids;
    }

protected function setCreatedProvider(string $type, SchemaInterface $provider): void
    {
        $this->createdProviders[$type] = $provider;
    }

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


Question:
Prints all missing rule ids.

@param visitor
The visitor.

private boolean printMissingRules(CollectRulesVisitor visitor) {
        Set<String> missingConcepts = visitor.getMissingConcepts();
        if (!missingConcepts.isEmpty()) {
            logger.info("Missing concepts [" + missingConcepts.size() + "]");
            for (String missingConcept : missingConcepts) {
                logger.warn(LOG_LINE_PREFIX + missingConcept);
            }
        }
        Set<String> missingConstraints = visitor.getMissingConstraints();
        if (!missingConstraints.isEmpty()) {
            logger.info("Missing constraints [" + missingConstraints.size() + "]");
            for (String missingConstraint : missingConstraints) {
                logger.warn(LOG_LINE_PREFIX + missingConstraint);
            }
        }
        Set<String> missingGroups = visitor.getMissingGroups();
        if (!missingGroups.isEmpty()) {
            logger.info("Missing groups [" + missingGroups.size() + "]");
            for (String missingGroup : missingGroups) {
                logger.warn(LOG_LINE_PREFIX + missingGroup);
            }
        }
        return missingConcepts.isEmpty() && missingConstraints.isEmpty() && missingGroups.isEmpty();
    }

private function buildIdParameter() {
        $parameter = new Swagger\Parameter();
        $parameter->setName('id');
        $parameter->setDescription('Which ' . ucfirst($this->getModel()->getSource()) . ' to target.');
        $parameter->setParamType('path');
        $parameter->setType('integer');
        $parameter->setRequired(true);

        return $parameter;
    }

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


Question: Prints out this {@link StatsSnapshot} into log.

@SuppressWarnings("UnusedDeclaration") public void dump() {
    Buffer buffer = new Buffer();
    try {
      dump(buffer);
    } catch (IOException e) {
      throw new AssertionError(e);
    }
    Log.i(TAG, buffer.readUtf8());
  }

def prt_tsv_dat(prt, data_nts, **kws):
    """"""
    sep = "\t" if 'sep' not in kws else kws['sep']
    fld2fmt = None if 'fld2fmt' not in kws else kws['fld2fmt']
    if 'sort_by' in kws:
        data_nts = sorted(data_nts, key=kws['sort_by'])
    prt_if = kws['prt_if'] if 'prt_if' in kws else None
    prt_flds = kws['prt_flds'] if 'prt_flds' in kws else data_nts[0]._fields
    items = 0
    for nt_data_row in data_nts:
        if prt_if is None or prt_if(nt_data_row):
            if fld2fmt is not None:
                row_fld_vals = [(fld, getattr(nt_data_row, fld)) for fld in prt_flds]
                row_vals = _fmt_fields(row_fld_vals, fld2fmt)
            else:
                row_vals = [getattr(nt_data_row, fld) for fld in prt_flds]
            prt.write("{}\n".format(sep.join(str(d) for d in row_vals)))
            items += 1
    return items

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


Question:
Parses the configuration to get the fraction of managed memory and validates the value.

@param configuration configuration object
@return fraction of managed memory

public static float getManagedMemoryFraction(Configuration configuration) {
		float managedMemoryFraction = configuration.getFloat(TaskManagerOptions.MANAGED_MEMORY_FRACTION);

		checkConfigParameter(managedMemoryFraction > 0.0f && managedMemoryFraction < 1.0f, managedMemoryFraction,
			TaskManagerOptions.MANAGED_MEMORY_FRACTION.key(),
			"MemoryManager fraction of the free memory must be between 0.0 and 1.0");

		return managedMemoryFraction;
	}

def actually_mount(self, client):
        """"""
        a_obj = self.config.copy()
        if 'description' in a_obj:
            del a_obj['description']

        try:
            m_fun = getattr(client, self.mount_fun)
            if self.description and a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description,
                      config=a_obj)
            elif self.description:
                m_fun(self.backend,
                      mount_point=self.path,
                      description=self.description)
            elif a_obj:
                m_fun(self.backend,
                      mount_point=self.path,
                      config=a_obj)
            else:
                m_fun(self.backend,
                      mount_point=self.path)
        except hvac.exceptions.InvalidRequest as exception:
            match = re.match('existing mount at (?P<path>.+)', str(exception))
            if match:
                e_msg = "%s has a mountpoint conflict with %s" % \
                        (self.path, match.group('path'))
                raise aomi_excep.VaultConstraint(e_msg)
            else:
                raise

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


Question:
@param \Symfony\Component\HttpFoundation\Request $request
@param \eZ\Publish\API\Repository\Values\Content\Section $section

@return \Symfony\Component\HttpFoundation\Response

public function updateAction(Request $request, Section $section): Response
    {
        $this->denyAccessUnlessGranted(new Attribute('section', 'edit'));
        $form = $this->formFactory->updateSection(
            new SectionUpdateData($section)
        );
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $data = $form->getData();
            try {
                $sectionUpdateStruct = $this->sectionUpdateMapper->reverseMap($data);
                $section = $this->sectionService->updateSection($data->getSection(), $sectionUpdateStruct);

                $this->notificationHandler->success(
                    $this->translator->trans(
                        /** @Desc("Section '%name%' updated.") */
                        'section.update.success',
                        ['%name%' => $section->name],
                        'section'
                    )
                );

                return new RedirectResponse($this->generateUrl('ezplatform.section.view', [
                    'sectionId' => $section->id,
                ]));
            } catch (Exception $e) {
                $this->notificationHandler->error($e->getMessage());
            }
        }

        return $this->render('@ezdesign/admin/section/update.html.twig', [
            'section' => $section,
            'form_section_update' => $form->createView(),
        ]);
    }

public function authenticate($code)
    {
        // Validate code
        if (!$code || strlen($code) != 6) {
            throw new Exception('Invalid authorization code');
        }

        // Check for required items
        if (!$this->clientId) {
            throw new Exception('Client ID is required');
        }
        if (!$this->clientSecret) {
            throw new Exception('Client secret is required');
        }
        if (!$this->redirectUri) {
            throw new Exception('Redirect URI is required');
        }

        $fields = [
            'client_id'     => $this->clientId,
            'client_secret' => $this->clientSecret,
            'code'          => $code,
            'redirect_uri'  => urlencode($this->redirectUri),
            'grant_type'    => 'authorization_code'
        ];

        $url  = 'https://';
        $url .= $this->level . '.';
        $url .= (!empty($this->environment)) ? $this->environment . '.' : '';
        $url .= self::HOSTNAME . '/' . self::TOKEN;

        $this->http->setUrl($url)
                   ->setPostFields($fields)
                   ->setHeader(['Accept' => 'application/json']);

        $data = json_decode($this->http->execute());

        if (isset($data->access_token)) {
            $this->setAccessToken($data->access_token);
            $this->setOrcid($data->orcid);
        } else {
            // Seems like the response format changes on occasion...not sure what's going on there?
            $error = (isset($data->error_description)) ? $data->error_description : $data->{'error-desc'}->value;

            throw new Exception($error);
        }

        return $this;
    }

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


Question: // Handle executing the request and returning a response

func (fn DeletePetHandlerFunc) Handle(params DeletePetParams, principal interface{}) middleware.Responder {
	return fn(params, principal)
}

public function end($exitCode = 0, $exit = true)
    {
        if ($this->hasEventHandler('endRequest')) {
            $this->onEndRequest(new Event($this));
        }
        if ($exit) {
            exit($exitCode);
        }
    }

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


Question:
Delegate the calling to {@link System#load(String)} or {@link System#loadLibrary(String)}.
@param libName - The native library path or name
@param absolute - Whether the native library will be loaded by path or by name

public static void loadLibrary(String libName, boolean absolute) {
        if (absolute) {
            System.load(libName);
        } else {
            System.loadLibrary(libName);
        }
    }

def _get_initial_binary_name(self):

        binary_name = None

        # if this function is a simprocedure but not a syscall, use its library name as
        # its binary name
        # if it is a syscall, fall back to use self.binary.binary which explicitly says cle##kernel
        if self.project and self.is_simprocedure and not self.is_syscall:
            hooker = self.project.hooked_by(self.addr)
            if hooker is not None:
                binary_name = hooker.library_name

        if binary_name is None and self.binary is not None:
            binary_name = os.path.basename(self.binary.binary)

        return binary_name

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


Question:
Method to update a photo from a filepath

@param integer $photoId
@param stirng $filepath
@return array

public function updatePhotoFromPath($photoId, $filepath)
    {
        if (is_null($photoId) || $photoId == '') {
            throw new Exception('The photoId is required to update a photo.');
        }

        if (is_null($filepath) || $filepath == '') {
            throw new Exception('The filepath is required to upload a file.');
        }

        if (!file_exists($filepath)) {
            throw new Exception('The filepath does not point to an accessible file.');
        }

        $params = array(
            'method' => 'sp.photo.update',
            'photo_id' => $photoId,
        );

        $photos = array(
            'photo' => new CURLFile($filepath),
        );

        return $this->_makeApiRequest($params, $photos);
    }

public function delete()
    {
        if (!$this->hasRequestParameter('uri') || !$this->hasRequestParameter('path') || !$this->hasRequestParameter('lang')) {
            throw new common_exception_MissingParameter();
        }

        $item = $this->getResource($this->getRequestParameter('uri'));
        $itemLang = $this->getRequestParameter('lang');

        $resolver = new ItemMediaResolver($item, $itemLang);
        $asset = $resolver->resolve($this->getRequestParameter('path'));
        $deleted = $asset->getMediaSource()->delete($asset->getMediaIdentifier());

        return $this->returnJson(array('deleted' => $deleted));
    }

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


Question: Checks if a notification is pending.

def _check_for_pending(self, *args, **kwargs):

        if self._notification_pending and not self._processing:
            self._processing = True
            args, kwargs = self._data
            self._notify(*args, **kwargs)
            self._notification_pending = False
            self._processing = False

func (s *ExtensionManagerServer) Ping(ctx context.Context) (*osquery.ExtensionStatus, error) {
	return &osquery.ExtensionStatus{Code: 0, Message: "OK"}, nil
}

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


Question:
Handle adding value to element according to the value type.

@param mixed       $value
@param \DOMElement $element

@return Element

protected function appendValueToElementToSend($value, \DOMElement $element)
    {
        if ($value instanceof Element) {
            $this->appendElementToElementToSend($value, $element);
        } elseif (is_array($value)) {
            $this->appendValuesToElementToSend($value, $element);
        } elseif (!empty($value)) {
            $element->appendChild(self::getDom()->createTextNode($value));
        }

        return $this;
    }

public function render()
    {
        $xml = new SimpleXMLElement(
            '<?xml version="1.0" encoding="UTF-8" ?>
            <rss version="2.0"
                xmlns:content="http://purl.org/rss/1.0/modules/content/"
                xmlns:wfw="http://wellformedweb.org/CommentAPI/"
                xmlns:dc="http://purl.org/dc/elements/1.1/"
                xmlns:atom="http://www.w3.org/2005/Atom"
                xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
                xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
            />',
            LIBXML_NOERROR | LIBXML_ERR_NONE | LIBXML_ERR_FATAL
        );

        foreach ($this->channels as $channel) {
            $toDom = dom_import_simplexml($xml);
            $fromDom = dom_import_simplexml($channel->asXML());
            $toDom->appendChild($toDom->ownerDocument->importNode($fromDom, true));
        }

        $dom = new \DOMDocument('1.0', 'UTF-8');
        $dom->appendChild($dom->importNode(dom_import_simplexml($xml), true));
        $dom->formatOutput = true;

        return $dom->saveXML();
    }

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


Question: List all products in the shopping cart

def get(self, request, *args, **kwargs):

        cart = ShoppingCartProxy(request)
        return JsonResponse(cart.get_products(onlypublic=request.GET.get('onlypublic', True)))

def get_collections(self):

        result = self.api_request('/catalog')

        # get the collection name from the url
        return [(os.path.split(x)[1], x) for x in result['collections']]

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


Question: //  id3v2genre parse a id3v2 genre tag and expand the numeric genres

func id3v2genre(genre string) string {
	c := true
	for c {
		orig := genre
		if match := id3v2genreRe.FindStringSubmatch(genre); len(match) > 0 {
			if genreID, err := strconv.Atoi(match[2]); err == nil {
				if genreID < len(id3v2Genres) {
					genre = id3v2Genres[genreID]
					if match[1] != "" {
						genre = strings.TrimSpace(match[1]) + " " + genre
					}
					if match[3] != "" {
						genre = genre + " " + match[3]
					}
				}
			}
		}
		c = (orig != genre)
	}
	return strings.Replace(genre, "((", "(", -1)
}

def _add_ped_metadata(name, metadata):

    ignore = set(["-9", "undefined", "unknown", "."])
    def _ped_mapping(x, valmap):
        try:
            x = int(x)
        except ValueError:
            x = -1
        for k, v in valmap.items():
            if k == x:
                return v
        return None
    def _ped_to_gender(x):
        return _ped_mapping(x, {1: "male", 2: "female"})
    def _ped_to_phenotype(x):
        known_phenotypes = set(["unaffected", "affected", "tumor", "normal"])
        if x in known_phenotypes:
            return x
        else:
            return _ped_mapping(x, {1: "unaffected", 2: "affected"})
    def _ped_to_batch(x):
        if x not in ignore and x != "0":
            return x
    with open(metadata["ped"]) as in_handle:
        for line in in_handle:
            parts = line.split("\t")[:6]
            if parts[1] == str(name):
                for index, key, convert_fn in [(4, "sex", _ped_to_gender), (0, "batch", _ped_to_batch),
                                               (5, "phenotype", _ped_to_phenotype)]:
                    val = convert_fn(parts[index])
                    if val is not None and key not in metadata:
                        metadata[key] = val
                break
    return metadata

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


Question:
Get transformer for type.

@param typeName the type name
@return transform

public static PrefsTransform lookup(TypeName typeName) {
		PrefsTransform transform = cache.get(typeName);

		if (transform != null) {
			return transform;
		}

		transform = getTransform(typeName);
		AssertKripton.assertNotNull(transform, new UnsupportedFieldTypeException(typeName));
		cache.put(typeName, transform);

		return transform;
	}

func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
	jobOpts = applyDefaultsAndValidate(jobOpts)

	vfn := reflect.ValueOf(fn)
	validateHandlerType(wp.contextType, vfn)
	jt := &jobType{
		Name:           name,
		DynamicHandler: vfn,
		JobOptions:     jobOpts,
	}
	if gh, ok := fn.(func(*Job) error); ok {
		jt.IsGeneric = true
		jt.GenericHandler = gh
	}

	wp.jobTypes[name] = jt

	for _, w := range wp.workers {
		w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
	}

	return wp
}

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


Question: Use this API to fetch auditnslogpolicy_aaagroup_binding resources of given name .

public static auditnslogpolicy_aaagroup_binding[] get(nitro_service service, String name) throws Exception{
		auditnslogpolicy_aaagroup_binding obj = new auditnslogpolicy_aaagroup_binding();
		obj.set_name(name);
		auditnslogpolicy_aaagroup_binding response[] = (auditnslogpolicy_aaagroup_binding[]) obj.get_resources(service);
		return response;
	}

func Convert_v1_LocalResourceAccessReview_To_authorization_LocalResourceAccessReview(in *v1.LocalResourceAccessReview, out *authorization.LocalResourceAccessReview, s conversion.Scope) error {
	return autoConvert_v1_LocalResourceAccessReview_To_authorization_LocalResourceAccessReview(in, out, s)
}

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


Question: // SetClusterParameterGroupName sets the ClusterParameterGroupName field's value.

func (s *RestoreFromClusterSnapshotInput) SetClusterParameterGroupName(v string) *RestoreFromClusterSnapshotInput {
	s.ClusterParameterGroupName = &v
	return s
}

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

    return array_merge($return, $array);
  }

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


Question:
Accepts result of `validateForm` and returns true
if `formErrors` contains only null-values.
@param {Object} formErrors - {
%fieldID%: [ %failed_validators% ],
...
}
@returns {Boolean}

function isFormValid ( formErrors ) {
        return t.reduce(function ( acc, v, k ) {
            return acc && !(v && v.length);
        }, true, formErrors );
    }

protected function addPageParameterNode()
    {
    	$builder = new TreeBuilder();
    	$node = $builder->root('page');

    	$node
	    	->treatTrueLike(array(
	    		'versionable' => false,
	    		'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->treatFalseLike(array(
    			'versionable' => false,
    			'signable' => false,
	    		'form' => array(
	    			'type' => "ASF\DocumentBundle\Form\Type\PageType",
	    			'name' => 'page_type'
	    		)
	    	))
	    	->addDefaultsIfNotSet()
	    	->children()
	    		->booleanNode('versionable')
	    			->defaultFalse()
	    		->end()
	    		->booleanNode('signable')
	    			->defaultFalse()
	    		->end()
		    	->arrayNode('form')
			    	->addDefaultsIfNotSet()
			    	->children()
				    	->scalarNode('type')
				    		->defaultValue('ASF\DocumentBundle\Form\Type\PageType')
				    	->end()
				    	->scalarNode('name')
				    		->defaultValue('page_type')
				    	->end()
				    	->arrayNode('validation_groups')
				    		->prototype('scalar')->end()
				    		->defaultValue(array("Default"))
				    	->end()
			    	->end()
		    	->end()
	    	->end()
    	;

    	return $node;
    }

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


Question:
Get an elements class/id weight. Uses regular expressions to tell if this
element looks good or bad.

@param Element
@return number (Integer)

function getClassWeight(e) {
  var weight = 0;

  /* Look for a special classname */
  if (e.className !== '') {
    if (e.className.search(regexps.negativeRe) !== -1) weight -= 25;

    if (e.className.search(regexps.positiveRe) !== -1) weight += 25;
  }

  /* Look for a special ID */
  if (typeof(e.id) == 'string' && e.id != "") {
    if (e.id.search(regexps.negativeRe) !== -1) weight -= 25;

    if (e.id.search(regexps.positiveRe) !== -1) weight += 25;
  }

  return weight;
}

def comment(string, options = {})
      options = {
        style: :css,
        per_line: true
      }.update(options)

      commenters = {
        html: proc { |s| "<!-- #{s} -->" },
        css: proc { |s| "/* #{s} */" },
        js: proc { |s| "/* #{s} */" }
      }

      commenter = commenters[options[:style]] || commenters[:js]

      if options[:per_line]
        string = string.split(/\r?\n/)
        string.map { |s| commenter.call(s) }.join("\n")
      else
        commenter.call(string)
      end
    end

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


Question:
// PrintFs prints the given filesystem to the given writer starting from the given path.
// This is useful for debugging.

func PrintFs(fs afero.Fs, path string, w io.Writer) {
	if fs == nil {
		return
	}
	afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
		if info != nil && !info.IsDir() {
			s := path
			if lang, ok := info.(hugofs.LanguageAnnouncer); ok {
				s = s + "\tLANG: " + lang.Lang()
			}
			if fp, ok := info.(hugofs.FilePather); ok {
				s = s + "\tRF: " + fp.Filename() + "\tBP: " + fp.BaseDir()
			}
			fmt.Fprintln(w, "    ", s)
		}
		return nil
	})
}

def _pprint(params):
    """"""
    params_list = list()
    line_sep = ','
    for i, (k, v) in enumerate(sorted(params.iteritems())):
        if type(v) is float:
            # use str for representing floating point numbers
            # this way we get consistent representation across
            # architectures and versions.
            this_repr = '%s=%.10f' % (k, v)
        else:
            # use repr of the rest
            this_repr = '%s=%r' % (k, v)
        params_list.append(this_repr)

    lines = ','.join(params_list)
    return lines

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


Question: // Suffix returns the file suffix without any delmiter prepended.

func (m Type) Suffix() string {
	if m.fileSuffix != "" {
		return m.fileSuffix
	}
	if len(m.Suffixes) > 0 {
		return m.Suffixes[0]
	}
	// There are MIME types without file suffixes.
	return ""
}

def get_nodes_with_role(role_name, environment=None):

    prefix_search = role_name.endswith("*")
    if prefix_search:
        role_name = role_name.rstrip("*")
    for n in get_nodes(environment):
        roles = get_roles_in_node(n, recursive=True)
        if prefix_search:
            if any(role.startswith(role_name) for role in roles):
                yield n
        else:
            if role_name in roles:
                yield n

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


Question:
List of all the tasks defined in the given scope (and its
 sub-scopes).

def tasks_in_scope(scope)
      prefix = scope.join(":")
      tasks.select { |t|
        /^#{prefix}:/ =~ t.name
      }
    end

def walk_target_deps_topological_order(self, target: Target):
        """"""
        all_deps = get_descendants(self.target_graph, target.name)
        for dep_name in topological_sort(self.target_graph):
            if dep_name in all_deps:
                yield self.targets[dep_name]

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


Question: Multiplies two long values and rounds according {@code MathContext}

private static BigDecimal multiplyAndRound(long x, long y, int scale, MathContext mc) {
        long product = multiply(x, y);
        if(product!=INFLATED) {
            return doRound(product, scale, mc);
        }
        // attempt to do it in 128 bits
        int rsign = 1;
        if(x < 0) {
            x = -x;
            rsign = -1;
        }
        if(y < 0) {
            y = -y;
            rsign *= -1;
        }
        // multiply dividend0 * dividend1
        long m0_hi = x >>> 32;
        long m0_lo = x & LONG_MASK;
        long m1_hi = y >>> 32;
        long m1_lo = y & LONG_MASK;
        product = m0_lo * m1_lo;
        long m0 = product & LONG_MASK;
        long m1 = product >>> 32;
        product = m0_hi * m1_lo + m1;
        m1 = product & LONG_MASK;
        long m2 = product >>> 32;
        product = m0_lo * m1_hi + m1;
        m1 = product & LONG_MASK;
        m2 += product >>> 32;
        long m3 = m2>>>32;
        m2 &= LONG_MASK;
        product = m0_hi*m1_hi + m2;
        m2 = product & LONG_MASK;
        m3 = ((product>>>32) + m3) & LONG_MASK;
        final long mHi = make64(m3,m2);
        final long mLo = make64(m1,m0);
        BigDecimal res = doRound128(mHi, mLo, rsign, scale, mc);
        if(res!=null) {
            return res;
        }
        res = new BigDecimal(BigInteger.valueOf(x).multiply(y*rsign), INFLATED, scale, 0);
        return doRound(res,mc);
    }

def digamma(x, context=None):

    return _apply_function_in_current_context(
        BigFloat,
        mpfr.mpfr_digamma,
        (BigFloat._implicit_convert(x),),
        context,
    )

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


Question: // LeaveRoom leaves the given room. See http://matrix.org/docs/spec/client_server/r0.2.0.html#post-matrix-client-r0-rooms-roomid-leave

func (cli *Client) LeaveRoom(roomID string) (resp *RespLeaveRoom, err error) {
	u := cli.BuildURL("rooms", roomID, "leave")
	_, err = cli.MakeRequest("POST", u, struct{}{}, &resp)
	return
}

def classify_identifier(did):

    if _is_unused_did(did):
        return 'unused on this Member Node'
    elif is_sid(did):
        return 'a Series ID (SID) of a revision chain'
    elif is_local_replica(did):
        return 'a Persistent ID (PID) of a local replica'
    elif is_unprocessed_local_replica(did):
        return (
            'a Persistent ID (PID) of an accepted but not yet processed local replica'
        )
    elif is_archived(did):
        return 'a Persistent ID (PID) of a previously archived local object'
    elif is_obsoleted(did):
        return 'a Persistent ID (PID) of a previously updated (obsoleted) local object'
    elif is_resource_map_db(did):
        return 'a Persistent ID (PID) of a local resource map'
    elif is_existing_object(did):
        return 'a Persistent ID (PID) of an existing local object'
    elif is_revision_chain_placeholder(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing revision of a local '
            'replica'
        )
    elif is_resource_map_member(did):
        return (
            'a Persistent ID (PID) of a remote or non-existing object aggregated in '
            'a local Resource Map'
        )
    logger.warning('Unable to classify known identifier. did="{}"'.format(did))
    return '<UNKNOWN>'

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


Question:
Update counter goal

@see http://api.yandex.ru/metrika/doc/beta/management/goals/editgoal.xml

@param int $id
@param int $counterId
@param Models\Goal $goal
@return Models\Goal

public function updateGoal($id, $counterId, Models\Goal $goal)
    {
        $resource = 'counter/' . $counterId . '/goal/' . $id;
        $response = $this->sendPutRequest($resource, ["goal" => $goal->toArray()]);
        $goalResponse = new Models\UpdateGoalResponse($response);
        return $goalResponse->getGoal();
    }

def _yarn_capacity_scheduler_metrics(self, metrics_json, addl_tags, queue_blacklist):

        tags = ['queue_name:{}'.format(metrics_json['queueName'])]
        tags.extend(addl_tags)

        self._set_yarn_metrics_from_json(tags, metrics_json, YARN_ROOT_QUEUE_METRICS)

        if metrics_json['queues'] is not None and metrics_json['queues']['queue'] is not None:

            queues_count = 0
            for queue_json in metrics_json['queues']['queue']:
                queue_name = queue_json['queueName']

                if queue_name in queue_blacklist:
                    self.log.debug('Queue "{}" is blacklisted. Ignoring it'.format(queue_name))
                    continue

                queues_count += 1
                if queues_count > MAX_DETAILED_QUEUES:
                    self.warning(
                        "Found more than 100 queues, will only send metrics on first 100 queues. "
                        "Please filter the queues with the check's `queue_blacklist` parameter"
                    )
                    break

                tags = ['queue_name:{}'.format(str(queue_name))]
                tags.extend(addl_tags)

                self._set_yarn_metrics_from_json(tags, queue_json, YARN_QUEUE_METRICS)

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


Question:
Create a path data from its node.

@param data The path data (must not be null).
@return The path data node.

public static Xml exportPathData(PathData data)
    {
        Check.notNull(data);

        final Xml node = new Xml(NODE_PATH);
        node.writeString(ATT_CATEGORY, data.getName());
        node.writeDouble(ATT_COST, data.getCost());
        node.writeBoolean(ATT_BLOCK, data.isBlocking());
        exportAllowedMovements(node, data.getAllowedMovements());

        return node;
    }

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

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


Question: Reads and masks (if desired) the data and converts it in one dataframe per variable.

def read_data_by_variable(self, mask=True):
        """"""
        def print_elapsed_time(start, last_stopped, prefix):
            # print(f"{prefix} - Elapsed time [s] since start / last stopped: \
            #     {(int(time.time() - start_time))} / {(int(time.time() - last_stopped))}")
            return time.time()
        start_time = time.time()
        last_stopped = time.time()
        last_stopped = print_elapsed_time(start_time, last_stopped, "Starting chunk function")

        verbose = False

        self.read_data()
        last_stopped = print_elapsed_time(start_time, last_stopped, "Data read")

        # 2.
        sc_chunk = self.convert_data_to_dataframe()
        last_stopped = print_elapsed_time(start_time, last_stopped, "Data converted to df")

        # 3.B.
        if mask:
            # 3.A.
            ilocs_qa = np.where((self.df_layers["band"] == self.qa).values)[0]
            df_qa = self.data.iloc[:, ilocs_qa]
            df_qa.columns = self.df_layers["date"].iloc[ilocs_qa]
            df_clearsky = df_qa.isin(self.qa_valid)
            last_stopped = print_elapsed_time(start_time, last_stopped, "Clearsky df created")

            return_bands = self.variables
        else:
            return_bands = self.variables + [self.qa]

        dfs_variables = {}
        for var in return_bands:
            if verbose:
                print("VARIABLE:", var)
            ilocs_var = np.where((self.df_layers["band"] == var).values)[0]
            df_var = self.data.iloc[:, ilocs_var]
            df_var.columns = self.df_layers["date"].iloc[ilocs_var]
            if mask:
                df_var = df_var.where(df_clearsky, other=np.nan)
            dfs_variables[var] = df_var
        last_stopped = print_elapsed_time(start_time, last_stopped, "Clearsky df created")
        self._data = dfs_variables
        return self

def _apply_pipeline_and_get_build_instance(self,
	                                           X_factory,
	                                           mX_factory,
	                                           category_idx_store,
	                                           df,
	                                           parse_pipeline,
	                                           term_idx_store,
	                                           metadata_idx_store,
	                                           y):
		'''

		'''
		df.apply(parse_pipeline.parse, axis=1)
		y = np.array(y)
		X, mX = build_sparse_matrices(y, X_factory, mX_factory)
		return CorpusDF(df,
		                X,
		                mX,
		                y,
		                self._text_col,
		                term_idx_store,
		                category_idx_store,
		                metadata_idx_store)

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


Question:
Retrieve a service by name.

@param string $service

@return ServiceInterface

public function getService($service)
    {
        $service = $this->mapServiceName($service);

        if (isset($this->services[$service])) {
            return $this->services[$service];
        }

        return $this->services[$service] = $this->createService($service);
    }

private function populateAvailableTypes($onlyAutowiringTypes = false)
    {
        $this->types = array();
        if (!$onlyAutowiringTypes) {
            $this->ambiguousServiceTypes = array();
        }

        foreach ($this->container->getDefinitions() as $id => $definition) {
            $this->populateAvailableType($id, $definition, $onlyAutowiringTypes);
        }
    }

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


Question: Adds the match stage according to the chosen null management.

private function addMatch(Builder $aggregationBuilder, string $field, string $operator, string $value, string $nullManagement = null): void
    {
        try {
            $value = new \DateTime($value);
        } catch (\Exception $e) {
            // Silently ignore this filter if it can not be transformed to a \DateTime
            $this->logger->notice('Invalid filter ignored', [
                'exception' => new InvalidArgumentException(sprintf('The field "%s" has a wrong date format. Use one accepted by the \DateTime constructor', $field)),
            ]);

            return;
        }

        $operatorValue = [
            self::PARAMETER_BEFORE => '$lte',
            self::PARAMETER_STRICTLY_BEFORE => '$lt',
            self::PARAMETER_AFTER => '$gte',
            self::PARAMETER_STRICTLY_AFTER => '$gt',
        ];

        if ((self::INCLUDE_NULL_BEFORE === $nullManagement && \in_array($operator, [self::PARAMETER_BEFORE, self::PARAMETER_STRICTLY_BEFORE], true)) ||
            (self::INCLUDE_NULL_AFTER === $nullManagement && \in_array($operator, [self::PARAMETER_AFTER, self::PARAMETER_STRICTLY_AFTER], true)) ||
            (self::INCLUDE_NULL_BEFORE_AND_AFTER === $nullManagement && \in_array($operator, [self::PARAMETER_AFTER, self::PARAMETER_STRICTLY_AFTER, self::PARAMETER_BEFORE, self::PARAMETER_STRICTLY_BEFORE], true))
        ) {
            $aggregationBuilder->match()->addOr(
                $aggregationBuilder->matchExpr()->field($field)->operator($operatorValue[$operator], $value),
                $aggregationBuilder->matchExpr()->field($field)->equals(null)
            );

            return;
        }

        $aggregationBuilder->match()->addAnd($aggregationBuilder->matchExpr()->field($field)->operator($operatorValue[$operator], $value));
    }

protected function doAddFunctionPhases(Skill $model, $data) {
		$errors = [];
		foreach ($data as $entry) {
			if (!isset($entry['id'])) {
				$errors[] = 'Missing id for FunctionPhase';
			} else {
				$related = FunctionPhaseQuery::create()->findOneById($entry['id']);
				$model->addFunctionPhase($related);
			}
		}

		if (count($errors) > 0) {
			return new ErrorsException($errors);
		}
	}

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


Question: Initialize form metadata

def _init_metadata(self, **kwargs):
        """"""
        osid_objects.OsidObjectForm._init_metadata(self, **kwargs)
        self._rubric_default = self._mdata['rubric']['default_id_values'][0]
        self._level_default = self._mdata['level']['default_id_values'][0]

public function getConfiguration()
    {
        $driverChain = $this->getMetadataDriverImpl();
        // Inject the driverChain into the doctrine config
        $this->configuration->setMetadataDriverImpl($driverChain);
        return $this->configuration;
    }

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


Question:
Update properties after removing built-in filters.

@return void

protected function updateInternalState()
    {
        if (!$this->hasFilter(static::END_DATE_FILTER)) {
            $this->endDate = null;
        }

        if (!$this->hasFilter(static::RECURRENCES_FILTER)) {
            $this->recurrences = null;
        }
    }

public function stepUpdateRecordState($type, $id, $state) {
		$class = $this->convertTypeToClass($type);
		$obj = $this->fixtureFactory->get($class, $id);
		if(!$obj) {
			throw new \InvalidArgumentException(sprintf(
				'Can not find record "%s" with identifier "%s"',
				$type,
				$id
			));
		}

		switch($state) {
			case 'published':
				$obj->publish('Stage', 'Live');
				break;
			case 'not published':
			case 'unpublished':
				$oldMode = \Versioned::get_reading_mode();
				\Versioned::reading_stage('Live');
				$clone = clone $obj;
				$clone->delete();
				\Versioned::reading_stage($oldMode);
				break;
			case 'deleted':
				$obj->delete();
				break;
			default:
				throw new \InvalidArgumentException(sprintf(
					'Invalid state: "%s"', $state
				));
		}
	}

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


Question:
Identifies unique elementary reactions in data frame.

    Parameters
    ----------
    df : Data frame.

    Returns
    -------
    reaction_list : List of unique elementary reactions.

def unique_reactions(df):

    reaction_list =[]
    for idx, entry in enumerate(df['reactants']):
        reaction = []
        for x in entry:
            reaction.append(x)
        reaction.append('-->')
        for y in df['products'][idx]:
            reaction.append(y)
        reaction_list.append(reaction)
    string_list = [str(reaction) for reaction in reaction_list]
    string_list = sorted(list(set(string_list)))
    reaction_list = [ast.literal_eval(entry) for entry in string_list]
    return(reaction_list)

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:
Creates a customized copy of the Signature.
        Pass 'parameters' and/or 'return_annotation' arguments
        to override them in the new copy.

def replace(self, parameters=_void, return_annotation=_void):

        if parameters is _void:
            parameters = self.parameters.values()

        if return_annotation is _void:
            return_annotation = self._return_annotation

        return type(self)(parameters, return_annotation=return_annotation)

def _set_rc(self):
        """"""
        base_str = self._get_rc_strings()
        # to make sure that the '.' is not interpreted as a regex pattern,
        # we specify the pattern_base by ourselves
        pattern_base = map(lambda s: s.replace('.', '\.'), base_str)
        # pattern for valid keys being all formatoptions in this plotter
        pattern = '(%s)(?=$)' % '|'.join(self._get_formatoptions())
        self._rc = rcParams.find_and_replace(base_str, pattern=pattern,
                                             pattern_base=pattern_base)
        user_rc = SubDict(rcParams['plotter.user'], base_str, pattern=pattern,
                          pattern_base=pattern_base)
        self._rc.update(user_rc.data)

        self._defaultParams = SubDict(rcParams.defaultParams, base_str,
                                      pattern=pattern,
                                      pattern_base=pattern_base)

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


Question:
Builds a flat list of files by diving down recursively

@return  array

public function getFlatListOfFiles()
	{
		if (!isset($this->flatData))
		{
			$this->flatData = [];

			foreach ($this as $entity)
			{
				if ($entity->isFile())
				{
					$this->flatData[] = $entity;
				}
				else
				{
					// The result of this is already flat, so no need for recursion
					foreach ($entity->listContents(true) as $sub)
					{
						if ($sub->isfile())
						{
							$this->flatData[] = $sub;
						}
					}
				}
			}
		}

		return $this->flatData;
	}

def _scan_directory(directory, sentinel, depth=0):
    '''
    '''
    directory = os.path.abspath(directory)
    real_directory = os.path.realpath(directory)

    if depth < max_directory_depth and real_directory not in sentinel \
            and os.path.isdir(directory):
        sentinel.add(real_directory)

        for item in os.listdir(directory):
            if item in ('.', '..'):
                # I'm not sure if this is even needed any more.
                continue

            p = os.path.abspath(os.path.join(directory, item))
            if (os.path.isdir(p) and _dir_ignore.search(p)) \
                    or (os.path.isfile(p) and _ext_ignore.search(p)):
                continue

            yield p

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


Question: // SetSignatureAlgorithm sets the SignatureAlgorithm field's value.

func (s *CertificateDetail) SetSignatureAlgorithm(v string) *CertificateDetail {
	s.SignatureAlgorithm = &v
	return s
}

def set_trigger_group_bit_mask(self, trigger_group_bit_mask):
        """"""
        set_cmd = self._create_set_property_msg("_trigger_group_bit_mask",
                                                0x0c, trigger_group_bit_mask)
        self._send_method(set_cmd, self._property_set)

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


Question:
Create this calendar in a popup menu and synchronize the text field on change.
@param strDateParam The name of the date property (defaults to "date").
@param dateTarget The initial date for this button.
@param button The calling button.

public static JCalendarPopup createCalendarPopup(String strDateParam, Date dateTarget, Component button)
    {
        return JCalendarPopup.createCalendarPopup(null, dateTarget, button, null);
    }

public static function callEvents(MocaBonita $mocaBonita, $dispatch, $complement = null)
    {
        foreach ($mocaBonita->getMbEvents($dispatch) as $event) {
            call_user_func_array(
                [$event, $dispatch],
                [$mocaBonita->getMbRequest(), $mocaBonita->getMbResponse(), $complement]
            );
        }
    }

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


Question: Create a common loader

function(config, cb){
    // This will tell webpack to create a new chunk
    rq.ensure(['INDEX_PATH'],function(rq){
      let library = rq('INDEX_PATH');
      library = library.default || library; // To preven issues between versions
      cb(
        // Expected to export an initializing function
        library(config)
      );
    },'NAME');
  }

@Override
    public T addAsLibraries(File... resources) throws IllegalArgumentException {
        Validate.notNull(resources, "Resources must be specified");
        for (File resource : resources) {
            addAsLibrary(resource);
        }
        return covarientReturn();
    }

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


Question:
/*
   Returns a new HTTP Response.
*/

func createResponse(res *stackr.Response, next func(), app *Server) *Response {

	this := &Response{}

	this.Response = res

	this.SetNext(next)

	this.SetApplication(app)

	this.Charset = "utf-8"

	this.Locals = map[string]string{}

	return this
}

private static function _doResponse($type, $objects, $echoResponse, $format) {
        $ret = array();
        $ret['status'] = $type;
        if (is_array($objects)) {
            foreach ($objects as $k => $v) {
                $ret[$k] = $v;
            }
        } else {
            $ret[] = $objects;
        }

        switch ($format) {
            case 'xml':
                require_once 'XML/Serializer.php';
                $options = array(
                    "indent" => "    ",
                    "linebreak" => "\n",
                    "typeHints" => false,
                    "addDecl" => true,
                    "encoding" => "UTF-8",
                    "rootName" => "data",
//					"rootAttributes"  => array("version" => "0.91"),
                    "defaultTagName" => "item",
                    "attributesArray" => "_attributes"
                );

                $serializer = new \XML_Serializer($options);

                $rc = $serializer->serialize($ret);
                if ($rc !== TRUE) {

                }
                $ret = $serializer->getSerializedData();
                break;

            case 'json':
            default:
                $ret = json_encode($ret);
                break;
        }

        if ($echoResponse) {
            echo $ret;
        }
        return $ret;
    }

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


Question:
Возвращает подготовленный SELECT для выборки значения из кэша по ключу
@return SelectBuilder

private function getPreparedSelect()
    {
        if (is_null($this->preparedSelect)) {
            $this->preparedSelect = $this->getServer()
                ->select()
                ->select($this->valueColumnName)
                ->from($this->tableName)
                ->where('AND')
                ->expr($this->keyColumnName, '=', ':id')
                ->begin('OR')
                ->expr($this->expireColumnName, '=', ':zero')
                ->expr($this->expireColumnName, '>', ':expire')
                ->end();
        }

        return $this->preparedSelect;
    }

func NewPodStore(c kubernetes.Interface, namespace string, label labels.Selector, field fields.Selector) *PodStore {
	lw := &cache.ListWatch{
		ListFunc: func(options metav1.ListOptions) (runtime.Object, error) {
			options.LabelSelector = label.String()
			options.FieldSelector = field.String()
			obj, err := c.Core().Pods(namespace).List(options)
			return runtime.Object(obj), err
		},
		WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) {
			options.LabelSelector = label.String()
			options.FieldSelector = field.String()
			return c.Core().Pods(namespace).Watch(options)
		},
	}
	store := cache.NewStore(cache.MetaNamespaceKeyFunc)
	stopCh := make(chan struct{})
	reflector := cache.NewReflector(lw, &v1.Pod{}, store, 0)
	go reflector.Run(stopCh)
	return &PodStore{Store: store, stopCh: stopCh, Reflector: reflector}
}

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


Question:
Invoice the billable entity outside of regular billing cycle.

@return bool|StripeInvoice

public function invoice()
    {
        if ($this->stripe_id) {
            try {
                return StripeInvoice::create(['customer' => $this->stripe_id], $this->getStripeKey())->pay();
            } catch (InvalidRequest $e) {
                return false;
            }
        }

        return true;
    }

public function update_status($instance, $newstatus) {
        global $DB;

        $instance->status = $newstatus;
        $DB->update_record('enrol', $instance);

        $context = context_course::instance($instance->courseid);
        \core\event\enrol_instance_updated::create_from_record($instance)->trigger();

        // Invalidate all enrol caches.
        $context->mark_dirty();
    }

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


Question:
Attempt to authorize and process the user's login with the specified password.

@return void

public function processLogin()
    {
        if ($this->isActive() && !empty($_REQUEST['password'])) {
            if ($this->verifyPassword($_REQUEST['password'])) {
                $this->setCookie();

                if (wp_safe_redirect($this->redirectUrl())) {
                    exit;
                }

                return;
            }

            $this->unsetCookie();
            $this->errors->add('invalid_password', __('The password you have entered is incorrect.', 'app'));
        }
    }

private function parse($body)
    {
        $result = array();
        $data = json_decode($body);

        $response = is_array($data->response) ? new \stdClass : $data->response;
        if (null == $response) {
            $response = $data;
        }
        $response->errors = $data->errors;
        $response->test = isset($data->test) ? $data->test : $response->test;

        if ($data->successful == true) {
            if ((isset($response->authorized)
                && $response->authorized == true)
                || (isset($response->id)
                && $response->id !== null)
            ) {
                $response->authorization_id = isset($response->id)
                    ? $response->id
                    : $response->token;
            } else {
                $response->authorization_id = null;
            }

            $response->success = true;
        } else {
            $response->success = false;
            $response->authorization_id = null;
        }

        $response->message = isset($response->message) ? $response->message : $data->errors;

        return (array) $response;

    }

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


Question:
// Prepend reserves the requested space in front of the buffer, returning a
// slice that represents the reserved space.

func (p *Prependable) Prepend(size int) []byte {
	if size > p.usedIdx {
		return nil
	}

	p.usedIdx -= size
	return p.View()[:size:size]
}

def _pad_block(self):

    pad_length = _BLOCK_SIZE - self.__position % _BLOCK_SIZE
    if pad_length and pad_length != _BLOCK_SIZE:
      self.__writer.write('\x00' * pad_length)
      self.__position += pad_length

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


Question: // Release releases a volume reference

func (s *VolumesService) Release(ctx context.Context, name string, ref string) error {
	return s.vs.Release(ctx, name, ref)
}

public static HandlerReference newRef(
            ComponentType component, Method method,
            int priority, HandlerScope filter) {
        if (handlerTracking.isLoggable(Level.FINE)) {
            return new VerboseHandlerReference(
                component, method, priority, filter);
        } else {
            return new HandlerReference(component, method, priority, filter);
        }
    }

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


Question:
Checks if object has a property with specified name..

@param obj  an object to introspect.
@param name a name of the property to check.
@return true if the object has the property and false if it doesn't.

public static boolean hasProperty(Object obj, String name) {
		if (obj == null)
			throw new NullPointerException("Object cannot be null");
		if (name == null)
			throw new NullPointerException("Property name cannot be null");

		Class<?> objClass = obj.getClass();

		// Search in fields
		for (Field field : objClass.getFields()) {
			if (matchField(field, name))
				return true;
		}

		// Search in properties
		name = "get" + name;
		for (Method method : objClass.getMethods()) {
			if (matchPropertyGetter(method, name))
				return true;
		}

		return false;
	}

public function dispatch($route, $request)
    {
        $request->setParam('Closure', $route[4]);

        if(isset($route[3]) && is_string($route[3])) {
            $view = $route[3];
            $data = $route[4];
            return ['view' => [$view, $data]];
        }
        elseif(isset($route[2]) && is_string($route[2])) {
            list($controller, $method) = explode('@', $route[2]);
            return ['controller' => [$controller, $method]];
        }
        elseif(isset($route[2]) && ($route[2] instanceof Closure || get_class($route[2]) === "Closure")) {
            $function = $route[2];
            $reflectionFunction = new ReflectionFunction($function);
            $numReqParam = $reflectionFunction->getNumberOfRequiredParameters();
            if($numReqParam > count($request->getParam('Closure'))) {
                throw new Exception('Invaliding number of required parameter passed in route\'s callable function: '.$route[1]);
            }
            ob_start();
            if($request->getParam('Closure') !== false && is_array($request->getParam('Closure')) ) {
                $return = call_user_func_array($route[2], $request->getParam('Closure'));
            }
            else {
                //$function();
                throw new Exception('Invaliding parameter passed in route\'s callable function: '.$route[1]);
            }
            $output = ob_get_clean();
            return ['output' => [$output, $return]];
        }
        else {
            throw new Exception('Invaliding route is registered for: '.$route[1]);
        }
    }

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


Question: Calculate the centre of a tile given the top-left corner and the size of the image.

def _center_tile(self, position, size):
        x, y = position
        w, h = size
        """"""
        return x + (self.cell_width - w) / 2, y + (self.cell_height - h) / 2

protected BaseTile computeFringeTile (int tx, int ty)
    {
        return _panel == null ? null : _panel.computeFringeTile(tx, ty);
    }

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