Question:
Add new jobs to the priority table and update the build system if required.
    data - it is a list of dictionaries that describe a job type

    returns the number of new, failed and updated jobs

def _update_table(data):

    jp_index, priority, expiration_date = _initialize_values()

    total_jobs = len(data)
    new_jobs, failed_changes, updated_jobs = 0, 0, 0
    # Loop through sanitized jobs, add new jobs and update the build system if needed
    for job in data:
        key = _unique_key(job)
        if key in jp_index:
            # We already know about this job, we might need to update the build system
            # We're seeing the job again with another build system (e.g. buildbot vs
            # taskcluster). We need to change it to '*'
            if jp_index[key]['build_system_type'] != '*' and jp_index[key]['build_system_type'] != job["build_system_type"]:
                db_job = JobPriority.objects.get(pk=jp_index[key]['pk'])
                db_job.buildsystem = '*'
                db_job.save()

                logger.info('Updated %s/%s from %s to %s',
                            db_job.testtype, db_job.buildtype,
                            job['build_system_type'], db_job.buildsystem)
                updated_jobs += 1

        else:
            # We have a new job from runnablejobs to add to our master list
            try:
                jobpriority = JobPriority(
                    testtype=str(job["testtype"]),
                    buildtype=str(job["platform_option"]),
                    platform=str(job["platform"]),
                    priority=priority,
                    expiration_date=expiration_date,
                    buildsystem=job["build_system_type"]
                )
                jobpriority.save()
                logger.info('New job was found (%s,%s,%s,%s)',
                            job['testtype'], job['platform_option'], job['platform'],
                            job["build_system_type"])
                new_jobs += 1
            except Exception as error:
                logger.warning(str(error))
                failed_changes += 1

    logger.info('We have %s new jobs and %s updated jobs out of %s total jobs processed.',
                new_jobs, updated_jobs, total_jobs)

    if failed_changes != 0:
        logger.warning('We have failed %s changes out of %s total jobs processed.',
                       failed_changes, total_jobs)

    return new_jobs, failed_changes, updated_jobs

def _get_current_migration_state(self, loader, apps):

        # Only care about applied migrations for the passed-in apps.
        apps = set(apps)
        relevant_applied = [migration for migration in loader.applied_migrations if migration[0] in apps]
        # Sort them by the most recent migration and convert to a dictionary,
        # leaving apps as keys and most recent migration as values.
        # NB: this is a dirty trick
        most_recents = dict(sorted(relevant_applied, key=lambda m: m[1]))
        # Fill in the apps with no migrations with 'zero'.
        # NOTE: Unicode Django application names are unsupported.
        most_recents = [[app, 'zero' if app not in most_recents else str(most_recents[app])] for app in apps]
        return most_recents

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


Question:
Sets the similarity implementation, which will be used for indexing and
searching. The implementation must extend {@link Similarity}.

@param className
a {@link Similarity} implementation.

public void setSimilarityClass(String className)
   {
      try
      {
         Class<?> similarityClass = ClassLoading.forName(className, this);
         similarity = (Similarity)similarityClass.newInstance();
      }
      catch (ClassNotFoundException e)
      {
         log.warn("Invalid Similarity class: " + className, e);
      }
      catch (InstantiationException e)
      {
         log.warn("Invalid Similarity class: " + className, e);
      }
      catch (IllegalAccessException e)
      {
         log.warn("Invalid Similarity class: " + className, e);
      }
   }

public function load(ContainerBuilder $container, array $config) {
        // Client initializer definition
        $clientInitializerDefinition = new Definition(
            ApiClientAwareInitializer::class,
            [
                $config['apiClient']
            ]
        );
        $clientInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Definition for the array contains comparator
        $comparatorDefinition = new Definition(ArrayContainsComparator::class);

        // Comparator initializer definition
        $comparatorInitializerDefinition = new Definition(
            ArrayContainsComparatorAwareInitializer::class,
            [
                new Reference(self::COMPARATOR_SERVICE_ID)
            ]
        );
        $comparatorInitializerDefinition->addTag(ContextExtension::INITIALIZER_TAG);

        // Add all definitions to the container
        $container->setDefinition(self::APICLIENT_INITIALIZER_SERVICE_ID, $clientInitializerDefinition);
        $container->setDefinition(self::COMPARATOR_SERVICE_ID, $comparatorDefinition);
        $container->setDefinition(self::COMPARATOR_INITIALIZER_SERVICE_ID, $comparatorInitializerDefinition);
    }

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


Question:
Checks if an event mapping with the given eventType exists.

@param eventType the event type name.
@return true if the mapping exists, false otherwise.

@Beta
    public boolean containsCustomEventMappingFor(final String eventType) {
        if (eventType == null || eventType.isEmpty()) {
            return false;
        } else {
            return this.eventTypeToEventDataMapping.containsKey(canonicalizeEventType(eventType));
        }
    }

public void marshall(FilterLogEventsRequest filterLogEventsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(filterLogEventsRequest.getLogGroupName(), LOGGROUPNAME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLogStreamNames(), LOGSTREAMNAMES_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLogStreamNamePrefix(), LOGSTREAMNAMEPREFIX_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getEndTime(), ENDTIME_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getFilterPattern(), FILTERPATTERN_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getNextToken(), NEXTTOKEN_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getLimit(), LIMIT_BINDING);
            protocolMarshaller.marshall(filterLogEventsRequest.getInterleaved(), INTERLEAVED_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:
Return a new {@link Source} from the specified value supplier that can be used to
perform the mapping.
@param <T> the source type
@param supplier the value supplier
@return a {@link Source} that can be used to complete the mapping
@see #from(Object)

public <T> Source<T> from(Supplier<T> supplier) {
		Assert.notNull(supplier, "Supplier must not be null");
		Source<T> source = getSource(supplier);
		if (this.sourceOperator != null) {
			source = this.sourceOperator.apply(source);
		}
		return source;
	}

func updateNodeField(src interface{}, targetName string, target interface{}) interface{} {
	var isPtr bool
	srcVal := reflect.ValueOf(src)
	// verify condition
	if srcVal.Kind() == reflect.Ptr {
		isPtr = true
		srcVal = srcVal.Elem()
	}
	targetVal := reflect.ValueOf(target)
	if srcVal.Kind() != reflect.Struct {
		return src
	}
	srcFieldValue := srcVal.FieldByName(targetName)
	if !srcFieldValue.IsValid() || srcFieldValue.Kind() != targetVal.Kind() {
		return src
	}

	if srcFieldValue.CanSet() {
		if srcFieldValue.Kind() == reflect.Slice {
			items := reflect.MakeSlice(srcFieldValue.Type(), targetVal.Len(), targetVal.Len())
			for index := 0; index < items.Len(); index++ {
				tmp := targetVal.Index(index).Interface()
				items.Index(index).Set(reflect.ValueOf(tmp))
			}
			srcFieldValue.Set(items)
		} else {
			srcFieldValue.Set(targetVal)
		}
	}
	if isPtr {
		return srcVal.Addr().Interface()
	}
	return srcVal.Interface()
}

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


Question: Sets the rounding params.

public void setRoundingParams(@Nullable RoundingParams roundingParams) {
    mRoundingParams = roundingParams;
    WrappingUtils.updateOverlayColorRounding(mTopLevelDrawable, mRoundingParams);
    for (int i = 0; i < mFadeDrawable.getNumberOfLayers(); i++) {
      WrappingUtils.updateLeafRounding(getParentDrawableAtIndex(i), mRoundingParams, mResources);
    }
  }

def reset_parameters(self, init_weight):

        stdv = 1. / math.sqrt(self.num_units)
        self.linear_att.data.uniform_(-init_weight, init_weight)

        if self.normalize:
            self.normalize_scalar.data.fill_(stdv)
            self.normalize_bias.data.zero_()

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


Question: // Set the value

func (r *Ref) setValue(val interface{}, commitPoint uint64) {
	hcnt := r.calcHistoryCount()

	if r.tvals == nil {
		r.tvals = newTval(val, commitPoint)
	} else if (r.getFault() > 0 && hcnt < r.maxHistory) || hcnt < r.minHistory {
		r.tvals = newTvalPrior(val, commitPoint, r.tvals)
		r.setFault(0)
	} else {
		r.tvals = r.tvals.next
		r.tvals.setValue(val, commitPoint)
	}
}

public void registerDefaultValueProcessor( Class target, DefaultValueProcessor defaultValueProcessor ) {
      if( target != null && defaultValueProcessor != null ) {
         defaultValueMap.put( target, defaultValueProcessor );
      }
   }

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


Question: // SetId sets the Id field's value.

func (s *RotateChannelCredentialsInput) SetId(v string) *RotateChannelCredentialsInput {
	s.Id = &v
	return s
}

protected void resetAllValues() {
        logic = new FilterFieldStringData(CommonFilterConstants.LOGIC_FILTER_VAR, CommonFilterConstants.LOGIC_FILTER_VAR_DESC);

        filterVars.clear();
        filterVars.add(logic);
    }

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


Question:
implement the visitor to reset the stack

@param obj
the context object of the currently parsed method

@Override
    public void visitCode(Code obj) {
        Method m = getMethod();
        if (prescreen(m)) {
            stack.resetForMethodEntry(this);
            popStack.clear();
            super.visitCode(obj);
        }
    }

public function setParameter($name, $parameter)
  {
    if ($this->isLocked()) {
      return $this->getObj()->setParameter($name, $parameter)->setLocked();
    } else {
      return parent::setParameter($name, $parameter);
    }
  }

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


Question:
Handle the current request as a CLIRequest one
This method ends the script

public static function handleCurrentRequest() {
		try {
			CLIRoute::initialize();
			static::$mainRequest = static::generateFromEnvironment();
			$response = static::$mainRequest->process();
		} catch( \Exception $e ) {
			$response = CLIResponse::generateFromException($e);
		}
		$response->process();
		exit($response->getCode());
	}

func Check(cr CypherRunner) error {
	var results []struct {
		node interface{}
	}

	query := &neoism.CypherQuery{
		Statement: `MATCH (n) RETURN id(n) LIMIT 1`,
		Result:    &results,
	}

	err := cr.CypherBatch([]*neoism.CypherQuery{query})

	if err != nil {
		return err
	}
	return nil
}

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


Question:
/*!
\note Transaction unsafe. If you call several transaction unsafe methods you must enclose
the calls within a db transaction; thus within db->begin and db->commit.

function updatePrices()
    {
        $productCollection = $this->attribute( 'productcollection' );
        if ( $productCollection )
        {
            $currencyCode = '';
            $items = $this->items();

            $db = eZDB::instance();
            $db->begin();
            foreach( $items as $itemArray )
            {
                $item = $itemArray['item_object'];
                $productContentObject = $item->attribute( 'contentobject' );
                $priceObj = null;
                $price = 0.0;
                $attributes = $productContentObject->contentObjectAttributes();
                foreach ( $attributes as $attribute )
                {
                    $dataType = $attribute->dataType();
                    if ( eZShopFunctions::isProductDatatype( $dataType->isA() ) )
                    {
                        $priceObj = $attribute->content();
                        $price += $priceObj->attribute( 'price' );
                        break;
                    }
                }
                if ( !is_object( $priceObj ) )
                    break;

                $currency = $priceObj->attribute( 'currency' );
                $optionsPrice = $item->calculatePriceWithOptions( $currency );

                $price += $optionsPrice;
                $item->setAttribute( "price", $price );
                if ( $priceObj->attribute( 'is_vat_included' ) )
                {
                    $item->setAttribute( "is_vat_inc", '1' );
                }
                else
                {
                    $item->setAttribute( "is_vat_inc", '0' );
                }
                $item->setAttribute( "vat_value", $priceObj->VATPercent( $productContentObject ) );
                $item->setAttribute( "discount", $priceObj->attribute( 'discount_percent' ) );
                $item->store();

                $currencyCode = $priceObj->attribute( 'currency' );
            }

            $productCollection->setAttribute( 'currency_code', $currencyCode );
            $productCollection->store();
            $db->commit();

            // update prices that are related to shipping values.
            eZShippingManager::updateShippingInfo( $productCollection->attribute( 'id' ) );
        }
    }

public function removeAll()
    {
        $pdo = $this->entityManager->getConnection()->getWrappedConnection();
        $pdo->beginTransaction();

        try {

            $pdo->exec('SET FOREIGN_KEY_CHECKS=0');
            $pdo->exec('TRUNCATE role_permission');
            $pdo->exec('TRUNCATE role_hierarchy');
            $pdo->exec('TRUNCATE role');
            $pdo->exec('TRUNCATE permission');
            $pdo->exec('TRUNCATE user_role');
            $pdo->exec('SET FOREIGN_KEY_CHECKS=1');

            $pdo->commit();

        } catch (\Exception $e) {
            $pdo->rollBack();
            throw new DatabaseException($e->getMessage());
        }
    }

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


Question:
/*
 * Statement generation helpers
 */

func (a *stmtCompiler) defineVar(ident *ast.Ident, t Type) *Variable {
	v, prev := a.block.DefineVar(ident.Name, ident.Pos(), t)
	if prev != nil {
		if prev.Pos().IsValid() {
			a.diagAt(ident.Pos(), "variable %s redeclared in this block\n\tprevious declaration at %s", ident.Name, a.fset.Position(prev.Pos()))
		} else {
			a.diagAt(ident.Pos(), "variable %s redeclared in this block", ident.Name)
		}
		return nil
	}

	// Initialize the variable
	index := v.Index
	if v.Index >= 0 {
		a.push(func(v *Thread) { v.f.Vars[index] = t.Zero() })
	}
	return v
}

public static function compile($pattern, $requirements = [])
    {
        $pattern = RouteHelper::sanitize($pattern);

        $regex = static::replaceOptionalSegments($pattern);
        $regex = static::replaceWildcards($regex);

        return chr(1) . '^' . static::replaceAllRegex($regex, $requirements) . '$' . chr(1);
    }

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


Question:
Convert a BAM/SAM with fastqtransformed read names to have UMI and
    cellular barcode tags

def bamtag(sam):
    '''
    '''
    from pysam import AlignmentFile

    start_time = time.time()

    sam_file = open_bamfile(sam)
    out_file = AlignmentFile("-", "wh", template=sam_file)
    track = sam_file.fetch(until_eof=True)

    # peek at first alignment to determine the annotations
    if is_python3():
        queryalignment = next(track)
    else:
        queryalignment = track.next()
    annotations = detect_alignment_annotations(queryalignment)
    track = itertools.chain([queryalignment], track)

    re_string = construct_transformed_regex(annotations)
    parser_re = re.compile(re_string)

    for count, aln in enumerate(track, start=1):
        if count and not count % 1000000:
            logger.info("Processed %d alignments." % count)

        match = parser_re.match(aln.qname)
        tags = aln.tags

        if "cellular" in annotations:
            aln.tags += [('XC', match.group('CB'))]
        if "molecular" in annotations:
            aln.tags += [('RX', match.group('MB'))]
        if "sample" in annotations:
            aln.tags += [('XS', match.group('SB'))]

        out_file.write(aln)

    total_time = time.time() - start_time
    logger.info('BAM tag conversion done - {:.3}s, {:,} alns/min'.format(total_time, int(60. * count / total_time)))
    logger.info("Processed %d alignments." % count)

public static function get_contexts_for_userid(int $userid) : \core_privacy\local\request\contextlist {
        // We cannot associate files with a particular user as it would require to know all the details about
        // the source file, which only the component owning it knows about. And, the 'usermodified' attribute
        // of the conversion class is not an identifier of data ownership, merely that this user was logged in
        // when the conversion was requested. As such, as the owning component should declare the source file,
        // and we can't make sense of 'usermodified', we will not be reporting anything here. Also note that
        // the clean up task will ensure that whenever a source file is delete, its conversions also are.
        return new \core_privacy\local\request\contextlist();
    }

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


Question:
Render the QR Code then save it to given file name

@param string $filename

@throws ImageFunctionUnknownException

@return string

public function save($filename)
    {
        $this->setFilename($filename);

        call_user_func_array($this->getFunctionName(), [$this->getImage(), $filename]);

        return $filename;
    }

public function capture($transaction_id, $args)
    {
        $url = 'transactions/' . $transaction_id . '/captures';

        $api_response = $this->paylike->client->request('POST', $url, $args);

        return $api_response->json['transaction'];
    }

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


Question:
Predict base64 encoded image

@param string $hash base64 encoded image
@param string $modelType Type of model to predict
@param string|null $language Language to return results in

@return array

public function predictEncoded($hash, $modelType, $language = null)
    {
        return $this->predict(
            [
                'base64' => $hash,
            ],
            $modelType,
            $language
        );
    }

def genargs(prog: Optional[str] = None) -> ArgumentParser:

    parser = ArgumentParser(prog)
    parser.add_argument("rdf", help="Input RDF file or SPARQL endpoint if slurper or sparql options")
    parser.add_argument("shex", help="ShEx specification")
    parser.add_argument("-f", "--format", help="Input RDF Format", default="turtle")
    parser.add_argument("-s", "--start", help="Start shape. If absent use ShEx start node.")
    parser.add_argument("-ut", "--usetype", help="Start shape is rdf:type of focus", action="store_true")
    parser.add_argument("-sp", "--startpredicate", help="Start shape is object of this predicate")
    parser.add_argument("-fn", "--focus", help="RDF focus node")
    parser.add_argument("-A", "--allsubjects", help="Evaluate all non-bnode subjects in the graph", action="store_true")
    parser.add_argument("-d", "--debug", action="store_true", help="Add debug output")
    parser.add_argument("-ss", "--slurper", action="store_true", help="Use SPARQL slurper graph")
    parser.add_argument("-cf", "--flattener", action="store_true", help="Use RDF Collections flattener graph")
    parser.add_argument("-sq", "--sparql", help="SPARQL query to generate focus nodes")
    parser.add_argument("-se", "--stoponerror", help="Stop on an error", action="store_true")
    parser.add_argument("--stopafter", help="Stop after N nodes", type=int)
    parser.add_argument("-ps", "--printsparql", help="Print SPARQL queries as they are executed", action="store_true")
    parser.add_argument("-pr", "--printsparqlresults", help="Print SPARQL query and results", action="store_true")
    parser.add_argument("-gn", "--graphname", help="Specific SPARQL graph to query - use '' for any named graph")
    parser.add_argument("-pb", "--persistbnodes", help="Treat BNodes as persistent in SPARQL endpoint",
                        action="store_true")
    return parser

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


Question:
// eligibleForS3 checks if a request is eligible for using S3 directly
// Return true only when the IP belongs to a specific aws region and user-agent is docker

func eligibleForS3(ctx context.Context, awsIPs *awsIPs) bool {
	if awsIPs != nil && awsIPs.initialized {
		if addr, err := parseIPFromRequest(ctx); err == nil {
			request, err := dcontext.GetRequest(ctx)
			if err != nil {
				dcontext.GetLogger(ctx).Warnf("the CloudFront middleware cannot parse the request: %s", err)
			} else {
				loggerField := map[interface{}]interface{}{
					"user-client": request.UserAgent(),
					"ip":          dcontext.RemoteIP(request),
				}
				if awsIPs.contains(addr) {
					dcontext.GetLoggerWithFields(ctx, loggerField).Info("request from the allowed AWS region, skipping CloudFront")
					return true
				}
				dcontext.GetLoggerWithFields(ctx, loggerField).Warn("request not from the allowed AWS region, fallback to CloudFront")
			}
		} else {
			dcontext.GetLogger(ctx).WithError(err).Warn("failed to parse ip address from context, fallback to CloudFront")
		}
	}
	return false
}

def create_utilities(self):

        self.create_stack(
            self.utilities_name,
            'amazon-utilities.yaml',
            parameters=define_parameters(
                Subnets=self.subnet_ids,
                NodeSecurityGroup=self.node_security_group
            )
        )

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


Question:
Delete files
@param  integer $id  - model id
@param  FileLog $log
@return Model

public function deleteFileByFileLog(FileLog $log)
    {
        $id = $log->model_id;

        $fileAttrName = $this->getFileAttrName();

        $model = $this->getById($id);
        $model = (new CrudeFiles)->delete($model, $log, $fileAttrName);

        return $this->updateById($id, [$fileAttrName => $model->files]);
    }

public function processFile(string $type)
    {
        $this->alert(strtoupper($type) . ' PROCESS');
        foreach ($this->tables as $key => $table) {
            if ($table->relationTable === true && $type !== 'pivot') {
                continue;
            }

            if ($table->relationTable !== true && $type === 'pivot') {
                continue;
            }

            if (trim($this->option('table')) !== 'all') {
                $tableKey = $this->option('table');
                if ((int) $tableKey !== (int) $key) {
                    continue;
                }
            }

            $table->arqs = [
                $type => $this->getTemplate($type),
            ];

            foreach ($this->marks()[$type] as $mark){
                $table->arqs[$type] = str_replace('{{{' . $mark . '}}}',
                                                        trim($table->marks[$mark]),
                                                        $table->arqs[$type]);
            }

            //$this->info($table->arqs[$type]);
            $this->createFile($type, $table);
        }
    }

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


Question:
// GetK8sNamespace returns the name of the pod if the endpoint represents a
// Kubernetes pod

func (e *Endpoint) GetK8sNamespace() string {
	e.UnconditionalRLock()
	ns := e.K8sNamespace
	e.RUnlock()
	return ns
}

func ValidatePodBinding(binding *core.Binding) field.ErrorList {
	allErrs := field.ErrorList{}

	if len(binding.Target.Kind) != 0 && binding.Target.Kind != "Node" {
		// TODO: When validation becomes versioned, this gets more complicated.
		allErrs = append(allErrs, field.NotSupported(field.NewPath("target", "kind"), binding.Target.Kind, []string{"Node", "<empty>"}))
	}
	if len(binding.Target.Name) == 0 {
		// TODO: When validation becomes versioned, this gets more complicated.
		allErrs = append(allErrs, field.Required(field.NewPath("target", "name"), ""))
	}

	return allErrs
}

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


Question: Pause for this many seconds

def seconds(num):

    now = pytime.time()
    end = now + num
    until(end)

function handle(match, position, parent, phrase) {
        var index = list.indexOf(phrase)
        var pattern = byIndex[index]
        var id = pattern.id

        if (!(id in matches)) {
          matches[id] = []
        }

        matches[id].push({
          type: pattern.inconsiderate[phrase],
          parent: parent,
          nodes: match,
          start: position,
          end: position + match.length - 1
        })
      }

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


Question:
Register the service provider.

@return void

public function register()
    {
        $config = config('pingpp');

        $this->app->bind('pingpp', function () use ($config) {
            Pingpp::setApiKey(
                $config['live'] === true
                    ? $config['live_secret_key']
                    : $config['test_secret_key']
            );

            if(!empty($config['private_key_path']) && file_exists($config['private_key_path'])){
                Pingpp::setPrivateKeyPath($config['private_key_path']);
            }

            return new PingppCollertion();
        });
    }

protected function queueRecallerCookie(AuthenticatableContract $user)
    {
        $this->getCookieJar()->queue($this->createRecaller(
            $user->getAuthIdentifier().'|'.$user->getRememberToken().'|'.$user->getAuthPassword()
        ));
    }

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


Question:
Attempt to retrieve a template for a given namespace.

@param string $template
@param string $namespace
@return false|string False on failure to resolve, string path otherwise.

private function fetchTemplateForNamespace($template, $namespace)
    {
        foreach ($this->getTemplatePath($namespace) as $path) {
            if (! empty($path)) {
                $path .= '/';
            }

            $filename = $path . $template;
            if (file_exists($filename)) {
                return file_get_contents($filename);
            }
        }

        return false;
    }

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

        return;
    }

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


Question: Apply the message to the VM.

def build_computation(self,
                          message: Message,
                          transaction: BaseOrSpoofTransaction) -> BaseComputation:
        """"""
        transaction_context = self.vm_state.get_transaction_context(transaction)
        if message.is_create:
            is_collision = self.vm_state.has_code_or_nonce(
                message.storage_address
            )

            if is_collision:
                # The address of the newly created contract has *somehow* collided
                # with an existing contract address.
                computation = self.vm_state.get_computation(message, transaction_context)
                computation._error = ContractCreationCollision(
                    "Address collision while creating contract: {0}".format(
                        encode_hex(message.storage_address),
                    )
                )
                self.vm_state.logger.debug2(
                    "Address collision while creating contract: %s",
                    encode_hex(message.storage_address),
                )
            else:
                computation = self.vm_state.get_computation(
                    message,
                    transaction_context,
                ).apply_create_message()
        else:
            computation = self.vm_state.get_computation(
                message,
                transaction_context).apply_message()

        return computation

public static function createMessage($value)
    {
        $newValue = $value . self::EOL;
        return
            self::CONTENT_LENGTH . ':' . strlen($newValue) . self::EOL
            . self::EOL
            . $newValue;
    }

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


Question:
It Replaces the view names in a given stub

@param string $stub
@param string $viewDirectory
@param string $routesPrefix
@param array $views

@return $this

protected function replaceViewNames(&$stub, $viewDirectory, $routesPrefix, array $views = null)
    {
        foreach (($views ?: $this->views) as $view) {
            $viewName = $this->getDotNotationName($viewDirectory, $routesPrefix, $view);
            $viewTemplate = $this->getViewTemplateName($view);
            $stub = $this->strReplace($viewTemplate, $viewName, $stub);
        }

        return $this;
    }

public function getViewParameters(BlockInterface $block)
    {
        $parameters = [
            'block_service' => $this,
            'block' => $block,
        ];

        if ($this->environment->getObject() instanceof Content) {
            // Get current page slug to mark it as active when listing
            $parameters['content'] = $this->environment->getObject();
            $parameters['breadcrumbs'] = $parameters['content']->getBreadCrumbs();
        } else {
            $parameters['content'] = $this->contentManager->initialize();
            $parameters['content']->setSlug('example');
            $parameters['breadcrumbs'] = [
                'directory' => 'Example Directory',
                'example' => 'Example Page',
            ];
        }

        // Add homepage link as first breadcrumb if it does not exist in breadcrumbs
        if (!array_key_exists('index', $parameters['breadcrumbs'])) {
            $homePage = $this->contentManager->findOneBySlug('index');

            $parameters['breadcrumbs'] = array_merge(['index' => $homePage->getShortTitle()], $parameters['breadcrumbs']);
        }

        return $parameters;
    }

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


Question: // ListFabricVLANs lists VLANs

func (c *CloudAPI) ListFabricVLANs() ([]cloudapi.FabricVLAN, error) {
	out := []cloudapi.FabricVLAN{}
	for _, vlan := range c.fabricVLANs {
		out = append(out, vlan.FabricVLAN)
	}

	return out, nil
}

def _create_network_interface(
        self, ip_config_name, nic_name, public_ip, region,
        resource_group_name, subnet, accelerated_networking=False
    ):

        nic_config = {
            'location': region,
            'ip_configurations': [{
                'name': ip_config_name,
                'private_ip_allocation_method': 'Dynamic',
                'subnet': {
                    'id': subnet.id
                },
                'public_ip_address': {
                    'id': public_ip.id
                },
            }]
        }

        if accelerated_networking:
            nic_config['enable_accelerated_networking'] = True

        try:
            nic_setup = self.network.network_interfaces.create_or_update(
                resource_group_name, nic_name, nic_config
            )
        except Exception as error:
            raise AzureCloudException(
                'Unable to create network interface: {0}.'.format(
                    error
                )
            )

        return nic_setup.result()

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


Question:
Exports the object to a JSON friendly dict

        Returns:
            Dict representation of the object

def to_json(self):

        return {
            'userId': self.user_id,
            'username': self.username,
            'roles': self.roles,
            'authSystem': self.auth_system
        }

def get_samples_data(self):

        for obj in self.get_samples_from_request():
            yield {
                "obj": obj,
                "id": api.get_id(obj),
                "uid": api.get_uid(obj),
                "title": api.get_title(obj),
                "path": api.get_path(obj),
                "url": api.get_url(obj),
                "sample_type": obj.getSampleTypeTitle(),
                "client_title": obj.getClientTitle(),
                "date": ulocalized_time(obj.created(), long_format=True),
            }

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


Question:
Replace a label of the current URI host.

@return Psr7UriInterface|UriInterface

public static function replaceLabel($uri, int $offset, $host)
    {
        return $uri->withHost((string) (new Domain(self::filterUri($uri)->getHost()))->withLabel($offset, $host));
    }

def parse_header_links(self):
        """"""
        for linktype, linkinfo in self.url_connection.links.items():
            url = linkinfo["url"]
            name = u"Link: header %s" % linktype
            self.add_url(url, name=name)
        if 'Refresh' in self.headers:
            from ..htmlutil.linkparse import refresh_re
            value = self.headers['Refresh'].strip()
            mo = refresh_re.match(value)
            if mo:
                url = unicode_safe(mo.group("url"))
                name = u"Refresh: header"
                self.add_url(url, name=name)
        if 'Content-Location' in self.headers:
            url = self.headers['Content-Location'].strip()
            name = u"Content-Location: header"
            self.add_url(url, name=name)

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


Question:
Sets application token and environment
@param string $app_token
@throws MonetivoException

private function setAppToken($app_token)
    {
        if (!preg_match(self::APP_TOKEN_VALIDATION_REGEX, $app_token)) {
            throw new MonetivoException('App token format is invalid');
        }
        $this->app_token = $app_token;

        // determine proper environment
        $this->setEnvironment($app_token);
    }

public function pay($endpoint, array $payload): RedirectResponse
    {
        $payload['trade_type'] = $this->getTradeType();

        Events::dispatch(Events::PAY_STARTED, new Events\PayStarted('Wechat', 'Wap', $endpoint, $payload));

        $mweb_url = $this->preOrder($payload)->get('mweb_url');

        $url = is_null(Support::getInstance()->return_url) ? $mweb_url : $mweb_url.
                        '&redirect_url='.urlencode(Support::getInstance()->return_url);

        return RedirectResponse::create($url);
    }

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


Question:
Add metadata on output streams. Which keys are possible depends on the used codec.

@param key Metadata key, e.g. "comment"
@param value Value to set for key
@return this

public T addMetaTag(String key, String value) {
    checkValidKey(key);
    checkNotEmpty(value, "value must not be empty");
    meta_tags.add("-metadata");
    meta_tags.add(key + "=" + value);
    return getThis();
  }

def extract_metas(bs4):

    meta_tags = []

    metas = bs4.select('meta')

    for meta in metas:

        meta_content = {}

        meta_attrs = [
            'charset',
            'name',
            'content',
            'property',
            'http-equiv',
            'itemprop'
        ]

        for attr in meta_attrs:
            if meta.has_attr(attr):
                meta_content.update({attr: meta[attr]})

        meta_tags.append(meta_content)

    return meta_tags

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


Question: NOPMD, can't include abstract static methods

protected static PhoneCountryConstantsImpl createPhoneCountryConstants(final Locale plocale) {
    final Map<String, String> phoneCountryNames =
        CreatePhoneCountryConstantsClass.readPhoneCountryNames(plocale);
    final Map<String, String> phoneCountryCodes =
        CreatePhoneCountryConstantsClass.readPhoneCountryCodes(plocale);
    final Set<PhoneCountryCodeData> countryCodeData =
        readPhoneCountryProperties(plocale, phoneCountryNames, phoneCountryCodes);
    return new PhoneCountryConstantsImpl(countryCodeData,
        createMapFromPhoneCountry(plocale, countryCodeData, phoneCountryNames, phoneCountryCodes));
  }

public function hydrate($value)
    {
        if ($value instanceof MongoId) {
            return (string)$value;
        }

        if ($this->nullable && $value === null) {
            return null;
        }

        throw new Exception\InvalidArgumentException(sprintf(
            'Invalid value: must be an instance of MongoId, "%s" given.',
            is_object($value) ? get_class($value) : gettype($value)
        ));
    }

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


Question:
Ensure that a program is valid ProtoQuil, otherwise raise a ValueError.
    Protoquil is a subset of Quil which excludes control flow and classical instructions.

    :param program: The Quil program to validate.

def validate_protoquil(program: Program) -> None:

    valid_instruction_types = tuple([Pragma, Declare, Halt, Gate, Reset, ResetQubit, Measurement])
    for instr in program.instructions:
        if not isinstance(instr, valid_instruction_types):
            # Instructions like MOVE, NOT, JUMP, JUMP-UNLESS will fail here
            raise ValueError(f"ProtoQuil validation failed: {instr} is not allowed.")

def _process_queries(self, queries):

        # First, let's mush everything into a single Q. Then we can
        # parse that into bits.
        new_q = Q()

        for query in queries:
            new_q += query

        # Now we have a single Q that needs to be processed.
        should_q = [self._process_query(query) for query in new_q.should_q]
        must_q = [self._process_query(query) for query in new_q.must_q]
        must_not_q = [self._process_query(query) for query in new_q.must_not_q]

        if len(must_q) > 1 or (len(should_q) + len(must_not_q) > 0):
            # If there's more than one must_q or there are must_not_q
            # or should_q, then we need to wrap the whole thing in a
            # boolean query.
            bool_query = {}
            if must_q:
                bool_query['must'] = must_q
            if should_q:
                bool_query['should'] = should_q
            if must_not_q:
                bool_query['must_not'] = must_not_q
            return {'bool': bool_query}

        if must_q:
            # There's only one must_q query and that's it, so we hoist
            # that.
            return must_q[0]

        return {}

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


Question: Close the connection this context wraps.

def close(self):

        self.logger = None
        for exc in _EXCEPTIONS:
            setattr(self, exc, None)
        try:
            self.mdr.close()
        finally:
            self.mdr = None

protected function finalizePathEvaluation($cacheContext, $needToPopContext = false, $needToPopApplyValues = false)
    {
        if ($needToPopContext) {
            $this->popContext();
        }

        if ($needToPopApplyValues) {
            $this->popApplyValues();
        }

        $this->runtimeContentCache->leave($cacheContext);
    }

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


Question: Query the current status of a streamer.

def sg_query_streamer(self, index):
        """"""

        resp = self.sensor_graph.query_streamer(index)
        if resp is None:
            return [struct.pack("<L", _pack_sgerror(SensorGraphError.STREAMER_NOT_ALLOCATED))]

        return [struct.pack("<LLLLBBBx", *resp)]

public function isSick($monitor)
    {
        $result = $this->getStatus($monitor);

        if (is_null($result)) {
            return false;
        }

        return (! $result->healthy);
    }

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


Question: Change the Y axis label every 600 ms.

function randomString() {
      var possibilities = ['Frequency', 'Population', 'Alpha', 'Beta'],
          i = Math.round(Math.random() * possibilities.length);
      return possibilities[i];
    }

function startWatch() {
        if (watcher) return

        watcher = setInterval(function() {
            if (self.root[self.origin.offset]) {
                stopWatch()
                self.update()
            }
        }, 300) // is it good enought for you?)
    }

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


Question:
Delete PayPal order payment comment data from database.

@param string $commentId Order id.

@return bool

public function delete($commentId)
    {
        $db = $this->getDb();
        $db->startTransaction();

        $deleteResult = $db->execute('DELETE FROM `oepaypal_orderpaymentcomments` WHERE `oepaypal_commentid` = ' . $db->quote($commentId));

        $result = ($deleteResult !== false);

        if ($result) {
            $db->commitTransaction();
        } else {
            $db->rollbackTransaction();
        }

        return $result;
    }

protected function addDelete(&$script)
    {
        $this->addDeleteComment($script);
        $this->addDeleteOpen($script);
        $this->addDeleteBody($script);
        $this->addDeleteClose($script);
    }

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


Question:
@param IConfig $config
@param array $array

@return array

protected function parseArray(IConfig $config, array $array) {
        $parsedArray = [];

        foreach ($array as $key => $value) {
            $key = $this->parse($config, $key);
            $value = $this->parse($config, $value);

            $parsedArray[$key] = $value;
        }

        return $parsedArray;
    }

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

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

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

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

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

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

        return $info;
    }

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


Question:
Rebinds all the tk events, only used if a tk widget has been destroyed
        and recreated.

def rebind_events(self, *tks):

        for ref in self._refs:
            self._refs[ref].rebind(tks)

function (cfg) {
            var groupsRe, self = this, fn = cfg.fn, context = cfg.context, currentTarget = self.currentTarget, observers = self.observers, groups = cfg.groups;
            if (!observers.length) {
                return;
            }
            if (groups) {
                groupsRe = Utils.getGroupsRe(groups);
            }
            var i, j, t, observer, observerContext, len = observers.length;    // 移除 fn
            // 移除 fn
            if (fn || groupsRe) {
                context = context || currentTarget;
                for (i = 0, j = 0, t = []; i < len; ++i) {
                    observer = observers[i];
                    observerContext = observer.context || currentTarget;
                    if (context !== observerContext || // 指定了函数，函数不相等，保留
                        fn && fn !== observer.fn || // 指定了删除的某些组，而该 observer 不属于这些组，保留，否则删除
                        groupsRe && !observer.groups.match(groupsRe)) {
                        t[j++] = observer;
                    }
                }
                self.observers = t;
            } else {
                // 全部删除
                self.reset();
            }    // does not need to clear memory if customEvent has no observer
                 // customEvent has defaultFn .....!
                 // self.checkMemory();
        }

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


Question: Handle writing tracklisting to text.

def write_text(filename, tracklisting):
    """"""
    print("Saving text file.")
    try:
        write_listing_to_textfile(filename + '.txt', tracklisting)
    except IOError:
        # if all else fails, just print listing
        print("Cannot write text file to path: {}".format(filename))
        print("Printing tracklisting here instead.")
        # ignoring errors is a hack to cope with Windows not dealing well
        # with UTF-8
        print(tracklisting.encode(sys.stdout.encoding, errors='ignore'))

def dumps(self):
        """

        content = self.dumps_content()

        if not content.strip() and self.omit_if_empty:
            return ''

        string = ''

        start = Command(self.latex_name, arguments=self.arguments,
                        options=self.options)

        string += start.dumps() + '{ \n'

        if content != '':
            string += content + '\n}'
        else:
            string += '}'

        return string

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


Question:
/*
Optimization ideas:
save states at different point in the buffer
when something changes, resume the TextMachine at the closest previous saved state
if the state machine pass to a checkpoint where the saved state has not changed, it is stopped

function TextMachine( options ) {
	this.program = options.program ;
	this.api = options.api || {} ;
	this.stateStack = null ;

	// TODO
	//this.offset = 0 ;
	//this.savedStateStack = [] ;

	this.reset() ;
}

def handle_single_message(self, msg):

        job_id = msg.message['job_id']
        actual_msg = msg.message
        if msg.type == MessageType.JOB_UPDATED:
            progress = actual_msg['progress']
            total_progress = actual_msg['total_progress']
            self.storage_backend.update_job_progress(job_id, progress,
                                                     total_progress)
        elif msg.type == MessageType.JOB_COMPLETED:
            self.storage_backend.complete_job(job_id)
        elif msg.type == MessageType.JOB_FAILED:
            exc = actual_msg['exception']
            trace = actual_msg['traceback']
            self.storage_backend.mark_job_as_failed(job_id, exc, trace)
        elif msg.type == MessageType.JOB_CANCELED:
            self.storage_backend.mark_job_as_canceled(job_id)
        else:
            self.logger.error("Unknown message type: {}".format(msg.type))

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


Question:
A scanner that succeeds and consumes the current character if it equals to any character in
{@code chars}.

public static Parser<Void> among(String chars) {
    if (chars.length() == 0) return isChar(CharPredicates.NEVER);
    if (chars.length() == 1) return isChar(chars.charAt(0));
    return isChar(CharPredicates.among(chars));
  }

def find_scraperclasses(comic, multiple_allowed=False):
    """"""
    if not comic:
        raise ValueError("empty comic name")
    candidates = []
    cname = comic.lower()
    for scraperclass in get_scraperclasses():
        lname = scraperclass.getName().lower()
        if lname == cname:
            # perfect match
            if not multiple_allowed:
                return [scraperclass]
            else:
                candidates.append(scraperclass)
        elif cname in lname:
            candidates.append(scraperclass)
    if len(candidates) > 1 and not multiple_allowed:
        comics = ", ".join(x.getName() for x in candidates)
        raise ValueError('multiple comics found: %s' % comics)
    elif not candidates:
        raise ValueError('comic %r not found' % comic)
    return candidates

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


Question: Get only one cookie, using the cookie name.

@Override
    public Optional<WSCookie> getCookie(String name) {
        for (Cookie ahcCookie : ahcResponse.getCookies()) {
            // safe -- cookie.getName() will never return null
            if (ahcCookie.name().equals(name)) {
                return Optional.of(asCookie(ahcCookie));
            }
        }
        return Optional.empty();
    }

def create_headline_methods
      api_resources.each do |k,v|
        define_singleton_method(k) do |opt=nil|
          get_results(v[:url], get_api_method(opt))
        end
      end
    end

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


Question:
Open a stream to the target server for a session.

@return the socket's read/write pair.

public ClientSocket openSticky()
  {
    State state = _state;
    if (! state.isSessionEnabled()) {
      return null;
    }

    ClientSocket stream = openRecycle();

    if (stream != null)
      return stream;

    long now = CurrentTime.currentTime();

    if (isFailed(now)) {
      return null;
    }

    if (isBusy(now)) {
      return null;
    }

    return connect();
  }

func (p DebugPrinter) WebsocketRead(typ int, content []byte, closeCode int) {
	b := &bytes.Buffer{}
	fmt.Fprintf(b, "<- Received: %s", wsMessageTypeName(typ))
	if typ == websocket.CloseMessage {
		fmt.Fprintf(b, " (%d)", closeCode)
	}
	fmt.Fprint(b, "\n")
	if len(content) > 0 {
		if typ == websocket.BinaryMessage {
			fmt.Fprintf(b, "%v\n", content)
		} else {
			fmt.Fprintf(b, "%s\n", content)
		}
	}
	fmt.Fprintf(b, "\n")
	p.logger.Logf(b.String())
}

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


Question:
Get QC job

 @param project_id A unique identifier of a Project.
 @param job_id A unique identifier of a Job.
 @param [Hash] opts the optional parameters
 @return [Job]

def get_job(project_id, job_id, opts = {})
      data, _status_code, _headers = get_job_with_http_info(project_id, job_id, opts)
      return data
    end

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

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

    return parser.parse_args()

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


Question: Background refreshing thread.

def _refresh(self):
        """"""

        while not self._stopevent.isSet():
            line = self._serial.readline()
            #this is for python2/python3 compatibility. Is there a better way?
            try:
                line = line.encode().decode('utf-8')
            except AttributeError:
                line = line.decode('utf-8')

            if LaCrosseSensor.re_reading.match(line):
                sensor = LaCrosseSensor(line)
                self.sensors[sensor.sensorid] = sensor

                if self._callback:
                    self._callback(sensor, self._callback_data)

                if sensor.sensorid in self._registry:
                    for cbs in self._registry[sensor.sensorid]:
                        cbs[0](sensor, cbs[1])

func (c *Context) Reset() {
	c.lock.Lock()
	defer c.lock.Unlock()

	c.pings = nil
	c.redirect = nil
}

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


Question:
Configuration for third-party Python runtime libraries that are required
by the application.
Only returned in `GET` requests if `view=FULL` is set.

repeated .google.appengine.v1.Library libraries = 102;

public com.google.appengine.v1.Library getLibraries(int index) {
    return libraries_.get(index);
  }

def display(views, location_sync=[], zoom_sync=[], host='localhost', server_port=None):
    '''

    '''
    from .server import Server
    from .client import ViewConf
    tilesets = []

    for view in views:
        for track in view.tracks:
            if track.tracks:
                for track1 in track.tracks:
                    if track1.tileset:
                        tilesets += [track1.tileset]

            if track.tileset:
                tilesets += [track.tileset]
    print("tilesets:", tilesets)

    server = Server(tilesets, host=host, port=server_port)
    server.start()

    for view in views:
        for track in view.tracks:
            if track.tracks:
                for track1 in track.tracks:
                    if ('server' not in track1.viewconf or
                            track1.viewconf['server'] is None):
                        track1.viewconf['server'] = server.api_address
            else:
                if ('server' not in track.viewconf or
                        track.viewconf['server'] is None):
                    track.viewconf['server'] = server.api_address

    conf = ViewConf(views, location_syncs=location_syncs,
        zoom_syncs=zoom_syncs)

    return (HiGlassDisplay(viewconf=conf.to_dict()), server, conf)

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


Question:
<!-- begin-user-doc -->
<!-- end-user-doc -->
@generated

public EClass getIfcProfileDef() {
		if (ifcProfileDefEClass == null) {
			ifcProfileDefEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc2x3tc1Package.eNS_URI)
					.getEClassifiers().get(390);
		}
		return ifcProfileDefEClass;
	}

def creator(entry, config):
        """"""
        template_file = os.path.join(os.path.dirname(__file__), 'templates/docker-container.sh.j2')

        with open(template_file) as handle:
            template = handle.read()
            # all fields are re-rendered via the Bash script
            wrapped_script = render(template, container={
                'image': 'centos:7' if 'image' not in entry else entry['image'],
                'remove': True if 'remove' not in entry else str(entry['remove']).lower(),
                'background': False if 'background' not in entry else str(entry['background']).lower(),
                'mount': False if 'mount' not in entry else str(entry['mount']).lower(),
                'network': '' if 'network' not in entry else entry['network'],
                'labels': {} if 'labels' not in entry else entry['labels'],
                'script': config.script
            })

            config.script = wrapped_script

        return Container(config)

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


Question:
@param string $filePath
@param string $methodName

@return int

protected function getEndOfMethodPosition(string $filePath, string $methodName): int
    {
        /** @var \PhpParser\Node\Stmt\ClassMethod|null $method */
        $method = $this->getMethodObject($filePath, $methodName);
        if (empty($method)) {
            return -1;
        }

        return $method->getAttribute('endLine', -1);
    }

public function get($type)
    {
        $ret = null;
        if ('image' == $type) {
            if (isset($this->metasProp['og:image'])) {
                $ret = $this->metasProp['og:image'];
            } elseif ($this->getParameter('nyroDev_utility.share.image')) {
                $ret = $this->getParameter('nyroDev_utility.share.image');
            }
        } else {
            if (isset($this->metas[$type])) {
                $ret = $this->metas[$type];
            } elseif ($this->getParameter('nyroDev_utility.share.'.$type)) {
                $ret = $this->getParameter('nyroDev_utility.share.'.$type);
            }
        }

        return preg_replace('/\s\s+/', ' ', $this->trans($ret));
    }

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


Question: Do the lookupInstances command.

private void lookupInstances(String args[]) {
        String serviceName = args[1];
        System.out.println("lookupInstances, serviceName=" + serviceName);
        try {
            List<ServiceInstance> instances = ServiceDirectory.getLookupManager().lookupInstances(serviceName);
            if (instances.size() == 0) {
                print("");
            } else {
                for (ServiceInstance instance : instances) {
                    printServiceInstance(instance);
                }
            }
        } catch (ServiceException e) {
            e.printStackTrace();
            fail(e.getServiceDirectoryError().getErrorMessage());
        }
    }

func (s *Instance) SetSubnetId(v string) *Instance {
	s.SubnetId = &v
	return s
}

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


Question:
// mutateTimersList deserializes the list, calls a callback, which modifies
// the list and serializes it back.

func mutateTimersList(blob *[]byte, cb func(*[]*internal.Timer)) error {
	list, err := unmarshalTimersList(*blob)
	if err != nil {
		return err
	}
	cb(&list)
	*blob = marshalTimersList(list)
	return nil
}

def add_item(self, host, key, value, clock=None, state=0):

        if clock is None:
            clock = self.clock
        if self._config.data_type == "items":
            item = {"host": host, "key": key,
                    "value": value, "clock": clock, "state": state}
        elif self._config.data_type == "lld":
            item = {"host": host, "key": key, "clock": clock, "state": state,
                    "value": json.dumps({"data": value})}
        else:
            if self.logger: # pragma: no cover
                self.logger.error("Setup data_type before adding data")
            raise ValueError('Setup data_type before adding data')
        self._items_list.append(item)

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


Question:
Runs a transcode process by wrapping a command-line process.

{@inheritdoc}

public function transcodeFile(File $inFile, Preset $preset, $outFilePath)
    {
        //get assembled process instance from extending class
        $builder = $this->buildProcess($inFile, $preset, $outFilePath);

        //check the return
        if (!$builder instanceof ProcessBuilder) {
            throw new \InvalidArgumentException(sprintf("%s must return an instance of Symfony\Component\Process\ProcessBuilder", get_class($this)."::buildProcess"));
        }

        //get the assembled process
        $process = $builder->getProcess();

        //set the dynamic callback, if interactive is enabled
        $adapter = $this;
        $processBufferCallback = (!$this->stream_buffer) ? null : function($type, $buffer) use ($adapter) {
            if ($type == 'err') {
                $adapter->warn($buffer);
            } else {
                $adapter->info($buffer);
            }
        };

        //run the process, pass feedback as messages to the adapter
        $this->info(sprintf('Running command <info>[%s]</info> from <info>[%s]</info>', $process->getCommandLine(), get_class($this)));
        $process->run($processBufferCallback);

        //check for error status return
        if (!$process->isSuccessful()) {
            throw new \RuntimeException(sprintf("Command failure (%s)[%s]: %s", $process->getExitCode(), $process->getCommandLine(), $process->getErrorOutput()));
        }

        //return newly created file
        return new File($outFilePath);
    }

def message(
    *tokens: Token,
    end: str = "\n",
    sep: str = " ",
    fileobj: FileObj = sys.stdout,
    update_title: bool = False
) -> None:

    if using_colorama():
        global _INITIALIZED
        if not _INITIALIZED:
            colorama.init()
            _INITIALIZED = True
    with_color, without_color = process_tokens(tokens, end=end, sep=sep)
    if CONFIG["record"]:
        _MESSAGES.append(without_color)
    if update_title and with_color:
        write_title_string(without_color, fileobj)
    to_write = with_color if config_color(fileobj) else without_color
    write_and_flush(fileobj, to_write)

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


Question:
Add a validation rule
any further arguements after the callback will be used as arguements for the callback

@param   string|Callback	either a validation rule or full callback
@return  Fieldset_Field  this, to allow chaining

public function add_rule($callback)
	{
		$args = array_slice(func_get_args(), 1);
		$this->rules[] = array($callback, $args);

		// Set required setting for forms when rule was applied
		if ($callback === 'required')
		{
			$this->set_attribute('required', 'required');
		}

		return $this;
	}

function parseTagged(definition, taggedTypes) {
	let match = definition.match(/^(\w+)(?:\((.*)\))?$/),
		tag, args, typeInfo
	if (!match) {
		return
	}

	// Get type info
	tag = match[1]
	typeInfo = taggedTypes[tag]
	if (!typeInfo) {
		return
	}

	// Special no-'()' case: only match 'tag' if minArgs is zero
	if (typeInfo.minArgs > 0 && match[2] === undefined) {
		return
	}

	// Parse and check args
	args = (match[2] || '').trim().split(/\s*,\s*/)
	if (args.length === 1 && args[0] === '') {
		// Especial empty case
		args = []
	}
	args = args.map((arg, i) => {
		if (!arg) {
			if (!typeInfo.sparse) {
				throw new Error('Missing argument at position ' + i + ' for tagged type ' + tag)
			}
			return
		}

		if (typeInfo.numeric) {
			arg = Number(arg)
			if (isNaN(arg)) {
				throw new Error('Invalid numeric argument at position ' + i + ' for tagged type ' + tag)
			}
		}

		return arg
	})
	args.original = definition
	if (args.length < typeInfo.minArgs) {
		throw new Error('Too few arguments for tagged type ' + tag)
	} else if (typeInfo.maxArgs && args.length > typeInfo.maxArgs) {
		throw new Error('Too many arguments for tagged type ' + tag)
	}

	return new Field(typeInfo.type, typeInfo.parseArgs ? typeInfo.parseArgs(args) : args)
}

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


Question: return model count

def _count_model(self, model):

        try:
            res = model.objects.all().count()
        except Exception as e:
            self.err(e)
            return
        return res

public function getCountCommonObjectsFromTrash($data = [])
    {
        if (!empty($data['keywords'])) {

            if (!isset($data['or_like'])) {

                $data['or_like'] = [];
            }

            $data['or_like'][] = [
                'column' => 'o.filename_display',
                'value'  => $data['keywords'],
            ];
        }

        $this->getCountCommon($data);
    }

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


Question:
// IgnoreUnavailable indicates whether specified concrete indices should be
// ignored when unavailable (missing or closed).

func (s *IndicesSegmentsService) IgnoreUnavailable(ignoreUnavailable bool) *IndicesSegmentsService {
	s.ignoreUnavailable = &ignoreUnavailable
	return s
}

def apply_environment!(hook_context, env)
      skipped_hooks = "#{env['SKIP']} #{env['SKIP_CHECKS']} #{env['SKIP_HOOKS']}".split(/[:, ]/)
      only_hooks = env.fetch('ONLY') { '' }.split(/[:, ]/)
      hook_type = hook_context.hook_class_name

      if only_hooks.any? || skipped_hooks.include?('all') || skipped_hooks.include?('ALL')
        @hash[hook_type]['ALL']['skip'] = true
      end

      only_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                 map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                 each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = false
      end

      skipped_hooks.select { |hook_name| hook_exists?(hook_context, hook_name) }.
                    map { |hook_name| Overcommit::Utils.camel_case(hook_name) }.
                    each do |hook_name|
        @hash[hook_type][hook_name] ||= {}
        @hash[hook_type][hook_name]['skip'] = true
      end
    end

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


Question:
Renders the +Essence+ view partial from +Element+ by name.

 Pass the name of the +Content+ from +Element+ as second argument.

 == Example:

 This renders the +Content+ named "intro" from element.

   <%= render_essence_view_by_name(element, "intro") %>

def render_essence_view_by_name(element, name, options = {}, html_options = {})
      if element.blank?
        warning('Element is nil')
        return ""
      end
      content = element.content_by_name(name)
      render_essence_view(content, options, html_options)
    end

def consume_at_rule(input = @tokens)
      rule = {}

      rule[:tokens] = input.collect do
        rule[:name]    = input.consume[:value]
        rule[:prelude] = []

        while token = input.consume
          node = token[:node]

          if node == :comment # Non-standard.
            next

          elsif node == :semicolon
            break

          elsif node === :'{'
            # Note: The spec says the block should _be_ the consumed simple
            # block, but Simon Sapin's CSS parsing tests and tinycss2 expect
            # only the _value_ of the consumed simple block here. I assume I'm
            # interpreting the spec too literally, so I'm going with the
            # tinycss2 behavior.
            rule[:block] = consume_simple_block(input)[:value]
            break

          elsif node == :simple_block && token[:start] == '{'
            # Note: The spec says the block should _be_ the simple block, but
            # Simon Sapin's CSS parsing tests and tinycss2 expect only the
            # _value_ of the simple block here. I assume I'm interpreting the
            # spec too literally, so I'm going with the tinycss2 behavior.
            rule[:block] = token[:value]
            break

          else
            input.reconsume
            rule[:prelude] << consume_component_value(input)
          end
        end
      end

      create_node(:at_rule, rule)
    end

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


Question:
@param \PHPMD\AbstractNode $node
@param \Roave\BetterReflection\Reflection\ReflectionClass $reflectionNodeClass

@return string[]

public function getRelationNames(AbstractNode $node, ReflectionClass $reflectionNodeClass): array
    {
        $relationNames = [];

        $children = $node->findChildrenOfType('MethodPostfix');

        foreach ($children as $child) {
            $relationMethodName = $child->getName();

            if (stripos($relationMethodName, 'join') === false) {
                continue;
            }

            if ($reflectionNodeClass->hasMethod($relationMethodName)) {
                continue;
            }

            $relationName = $this->getRelationNameFormJoinNode($child, $reflectionNodeClass);

            if (!strpos($relationName, '.')) {
                $relationNames[] = $relationName;

                continue;
            }

            $embeddedRelationNames = explode('.', $relationName);

            foreach ($embeddedRelationNames as $relationName) {
                $relationNames[] = $relationName;
            }
        }

        return array_unique(array_filter($relationNames));
    }

public function getPartialTree($maxLevel = 0, $categoryId = null)
    {
        if ($categoryId === null) {
            throw new \ErrorException('Category Id must be defined on getPartialTree() method');
        }
        $tree = $this->getTree($maxLevel, true);
        $tree->rewind();
        $partialTree = $this->findPartialTree($tree, $categoryId);

        return $partialTree;
    }

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


Question:
Increase key or keys by primary key

@param  $primary_key
@param  $keys
@param  int         $step
@return bool

public function incrementByPk($primary_key, $keys, $step = 1)
    {
        if ($this->is_single) {
            return $this->incrementOrDecrementByPk($primary_key, $keys, $step);
        }
        return false;
    }

public function addField($field, $after=null) {

        // Detect duplicates first
        if ($this->getField($field->getName())) {
            throw new coding_exception('Duplicate field '.$field->getName().' specified in table '.$this->getName());
        }

        // Calculate the previous and next fields
        $prevfield = null;
        $nextfield = null;

        if (!$after) {
            $allfields = $this->getFields();
            if (!empty($allfields)) {
                end($allfields);
                $prevfield = $allfields[key($allfields)];
            }
        } else {
            $prevfield = $this->getField($after);
        }
        if ($prevfield && $prevfield->getNext()) {
            $nextfield = $this->getField($prevfield->getNext());
        }

        // Set current field previous and next attributes
        if ($prevfield) {
            $field->setPrevious($prevfield->getName());
            $prevfield->setNext($field->getName());
        }
        if ($nextfield) {
            $field->setNext($nextfield->getName());
            $nextfield->setPrevious($field->getName());
        }
        // Some more attributes
        $field->setLoaded(true);
        $field->setChanged(true);
        // Add the new field
        $this->fields[] = $field;
        // Reorder the field
        $this->orderFields($this->fields);
        // Recalculate the hash
        $this->calculateHash(true);
        // We have one new field, so the table has changed
        $this->setChanged(true);

        return $field;
    }

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


Question:
Determine if the user is authorized to make this request.

@throws \Cortex\Foundation\Exceptions\GenericException

@return bool

public function authorize(): bool
    {
        parent::authorize();

        $user = $this->user($this->route('guard'))
                ?? $this->attemptUser($this->route('guard'))
                   ?? app('cortex.auth.admin')->whereNotNull('phone')->where('phone', $this->get('phone'))->first();

        if (! $user) {
            // User instance required to detect active TwoFactor methods
            throw new GenericException(trans('cortex/foundation::messages.session_required'), route('adminarea.login'));
        }

        return true;
    }

func HandleCredentialError(err error, ctx context.ProviderCallContext) {
	common.HandleCredentialError(IsAuthorisationFailure, err, ctx)
}

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


Question:
/*
Refresh the page after a live update from the server. This only
works in live preview mode (using the `--server` parameter).

function refresh(body) {
    document.querySelector('body').className = 'preload';
    document.body.innerHTML = body;

    // Re-initialize the page
    init();
    autoCollapse();

    document.querySelector('body').className = '';
}

function(options, cb) {
        let template, render;
        if(!options.params || !options.params.template || !options.params.template.content) {
            return utils.checkError('Missing template content', 727, cb);
        }

        try {
            template = handlebars.compile(options.params.template.content);
            if(options.params.template._id){
                if(!options.params.input.tags){
                    options.params.input.tags = {};
                }
                options.params.input.tags['soajs.template.id'] = options.params.template._id.toString();
            }
            render = template(options.params.input);
        }
        catch(e) {
            return utils.checkError(e, 727, cb);
        }

        return cb(null, { render });
    }

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


Question: // ListBindings returns all bindings

func (c *Client) ListBindings() (rec []BindingInfo, err error) {
	req, err := newGETRequest(c, "bindings/")
	if err != nil {
		return []BindingInfo{}, err
	}

	if err = executeAndParseRequest(c, req, &rec); err != nil {
		return []BindingInfo{}, err
	}

	return rec, nil
}

func (client *MyInventoryClient) New(appEnv *cfenv.App) *MyInventoryClient {

  if strings.ToUpper(os.Getenv("DISPLAY_NEW_SERVICES")) == "YES" {
    client.Enabled = true
    client.ServiceBaseURL = getServiceBinding("inventory-service", "target-url", appEnv)
  } else {
    client.Enabled = false
  }
  return client
}

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


Question: Send data to all connected clients.

def raw_callback(self, raw_packet):
        """"""
        if not ';PONG;' in raw_packet:
            log.info('forwarding packet %s to clients', raw_packet)
        else:
            log.debug('forwarding packet %s to clients', raw_packet)
        writers = [i[1] for i in list(clients)]
        for writer in writers:
            writer.write(str(raw_packet).encode() + CRLF)

def _ensure_opened(self):

        if not self._opened:
            self._opened = True
            self._update_servers()

            # Start or restart the events publishing thread.
            if self._publish_tp or self._publish_server:
                self.__events_executor.open()

        # Ensure that the monitors are open.
        for server in itervalues(self._servers):
            server.open()

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


Question:
Checks if value has an exact count

@param mixed $value The value
@param int   $count The count

@return bool

public static function exactCount($value, int $count): bool
    {
        if (!static::isCountable($value)) {
            return false;
        }

        return count($value) == $count;
    }

function (parameters) {

        /**
         * Job identifier.
         * @type {string}
         */
        this.hash = parameters.hash;

        /**
         * Array of hashes to {@link Artifact}s containing each requested result.
         * @type {string[]}
         */
        this.resultHashes = parameters.resultHashes || [];

        /**
         * Hash to an {@link Artifact} containing the union of all requests results.
         * @type {string}
         */
        this.resultSuperSet = parameters.resultSuperSet || null;

        this.userId = parameters.userId || [];

        /**
         * Current status of the job.
         * @type {string}
         */
        this.status = parameters.status || null;

        /**
         * Timestamp of when the job was created.
         * @type {string}
         */
        this.createTime = parameters.createTime || null;

        /**
         * Timestamp of when the job execution started by a worker.
         * @type {string}
         */
        this.startTime = parameters.startTime || null;

        /**
         * Timestamp of when the job execution finished on the worker.
         * @type {string}
         */
        this.finishTime = parameters.finishTime || null;

        /**
         * Id/label of the worker processing the job.
         * @type {string}
         */
        this.worker = parameters.worker || null;

        /**
         * Array of labels for the job.
         * @type {string[]}
         */
        this.labels = parameters.labels || [];

        /**
         * The (id) outputNumber (0, 1, 2, ...) of the latest {@link OutputInfo} (for this job) available on the server.
         * When no output is available the number is <b>null</b>.
         * @type {number}
         */
        this.outputNumber = typeof parameters.outputNumber === 'number' ? parameters.outputNumber : null;
    }

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


Question:
Returns default category sorting for selected category.

@return array

public function getDefaultSorting()
    {
        $aSorting = parent::getDefaultSorting();

        $oCategory = $this->getActiveCategory();

        if ($this->getListType() != 'search' && $oCategory && $oCategory instanceof \OxidEsales\Eshop\Application\Model\Category) {
            if ($sSortBy = $oCategory->getDefaultSorting()) {
                $sSortDir = ($oCategory->getDefaultSortingMode()) ? "desc" : "asc";
                $aSorting = ['sortby' => $sSortBy, 'sortdir' => $sSortDir];
            }
        }

        return $aSorting;
    }

public function setOrder($mode, $direction = self::DIRECTION_ASC)
    {
        $this->orderMode = $mode;
        $this->orderDirection = $direction;
    }

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


Question:
Creates a new exception using a format and values.

@param string $format    The format.
@param mixed  $value,... The value(s).

@return Exception The exception.

public static function create($format, $value = null)
    {
        if (0 < func_num_args()) {
            $format = vsprintf($format, array_slice(func_get_args(), 1));
        }

        return new static($format);
    }

func (s *Channel) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "Channel"}
	if s.ChannelName == nil {
		invalidParams.Add(request.NewErrParamRequired("ChannelName"))
	}
	if s.ChannelName != nil && len(*s.ChannelName) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ChannelName", 1))
	}
	if s.DataSource == nil {
		invalidParams.Add(request.NewErrParamRequired("DataSource"))
	}
	if s.DataSource != nil {
		if err := s.DataSource.Validate(); err != nil {
			invalidParams.AddNested("DataSource", err.(request.ErrInvalidParams))
		}
	}
	if s.ShuffleConfig != nil {
		if err := s.ShuffleConfig.Validate(); err != nil {
			invalidParams.AddNested("ShuffleConfig", err.(request.ErrInvalidParams))
		}
	}

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

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


Question:
Gets capabilities.

        Queries WFS server for its capabilities. Internally used by get_feature_type_info.

def get_capabilities(self):

        params = {'service'      : 'WFS',
                  'request'      : 'GetCapabilities',
                  'version'      : '1.0.0'}

        caps_response = requests.get(self._wfs_server, params=params)
        caps_response.raise_for_status()

        return ET.fromstring(caps_response.content)

def cget(self, key):

        if key == 'scalewidth':
            return self._scale.cget('length')
        elif key == 'from':
            return self._scale.cget('from')
        elif key == 'to':
            return self._scale.cget('to')
        elif key == 'entrywidth':
            return self._entry.cget('width')
        elif key == 'entryscalepad':
            return self.__entryscalepad
        elif key == 'compound':
            return self.__compound
        elif key == 'orient':
            return str(self._scale.cget('orient'))
        else:
            return ttk.Frame.cget(self, key)

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


Question:
Sets Inputs from Method Arguments.
@access		public
@return		void

public function setInputs()
	{
		$this->inputs	= array();
		$len	= pow( 2, $this->type );
		$args	= func_get_args();
		for( $i = 0; $i < $len; $i ++ )
			if( isset( $args[$i] ) )
				$this->inputs[$i] = $args[$i];
	}

protected function buildSet(
        /*# string */ $prefix,
        array $settings
    )/*# : array */ {
        if ($this instanceof UpdateStatementInterface) {
            return $this->buildUpdateSet($prefix, $settings);
        } else {
            return $this->buildInsertSet($prefix, $settings);
        }
    }

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


Question:
Format a string date to a string database readable format.

@param string $date
@param string $dateFormat
@return string

public function toDate($date, $dateFormat)
    {
        $dateTime = DateTime::createFromFormat($dateFormat, $date);

        return $dateTime->format(self::YMDH);
    }

public function toString()
    {
        $url = $this->scheme.':';
        if (trim($this->host) != '') {
            $url .= '//';
            if (trim($this->user) != '') {
                $url .= $this->user.((trim($this->pass) != '')?':'.$this->pass:'').'@';
            }
            $url .= $this->host;

            if (trim($this->port) != '') {
                $url .= ':'.$this->port;
            }
        }

        $url .= (trim($this->path) != '')?$this->path:'';
        $url .= (trim($this->query) != '')?'?'.$this->query:'';
        $url .= (trim($this->fragment) != '')?'#'.$this->fragment:'';

        if (!self::isValid($url)) {
            throw new RuntimeException('Built URL is not a valid one: '.$url);
        }

        return $url;
    }

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


Question:
Load the sql file and then execute it

@throws BuildException

public function main()
    {
        $conf = new GeneratorConfig();
        $conf->setBuildProperties($this->getProject()->getProperties());
        $this->setBuildConnections($conf->getBuildConnections());

        if ($this->sqldbmap === null || $this->getSqlDbMap()->exists() === false) {
            throw new BuildException("You haven't provided an sqldbmap, or " . "the one you specified doesn't exist: " . $this->sqldbmap->getPath());
        }

        if ($this->url === null) {
            throw new BuildException("DSN url attribute must be set!");
        }

        // get an ordered list of SQL files to execute
        $databases = $this->getFilesToExecute();

        $this->log(sprintf('Reading SQL files...'));
        foreach ($databases as $database => $files) {
            $statements[$database] = array();
            foreach ($files as $fileName) {
                $fullFileName = $this->srcDir ? $this->srcDir . DIRECTORY_SEPARATOR . $fileName : $fileName;
                if (file_exists($fullFileName)) {
                    $this->log(sprintf('  Loading statements from "%s"', $fullFileName));
                    $fileStatements = PropelSQLParser::parseFile($fullFileName);
                    $this->log(sprintf('    %d statements to execute', count($fileStatements)), Project::MSG_VERBOSE);
                    $statements[$database] = array_merge($statements[$database], $fileStatements);
                } else {
                    $this->log(sprintf('File "%s" in sqldbmap does not exist, skipping it.', $fullFileName));
                }
            }
        }

        $successfulStatements = 0;
        $this->log(sprintf('Executing SQL statements...'));
        foreach ($statements as $database => $statementList) {
            $successfulStatements += $this->insertDatabaseSqlFiles($database, $statementList);
        }

        $this->log(sprintf('SQL execution complete. %d statements successfully executed.', $successfulStatements));
    }

func (c *Client) FlushDB() error {
	_, err := c.execOnFirst(false, "FLUSHDB")
	return err
}

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


Question:
Scroll a AbsListView matching the specified index to the specified line.

@param index the index of the {@link AbsListView} to scroll
@param line the line to scroll to

public void scrollListToLine(int index, int line){
		if(config.commandLogging){
			Log.d(config.commandLoggingTag, "scrollListToLine("+index+", "+line+")");
		}

		scroller.scrollListToLine(waiter.waitForAndGetView(index, AbsListView.class), line);
	}

def create_content(self, cli, width, height):

        buffer = self._buffer(cli)

        # Get the document to be shown. If we are currently searching (the
        # search buffer has focus, and the preview_search filter is enabled),
        # then use the search document, which has possibly a different
        # text/cursor position.)
        def preview_now():
            """ True when we should preview a search. """
            return bool(self.preview_search(cli) and
                        cli.buffers[self.search_buffer_name].text)

        if preview_now():
            if self.get_search_state:
                ss = self.get_search_state(cli)
            else:
                ss = cli.search_state

            document = buffer.document_for_search(SearchState(
                text=cli.current_buffer.text,
                direction=ss.direction,
                ignore_case=ss.ignore_case))
        else:
            document = buffer.document

        get_processed_line = self._create_get_processed_line_func(cli, document)
        self._last_get_processed_line = get_processed_line

        def translate_rowcol(row, col):
            " Return the content column for this coordinate. "
            return Point(y=row, x=get_processed_line(row).source_to_display(col))

        def get_line(i):
            " Return the tokens for a given line number. "
            tokens = get_processed_line(i).tokens

            # Add a space at the end, because that is a possible cursor
            # position. (When inserting after the input.) We should do this on
            # all the lines, not just the line containing the cursor. (Because
            # otherwise, line wrapping/scrolling could change when moving the
            # cursor around.)
            tokens = tokens + [(self.default_char.token, ' ')]
            return tokens

        content = UIContent(
            get_line=get_line,
            line_count=document.line_count,
            cursor_position=translate_rowcol(document.cursor_position_row,
                                             document.cursor_position_col),
            default_char=self.default_char)

        # If there is an auto completion going on, use that start point for a
        # pop-up menu position. (But only when this buffer has the focus --
        # there is only one place for a menu, determined by the focussed buffer.)
        if cli.current_buffer_name == self.buffer_name:
            menu_position = self.menu_position(cli) if self.menu_position else None
            if menu_position is not None:
                assert isinstance(menu_position, int)
                menu_row, menu_col = buffer.document.translate_index_to_position(menu_position)
                content.menu_position = translate_rowcol(menu_row, menu_col)
            elif buffer.complete_state:
                # Position for completion menu.
                # Note: We use 'min', because the original cursor position could be
                #       behind the input string when the actual completion is for
                #       some reason shorter than the text we had before. (A completion
                #       can change and shorten the input.)
                menu_row, menu_col = buffer.document.translate_index_to_position(
                    min(buffer.cursor_position,
                        buffer.complete_state.original_document.cursor_position))
                content.menu_position = translate_rowcol(menu_row, menu_col)
            else:
                content.menu_position = None

        return content

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


Question:
Gets the valid offsets during this transition.
<p>
A gap will return an empty list, while an overlap will return both offsets.

@return the list of valid offsets

List<ZoneOffset> getValidOffsets() {
        if (isGap()) {
            return Collections.emptyList();
        }
        return Arrays.asList(getOffsetBefore(), getOffsetAfter());
    }

def _isCompatible(self, other, reporter):

        layer1 = self
        layer2 = other

        # incompatible number of glyphs
        glyphs1 = set(layer1.keys())
        glyphs2 = set(layer2.keys())
        if len(glyphs1) != len(glyphs2):
            reporter.glyphCountDifference = True
            reporter.warning = True
        if len(glyphs1.difference(glyphs2)) != 0:
            reporter.warning = True
            reporter.glyphsMissingFromLayer2 = list(glyphs1.difference(glyphs2))
        if len(glyphs2.difference(glyphs1)) != 0:
            reporter.warning = True
            reporter.glyphsMissingInLayer1 = list(glyphs2.difference(glyphs1))
        # test glyphs
        for glyphName in sorted(glyphs1.intersection(glyphs2)):
            glyph1 = layer1[glyphName]
            glyph2 = layer2[glyphName]
            glyphCompatibility = glyph1.isCompatible(glyph2)[1]
            if glyphCompatibility.fatal or glyphCompatibility.warning:
                if glyphCompatibility.fatal:
                    reporter.fatal = True
                if glyphCompatibility.warning:
                    reporter.warning = True
                reporter.glyphs.append(glyphCompatibility)

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


Question:
Get the next selector.
@return the next or null

@Nullable
    String next() {
        if( lastIdx >= selector.length() ) {
            return null;
        }
        LOOP: do {
            if( ++idx == selector.length() ) {
                break LOOP;
            }
            switch( selector.charAt( idx ) ) {
                case '.':
                case '#':
                case ':':
                case '[':
                    break LOOP;
            }
        } while( true );
        String str = selector.substring( lastIdx, idx ).trim();
        lastIdx = idx;
        return str;
    }

func (l *waiterList) PushFront(e *Entry) {
	waiterElementMapper{}.linkerFor(e).SetNext(l.head)
	waiterElementMapper{}.linkerFor(e).SetPrev(nil)

	if l.head != nil {
		waiterElementMapper{}.linkerFor(l.head).SetPrev(e)
	} else {
		l.tail = e
	}

	l.head = e
}

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


Question: Normalize arguments for single request. Override resource url to use action types root path and use name filter. Extend params if user defines other params.

function _normalizeArguments(obj) {
    var args = arguments;

    if (!obj || Utils.isFunction(obj)) {
      args = Array.prototype.slice.call(arguments, 0);
      args.unshift({});
    }

    // Split full path (/actions/_custom) - we get three parts:
    // 1) empty, 2) root path and 3) encoded action type name
    var url = this.path.split('/');

    args[0].url = '/' + url[1];
    args[0].params = Utils.extend(args[0].params, {
      filter: {
        name: decodeURIComponent(url[2])
      }
    });

    return args;
  }

public Route to(Controller controller, String method) {
        Preconditions.checkNotNull(controller);
        Preconditions.checkNotNull(method);
        this.controller = controller;
        try {
            this.controllerMethod = verifyThatControllerAndMethodExists(controller.getClass(),
                    method);
        } catch (Exception e) {
            throw new IllegalArgumentException(ERROR_CTRL + method + ERROR_IN + controller
                    .getClass() + "`, or the method is invalid", e);
        }
        return _build();
    }

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


Question:
Returns a {@link ICondition condition} that is satisfied by a {@link org.cornutum.tcases.PropertySet} that contains
between a specified minimum (exclusive) and maximum (inclusive) number of instances of a property.

public static Between betweenExclusiveMin( String property, int minimum, int maximum)
    {
    return new Between( moreThan( property, minimum), notMoreThan( property, maximum));
    }

public function set($id, $value)
    {
        $id = (string) $id;

        $this->validateSet($id);

        if ($type = $this->isDefined($id)) {
            if ($type[0] == ':') {
                $type = substr($type, 1);
                $actualType = $this->getType($value);
                if ($actualType != $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be of type %s, but %s given.', $id, $this->name, $type, $actualType));
                }
            } else {
                if (!$value instanceof $type) {
                    throw new WrongTypeException(sprintf('Value for item "%s" in %s container must be an instance of %s class, but %s given.', $id, $this->name, $type, $this->getType($value)));
                }
            }
        }

        $this->items[$id] = $value;
    }

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


Question: Make a delete requests (this returns a coroutine)

def delete(self, service, path, **kwargs):

        return self.make_request(Methods.DELETE, service, path, **kwargs)

func (d *Deployment) Reap(args *structs.DeploymentDeleteRequest,
	reply *structs.GenericResponse) error {
	if done, err := d.srv.forward("Deployment.Reap", args, args, reply); done {
		return err
	}
	defer metrics.MeasureSince([]string{"nomad", "deployment", "reap"}, time.Now())

	// Update via Raft
	_, index, err := d.srv.raftApply(structs.DeploymentDeleteRequestType, args)
	if err != nil {
		return err
	}

	// Update the index
	reply.Index = index
	return nil
}

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