Question:
@param  FileStorage $storage
@param  array<string, bool> $dependent_file_paths

@return void

private function populateFileStorage(FileStorage $storage, array $dependent_file_paths = [])
    {
        if ($storage->populated) {
            return;
        }

        $file_path_lc = strtolower($storage->file_path);

        if (isset($dependent_file_paths[$file_path_lc])) {
            return;
        }

        $dependent_file_paths[$file_path_lc] = true;

        $all_required_file_paths = $storage->required_file_paths;

        foreach ($storage->required_file_paths as $included_file_path => $_) {
            try {
                $included_file_storage = $this->file_storage_provider->get($included_file_path);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            $this->populateFileStorage($included_file_storage, $dependent_file_paths);

            $all_required_file_paths = $all_required_file_paths + $included_file_storage->required_file_paths;
        }

        foreach ($all_required_file_paths as $included_file_path => $_) {
            try {
                $included_file_storage = $this->file_storage_provider->get($included_file_path);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            $storage->declaring_function_ids = array_merge(
                $included_file_storage->declaring_function_ids,
                $storage->declaring_function_ids
            );

            $storage->declaring_constants = array_merge(
                $included_file_storage->declaring_constants,
                $storage->declaring_constants
            );
        }

        foreach ($storage->referenced_classlikes as $fq_class_name) {
            try {
                $classlike_storage = $this->classlike_storage_provider->get($fq_class_name);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            if (!$classlike_storage->location) {
                continue;
            }

            try {
                $included_file_storage = $this->file_storage_provider->get($classlike_storage->location->file_path);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            $storage->declaring_function_ids = array_merge(
                $included_file_storage->declaring_function_ids,
                $storage->declaring_function_ids
            );
        }

        $storage->required_file_paths = $all_required_file_paths;

        foreach ($all_required_file_paths as $required_file_path) {
            try {
                $required_file_storage = $this->file_storage_provider->get($required_file_path);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            $required_file_storage->required_by_file_paths += [$file_path_lc => $storage->file_path];
        }

        foreach ($storage->required_classes as $required_classlike) {
            try {
                $classlike_storage = $this->classlike_storage_provider->get($required_classlike);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            if (!$classlike_storage->location) {
                continue;
            }

            try {
                $required_file_storage = $this->file_storage_provider->get($classlike_storage->location->file_path);
            } catch (\InvalidArgumentException $e) {
                continue;
            }

            $required_file_storage->required_by_file_paths += [$file_path_lc => $storage->file_path];
        }

        $storage->populated = true;
    }

public function open($options = [])
    {
        $attributes = [];

        if ($this->isMode(self::MODE_EDIT)) {
            $this->addHiddenField((new Hidden('_method'))->value('PUT'));
        }

        $this->addRedirectUrlField();

        $attributes['action'] = $this->getAction();
        $attributes['method'] = Arr::get($options, 'method', 'post');
        $attributes['accept-charset'] = 'UTF-8';

        $attributes['class'] = Arr::get($options, 'class');

        if ($this->hasFile()) {
            $attributes['enctype'] = 'multipart/form-data';
        }

        $html = [];
        foreach ($attributes as $name => $value) {
            $html[] = "$name=\"$value\"";
        }

        return '<form '.implode(' ', $html).' pjax-container>';
    }

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


Question: // ReadString works like bufio.ReadString

func (c *Conn) ReadString(delim byte) (string, error) {
	bytes, err := c.ReadBytes(delim)
	return string(bytes), err
}

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:
Return the Metrics on this shelf in the order in which
        they were used.

def metric_ids(self):

        return self._sorted_ingredients([
            d.id for d in self.values() if isinstance(d, Metric)
        ])

protected function set_new_sortorder() {
        $search = array('parentid' => $this->get('parentid'), 'competencyframeworkid' => $this->get('competencyframeworkid'));
        $this->raw_set('sortorder', $this->count_records($search));
    }

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


Question:
Reset all the fields to their default value.
<p />NOTE: After executing, this records edit mode is set to NONE.
@param bDisplay The the new values (on work in the thick model).
@throws Exception An exception on initing a field.

public void initRecord(boolean bDisplay) throws DBException
    {
        int iFieldCount = this.getFieldCount();      // Number of fields to read in
        for (int iFieldSeq = Constants.MAIN_FIELD; iFieldSeq < iFieldCount + Constants.MAIN_FIELD; iFieldSeq++)
        {
            FieldInfo field = this.getField(iFieldSeq);
            field.initField(bDisplay);
        }
        this.setEditMode(Constants.EDIT_NONE);
    }

func (s *store) UpdateModel(controllerName, modelName string, details ModelDetails) error {
	if err := ValidateControllerName(controllerName); err != nil {
		return errors.Trace(err)
	}
	if err := ValidateModel(modelName, details); err != nil {
		return errors.Trace(err)
	}

	releaser, err := s.acquireLock()
	if err != nil {
		return errors.Annotatef(err,
			"cannot acquire lock file for updating model %s on controller %s", modelName, controllerName,
		)
	}
	defer releaser.Release()

	return errors.Trace(updateModels(
		controllerName,
		func(models *ControllerModels) (bool, error) {
			oldDetails, ok := models.Models[modelName]
			if ok && details == oldDetails {
				return false, nil
			}
			if ok && oldDetails.ModelType == "" && details.ModelType != model.IAAS ||
				oldDetails.ModelType != "" && oldDetails.ModelType != details.ModelType {
				oldModelType := oldDetails.ModelType
				if oldModelType == "" {
					oldModelType = model.IAAS
				}
				return false, errors.Errorf(
					"model type was %q, cannot change to %q", oldModelType, details.ModelType)
			}
			models.Models[modelName] = details
			return true, nil
		},
	))
}

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


Question:
Write each long value from a long value array into the session stream.

@param value a long value array which values will be written into
@return the DSL session
@throws IOException it will be thrown for transport errors

public JBBPOut Long(final long... value) throws IOException {
    assertNotEnded();
    assertArrayNotNull(value);
    if (this.processCommands) {
      for (final long l : value) {
        _writeLong(l);
      }
    }
    return this;
  }

public static void main(final String[] args) {
        Switch about = new Switch("a", "about", "display about message");
        Switch help = new Switch("h", "help", "display help message");

        FileArgument expectedFile = new FileArgument("e", "expected-file", "expected interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument observedFile = new FileArgument("b", "observed-file", "observed interpretation file, default stdin; at least one of expected or observed file must be provided", false);
        FileArgument outputFile = new FileArgument("o", "output-file", "output file, default stdout", false);
        IntegerArgument resolution = new IntegerArgument("r", "resolution", "resolution, must be in the range [1..4], default " + DEFAULT_RESOLUTION, false);
        StringListArgument loci = new StringListArgument("l", "loci", "list of loci to validate, default " + DEFAULT_LOCI, false);
        Switch printSummary = new Switch("s", "summary", "print summary");

        ArgumentList arguments = new ArgumentList(about, help, expectedFile, observedFile, outputFile, resolution, loci, printSummary);
        CommandLine commandLine = new CommandLine(args);

        ValidateInterpretation validateInterpretation = null;
        try
        {
            CommandLineParser.parse(commandLine, arguments);
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }

            // todo: allow for configuration of glclient
            validateInterpretation = new ValidateInterpretation(expectedFile.getValue(), observedFile.getValue(), outputFile.getValue(), resolution.getValue(DEFAULT_RESOLUTION), loci.getValue(DEFAULT_LOCI), printSummary.wasFound(), LocalGlClient.create());
        }
        catch (CommandLineParseException e) {
            if (about.wasFound()) {
                About.about(System.out);
                System.exit(0);
            }
            if (help.wasFound()) {
                Usage.usage(USAGE, null, commandLine, arguments, System.out);
                System.exit(0);
            }
            Usage.usage(USAGE, e, commandLine, arguments, System.err);
            System.exit(-1);
        }
        try {
            System.exit(validateInterpretation.call());
        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

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


Question:
Takes file.scss as an argument
Returns parsed variables hash-map
@param filePath
@returns {{}}

function sassVars (filePath) {
    const declarations = collectDeclarations(filePath);
    let variables = {};

    if (!declarations.length) {
        message('Warning: Zero declarations found');
        return;
    }

    declarations.forEach(function (declaration) {
        const parsedDeclaration = parseDeclaration(declaration);
        const varName = parsedDeclaration.key;
        let varValue = parsedDeclaration.value;
        const valueType = getValueType(varValue);

        /*
         * $key: $value;
         */
        if (valueType === 'var') {
            const localVarName = varValue;
            varValue = getVarValue(localVarName, variables);

            if (!varValue) {
                message(`Warning: Null value for variable ${localVarName}`);
            }
        }

        /*
         * $key: ($value-1 + $value-2) * $value-3 ... ;
         */
        if (valueType === 'expression') {
            // todo
        }

        /*
         * $key: value;
         */
        variables[varName] = varValue;
    });

    return variables;
}

protected function defineCss(NodeBuilder $saNode)
    {
        $saNode
            ->arrayNode('css')
                ->children()
                    ->arrayNode('files')
                        ->prototype('scalar')->end()
                    ->end()
                ->end()
            ->end();
    }

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


Question:
AdditionResult
@param XPath2ResultType $resType1
@param XPath2ResultType $resType2
@return XPath2ResultType

public static function AdditionResult( $resType1, $resType2 )
	{
		if ( $resType1 == XPath2ResultType::Number || $resType2 == XPath2ResultType::Number )
			return XPath2ResultType::Number;

		if ( $resType1 == XPath2ResultType::DateTime && $resType2 == XPath2ResultType::Duration )
			return XPath2ResultType::DateTime;

		if ( $resType1 == XPath2ResultType::Duration )
		{
			if ($resType2 == XPath2ResultType::Duration)
				return XPath2ResultType::Duration;

			if ($resType2 == XPath2ResultType::DateTime)
				return XPath2ResultType::DateTime;
		}

		return XPath2ResultType::Any;
	}

protected function execute(InputInterface $input, OutputInterface $output)
  {
    $method = $input->getOption('method');
    $routes = array();

    foreach (Route::$routes as $key => $route) {
      if ($method == 'all') {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      } else if (str_contains(implode(' ', $route['method']), $method)) {
        $middleware = implode('|', $route['middleware']);
        array_push($routes, array(implode(',', $route['method']), $route['pattern'], $route['name'], is_string($route['callback']) ? $route['callback'] : '<comment>Closure</comment>', $middleware));
      }
    }

    $table = new Table($output);
    $table->setStyle('box');
    $table
        ->setHeaders(array('Method', 'URI', 'Name', 'Action', 'Middleware'))
        ->setRows(
            $routes
        )
    ;
    $table->render();
  }

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


Question:
getter for affiliation - gets Affiliation of the author
@generated
@return value of the feature

public String getAffiliation() {
    if (AuthorInfo_Type.featOkTst && ((AuthorInfo_Type)jcasType).casFeat_affiliation == null)
      jcasType.jcas.throwFeatMissing("affiliation", "de.julielab.jules.types.AuthorInfo");
    return jcasType.ll_cas.ll_getStringValue(addr, ((AuthorInfo_Type)jcasType).casFeatCode_affiliation);}

protected function giveAbilities(array $ids, Model $authority = null)
    {
        $ids = array_diff($ids, $this->getAssociatedAbilityIds($authority, $ids, false));

        if (is_null($authority)) {
            $this->giveAbilitiesToEveryone($ids);
        } else {
            $this->giveAbilitiesToAuthority($ids, $authority);
        }
    }

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


Question: // Borrowed from https://golang.org/src/cmd/internal/objfile/pe.go

func findPESymbol(f *pe.File, name string) (*pe.Symbol, error) {
	for _, s := range f.Symbols {
		if s.Name != name {
			continue
		}
		if s.SectionNumber <= 0 {
			return nil, fmt.Errorf("symbol %s: invalid section number %d", name, s.SectionNumber)
		}
		if len(f.Sections) < int(s.SectionNumber) {
			return nil, fmt.Errorf("symbol %s: section number %d is larger than max %d", name, s.SectionNumber, len(f.Sections))
		}
		return s, nil
	}
	return nil, fmt.Errorf("no %s symbol found", name)
}

def _get_config_file(conf, atom):
    '''

    '''
    if '*' in atom:
        parts = portage.dep.Atom(atom, allow_wildcard=True)
        if not parts:
            return
        if parts.cp == '*/*':
            # parts.repo will be empty if there is no repo part
            relative_path = parts.repo or "gentoo"
        elif six.text_type(parts.cp).endswith('/*'):
            relative_path = six.text_type(parts.cp).split("/")[0] + "_"
        else:
            relative_path = os.path.join(*[x for x in os.path.split(parts.cp) if x != '*'])
    else:
        relative_path = _p_to_cp(atom)
        if not relative_path:
            return

    complete_file_path = BASE_PATH.format(conf) + '/' + relative_path

    return complete_file_path

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


Question:
Maps a value val in [vmin, vmax] to the corresponding color in
        the colorscale
        returns the rgb color code of that color

def _map_val2color(val, vmin, vmax, colorscale=None):

    colorscale = colorscale or colorscale_default

    if vmin >= vmax:
        raise ValueError("vmin should be < vmax")

    scale = list(map(float, np.array(colorscale)[:, 0]))
    colors = np.array(colorscale)[:, 1]

    colors_01 = (
        np.array(list(map(literal_eval, [color[3:] for color in colors]))) / 255.0
    )

    v = (val - vmin) / float((vmax - vmin))  # val is mapped to v in[0,1]

    idx = 0
    # sequential search for the two   consecutive indices idx, idx+1 such that
    # v belongs to the interval  [scale[idx], scale[idx+1]
    while v > scale[idx + 1]:
        idx += 1
    left_scale_val = scale[idx]
    right_scale_val = scale[idx + 1]
    vv = (v - left_scale_val) / (right_scale_val - left_scale_val)

    # get the triplet of three values in [0,1] that represent the rgb color
    # corresponding to val
    val_color01 = colors_01[idx] + vv * (colors_01[idx + 1] - colors_01[idx])
    val_color_0255 = list(map(np.uint8, 255 * val_color01))

    return "rgb" + str(tuple(val_color_0255))

function (){
    var scale = Math.min(
      (_svg.width() - PADDING * 2) / _width,
      (_svg.height() - PADDING * 2) / _height
    ),
    panZoomValues = _panZoom();

    if(
      panZoomValues.panX !== PADDING ||
      panZoomValues.panY !== PADDING ||
      panZoomValues.scale !== scale
    ) {
      _panZoomValues = _panZoom(PADDING, PADDING, scale);
    }
    else {
      _panZoomValues = _panZoom(
        _panZoomValues.panX,
        _panZoomValues.panY,
        _panZoomValues.scale);
    }
  }

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


Question:
Extracts distinct values from the array that don't contain whitespace.

@param array $array The array to extract the values from
@return \Puzzlout\Framework\Helpers\ArrayExtractionHelper The extrator instance.

public function ExtractDistinctValues($array) {
        foreach ($array as $key => $value) {
            $valueIsArray = is_array($value);
            $valueIsAlreadyExtracted = in_array($value, $this->List);
            $keyIsExtracted = in_array($key, $this->List);
            if (!$valueIsArray && !$valueIsAlreadyExtracted && !RegexHelper::Init($value)->StringContainsWhiteSpace()) {
                array_push($this->List, $value);
            }
            if (!$keyIsExtracted && is_string($key) && !RegexHelper::Init($key)->StringContainsWhiteSpace()) {
                array_push($this->List, $key);
            }
            if ($valueIsArray) {
                $this->ExtractDistinctValues($value);
            }
        }
        return $this;
    }

public function except($keys)
    {
        $keys = is_array($keys) ? $keys : func_get_args();

        return array_diff_key($this->data, array_flip((array) $keys));
    }

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


Question:
/*
(non-Javadoc)

@see net.jawr.web.resource.handler.ResourceReader#getResource(java.lang.
String, boolean)

@Override
	public Reader getResource(JoinableResourceBundle bundle, String resourceName, boolean processingBundle) {

		Reader rd = null;
		if (!resourceName.contains(":")) {
			InputStream is = context.getResourceAsStream(resourceName);
			if (is != null) {
				rd = new InputStreamReader(is, charset);
			}
		}
		return rd;
	}

function (jsonS) {
    var jws = KJUR.jws.JWS;
    if(jws.isSafeJSONString(jsonS)) {
      return jws.readSafeJSONString(jsonS);
    }
    return null;
  }

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


Question: // RollbackMigration undo a migration.

func (m *Migrate) RollbackMigration(mig *Migration) error {
	if mig.Rollback == nil {
		return ErrRollbackImpossible
	}

	if err := mig.Rollback(m.db); err != nil {
		return err
	}

	sql := fmt.Sprintf("DELETE FROM %s WHERE %s = ?", m.options.TableName, m.options.IDColumnName)
	if _, err := m.db.Exec(sql, mig.ID); err != nil {
		return err
	}
	return nil
}

public function reverseTransform($id)
    {
        if (!$id) {
            return null;
        }

        $object = $this->om
            ->getRepository($this->class)
            ->find($id)
        ;

        if (! $object) {
            throw new TransformationFailedException();
        }

        return $object;
    }

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


Question:
// formatDateTimeComponentPeriodAbbreviated renders an abbreviated period
// component.

func (t *Translator) formatDateTimeComponentPeriodAbbreviated(hour int) string {
	if hour < 12 {
		return t.rules.DateTime.FormatNames.Periods.Abbreviated.AM
	}

	return t.rules.DateTime.FormatNames.Periods.Abbreviated.PM
}

public function monthToString($month, $abbr = false)
	{
		switch ($month)
		{
			case 1:
				return $abbr ? \Lang::txt('JANUARY_SHORT') : \Lang::txt('JANUARY');
			case 2:
				return $abbr ? \Lang::txt('FEBRUARY_SHORT') : \Lang::txt('FEBRUARY');
			case 3:
				return $abbr ? \Lang::txt('MARCH_SHORT') : \Lang::txt('MARCH');
			case 4:
				return $abbr ? \Lang::txt('APRIL_SHORT') : \Lang::txt('APRIL');
			case 5:
				return $abbr ? \Lang::txt('MAY_SHORT') : \Lang::txt('MAY');
			case 6:
				return $abbr ? \Lang::txt('JUNE_SHORT') : \Lang::txt('JUNE');
			case 7:
				return $abbr ? \Lang::txt('JULY_SHORT') : \Lang::txt('JULY');
			case 8:
				return $abbr ? \Lang::txt('AUGUST_SHORT') : \Lang::txt('AUGUST');
			case 9:
				return $abbr ? \Lang::txt('SEPTEMBER_SHORT') : \Lang::txt('SEPTEMBER');
			case 10:
				return $abbr ? \Lang::txt('OCTOBER_SHORT') : \Lang::txt('OCTOBER');
			case 11:
				return $abbr ? \Lang::txt('NOVEMBER_SHORT') : \Lang::txt('NOVEMBER');
			case 12:
				return $abbr ? \Lang::txt('DECEMBER_SHORT') : \Lang::txt('DECEMBER');
		}
	}

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


Question:
@param CalendarEvent $event
@param       $start
@param       $end

@return CalendarEventVersionOccurrence

public function createEventOccurrence(CalendarEventVersion $version, CalendarEventRepetition $repetition, $start, $end)
    {
        return new CalendarEventVersionOccurrence($version, $repetition, $start, $end);
    }

public void marshall(MaintenanceWindowIdentity maintenanceWindowIdentity, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(maintenanceWindowIdentity.getWindowId(), WINDOWID_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getName(), NAME_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getEnabled(), ENABLED_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getDuration(), DURATION_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getCutoff(), CUTOFF_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getSchedule(), SCHEDULE_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getScheduleTimezone(), SCHEDULETIMEZONE_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getEndDate(), ENDDATE_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getStartDate(), STARTDATE_BINDING);
            protocolMarshaller.marshall(maintenanceWindowIdentity.getNextExecutionTime(), NEXTEXECUTIONTIME_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:
Evaluates inner joins.

@param QueryBuilder    $queryBuilder
@param CreatePaginator $annotation

public function evaluate(
        QueryBuilder $queryBuilder,
        CreatePaginator $annotation
    ) {
        foreach ($annotation->getInnerJoins() as $innerJoin) {
            $queryBuilder->innerJoin(
                trim($innerJoin[0]) . '.' . trim($innerJoin[1]),
                trim($innerJoin[2])
            );

            if (isset($innerJoin[3]) && $innerJoin[3]) {
                $queryBuilder->addSelect(trim($innerJoin[2]));
            }
        }
    }

private static List<ParameterFiller> parseParameters(List<String> parameters) {
    List<ParameterFiller> parameterFillers = new ArrayList<>(parameters.size());
    for (String parameter : parameters) {
      ParameterFiller parameterFiller = parseParameter(parameter);
      if (parameterFiller != null) {
        parameterFillers.add(parameterFiller);
      }
    }
    return parameterFillers;
  }

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


Question: Computes how the aria-posinset property should be set for the given step

function(oStep){
		var bIsTopLevel = oStep.getParent() instanceof sap.ui.commons.RoadMap;
		var iIdx = oStep.getParent()[bIsTopLevel ? "indexOfStep" : "indexOfSubStep"](oStep);
		var iCountInvisible = 0;
		var aSteps = oStep.getParent()[bIsTopLevel ? "getSteps" : "getSubSteps"]();
		for (var i = 0; i < iIdx; i++) {
			if (!aSteps[i].getVisible()) {
				iCountInvisible++;
			}
		}
		return iIdx + 1 - iCountInvisible;
	}

@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType)
	{
		switch (featureID)
		{
			case XbasePackage.XBINARY_OPERATION__LEFT_OPERAND:
				return getLeftOperand();
			case XbasePackage.XBINARY_OPERATION__RIGHT_OPERAND:
				return getRightOperand();
			case XbasePackage.XBINARY_OPERATION__REASSIGN_FIRST_ARGUMENT:
				return isReassignFirstArgument();
		}
		return super.eGet(featureID, resolve, coreType);
	}

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


Question: Try to get adapter class from Symbol, String or use Object as-is.

def get_adapter(adp)
        # okay, this is only because we can't camelize it :)
        adp = Loggr::Adapter::NOP if !adp

        # Code adapter from ActiveSupport::Inflector#camelize
        # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L30
        adp = adp.to_s.gsub(/\/(.?)/) { "::#{$1.upcase}" }.gsub(/(?:^|_)(.)/) { $1.upcase } if adp.is_a?(Symbol)

        clazz = adp

        if adp.respond_to?(:to_str)
          const = begin Loggr::Adapter.const_get(adp.to_s) rescue begin Loggr::Adapter.const_get(adp.to_s.upcase) rescue nil end end
          unless const
            # code adapter from ActiveSupport::Inflector#constantize
            # https://github.com/rails/rails/blob/v3.0.9/activesupport/lib/active_support/inflector/methods.rb#L107
            names = adp.to_s.split('::')
            names.shift if names.empty? || names.first.empty?

            const = ::Object
            names.each { |n| const = const.const_get(n) }
          end
          clazz = const
        end

        raise "#{clazz}: an adapter must implement #logger and #mdc" unless clazz.respond_to?(:logger) && clazz.respond_to?(:mdc)
        clazz
      end

public IAtom configure(IAtom atom, IIsotope isotope) {
        atom.setMassNumber(isotope.getMassNumber());
        atom.setSymbol(isotope.getSymbol());
        atom.setExactMass(isotope.getExactMass());
        atom.setAtomicNumber(isotope.getAtomicNumber());
        atom.setNaturalAbundance(isotope.getNaturalAbundance());
        return atom;
    }

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


Question: // SetItems sets the Items field's value.

func (s *ActiveTrustedSigners) SetItems(v []*Signer) *ActiveTrustedSigners {
	s.Items = 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:
// RunUnix attaches the router to a http.Server and starts listening and serving HTTP requests
// through the specified unix socket (ie. a file).
// Note: this method will block the calling goroutine indefinitely unless an error happens.

func (engine *Engine) RunUnix(file string) (err error) {
	debugPrint("Listening and serving HTTP on unix:/%s", file)
	defer func() { debugPrintError(err) }()

	os.Remove(file)
	listener, err := net.Listen("unix", file)
	if err != nil {
		return
	}
	defer listener.Close()
	os.Chmod(file, 0777)
	err = http.Serve(listener, engine)
	return
}

def search_for_port(port_glob, req, expected_res):
    '''  '''

    # Check that the USB port actually exists, based on the known vendor and
    # product ID.
    if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None:
        return None

    # Find ports matching the supplied glob.
    ports = glob.glob(port_glob)
    if len(ports) == 0:
        return None

    for port in ports:
        with r12_serial_port(port) as ser:
            if not ser.isOpen():
                ser.open()

            # Write a request out.
            if sys.version_info[0] == 2:
                ser.write(str(req).encode('utf-8'))
            else:
                ser.write(bytes(req, 'utf-8'))

            # Wait a short period to allow the connection to generate output.
            time.sleep(0.1)

            # Read output from the serial connection check if it's what we want.
            res = ser.read(ser.in_waiting).decode(OUTPUT_ENCODING)
            if expected_res in res:
                return port

    raise ArmException('ST Robotics connection found, but is not responsive.'
                       + ' Is the arm powered on?')
    return None

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


Question: Create a EOCubeChunk object from an EOCube object.

def from_eocube(eocube, ji):
        """"""
        eocubewin = EOCubeChunk(ji, eocube.df_layers, eocube.chunksize, eocube.wdir)
        return eocubewin

public function encryptECB($data) {
		return mcrypt_encrypt(MCRYPT_RIJNDAEL_128, self::BLOB_ENCRYPTION_KEY, self::pad($data), MCRYPT_MODE_ECB);
	}

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


Question: // SetDataSourceName sets the DataSourceName field's value.

func (s *CreateDataSourceFromS3Input) SetDataSourceName(v string) *CreateDataSourceFromS3Input {
	s.DataSourceName = &v
	return s
}

def set_name(self, name):
        """"""
        if not name:
            name = ''
        self._client['config']['name'] = name
        yield from self._server.client_name(self.identifier, name)

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


Question: (a16 + a17.*M + a18.*M.*M + a19.*M.*M.*M).*(d(r).^3)

def _compute_term_4(self, C, mag, R):

        return (
            (C['a16'] + C['a17'] * mag + C['a18'] * np.power(mag, 2) +
             C['a19'] * np.power(mag, 3)) * np.power(R, 3)
        )

def unfuse(self):

        stack = SequentialRNNCell()
        get_cell = {'rnn_relu': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='relu',
                                                            prefix=cell_prefix),
                    'rnn_tanh': lambda cell_prefix: RNNCell(self._num_hidden,
                                                            activation='tanh',
                                                            prefix=cell_prefix),
                    'lstm': lambda cell_prefix: LSTMCell(self._num_hidden,
                                                         prefix=cell_prefix),
                    'gru': lambda cell_prefix: GRUCell(self._num_hidden,
                                                       prefix=cell_prefix)}[self._mode]
        for i in range(self._num_layers):
            if self._bidirectional:
                stack.add(BidirectionalCell(
                    get_cell('%sl%d_'%(self._prefix, i)),
                    get_cell('%sr%d_'%(self._prefix, i)),
                    output_prefix='%sbi_l%d_'%(self._prefix, i)))
            else:
                stack.add(get_cell('%sl%d_'%(self._prefix, i)))

            if self._dropout > 0 and i != self._num_layers - 1:
                stack.add(DropoutCell(self._dropout, prefix='%s_dropout%d_'%(self._prefix, i)))

        return stack

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


Question:
/*!
\static
Similar to instance() but will always create a new copy.

static function create( $fileName = 'site.ini', $rootDir = 'settings', $useTextCodec = null, $useCache = null, $useLocalOverrides = null )
    {
        $impl = new eZINI( $fileName, $rootDir, $useTextCodec, $useCache, $useLocalOverrides );
        return $impl;
    }

def add(self, child):

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

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


Question:
// labelIsAllowed return true if a should be included in metric
// the caller should lock m.filterLock while calling this method

func (m *Metrics) labelIsAllowed(label *Label) bool {
	labelName := (*label).Name
	if m.blockedLabels != nil {
		_, ok := m.blockedLabels[labelName]
		if ok {
			// If present, let's remove this label
			return false
		}
	}
	if m.allowedLabels != nil {
		_, ok := m.allowedLabels[labelName]
		return ok
	}
	// Allow by default
	return true
}

@Override
    public ConcurrentMap<String, Object> deserializeAttributes(final byte[] in ) {
        ByteArrayInputStream bis = null;
        ObjectInputStream ois = null;
        try {
            bis = new ByteArrayInputStream( in );
            ois = createObjectInputStream( bis );

            final ConcurrentMap<String, Object> attributes = new ConcurrentHashMap<String, Object>();
            final int n = ( (Integer) ois.readObject() ).intValue();
            for ( int i = 0; i < n; i++ ) {
                final String name = (String) ois.readObject();
                final Object value = ois.readObject();
                if ( ( value instanceof String ) && ( value.equals( NOT_SERIALIZED ) ) ) {
                    continue;
                }
                if ( LOG.isDebugEnabled() ) {
                    LOG.debug( "  loading attribute '" + name + "' with value '" + value + "'" );
                }
                attributes.put( name, value );
            }

            return attributes;
        } catch ( final ClassNotFoundException e ) {
            LOG.warn( "Caught CNFE decoding "+ in.length +" bytes of data", e );
            throw new TranscoderDeserializationException( "Caught CNFE decoding data", e );
        } catch ( final IOException e ) {
            LOG.warn( "Caught IOException decoding "+ in.length +" bytes of data", e );
            throw new TranscoderDeserializationException( "Caught IOException decoding data", e );
        } finally {
            closeSilently( bis );
            closeSilently( ois );
        }
    }

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


Question:
Return to indicate the entry can be pulled from other remote caches which caching this value.

@param share sharing policy
@id cache ID

@Override
    public boolean shouldPull(int share, Object id) {
        final String methodName = "shouldPull()";
        boolean shouldPull = false;
        if (this.featureSupport.isReplicationSupported()) {
            // TODO write code to support shouldPull function
            //if (tc.isDebugEnabled()) {
            //    Tr.debug(tc, methodName + " cacheName=" + cacheName + " ERROR because it is not implemented yet");
            //}
        } else {
            //Tr.error(tc, "DYNA1065E", new Object[] { methodName, cacheName, this.cacheProviderName});
        }
        return shouldPull;
    }

func (self *RawDispatcher) AddResourceSeparateUdid(node *RestNode, name string, wireExample interface{}, index RestIndex,
	find RestFindUdid, post RestPost, put RestPutUdid, del RestDeleteUdid) {
	t := self.validateType(wireExample)
	obj := &restObjUdid{
		restShared: restShared{
			typ:   t,
			name:  name,
			index: index,
			post:  post,
		},
		find: find,
		del:  del,
		put:  put,
	}
	node.ResUdid[strings.ToLower(name)] = obj
}

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


Question:
Generate render options
Sets the default 'details' for template rendering.

protected function generateRenderOptions(array &$options)
    {
        $i18n = $this->controller->getService('i18n');
        $defaultLocales = $i18n->fallbacks();
        array_unshift($defaultLocales, $i18n->defaultLocale());

        $format = $this->controller->request() ?
            $this->controller->request()->format() :
            null;

        if (isset($options['details'])) {
            $details = $options['details'];
        } else {
            $details = [];
        }

        if (!isset($details['formats'])) {
            $details['formats'] = [];
        }
        if ($format) {
            $details['formats'][] = $format;
        }

        if (!isset($details['handlers'])) {
            $details['handlers'] = [];
        }
        $details['handlers'] = array_merge(
            array_keys($this->actionView()->handlers()),
            $details['handlers']
        );

        if (!isset($details['locale'])) {
            $details['locale'] = [];
        }
        $details['locale'] = array_merge($defaultLocales, $details['locale']);

        $options['details'] = $details;

        $layout = $this->controller->layout();
        if ($layout === null) {
            $options['layout'] = 'application';
        } elseif (is_string($layout)) {
            $options['layout'] = $layout;
        }
    }

public function canRender(ControllerContext $controllerContext)
    {
        $this->setControllerContext($controllerContext);
        try {
            $this->getTemplateSource();
            return true;
        } catch (Exception\InvalidTemplateResourceException $e) {
            return false;
        }
    }

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


Question: // Instances returns an implementation of Instances for OpenStack.

func (os *OpenStack) Instances() (cloudprovider.Instances, bool) {
	klog.V(4).Info("openstack.Instances() called")

	compute, err := os.NewComputeV2()
	if err != nil {
		klog.Errorf("unable to access compute v2 API : %v", err)
		return nil, false
	}

	klog.V(4).Info("Claiming to support Instances")

	return &Instances{
		compute: compute,
		opts:    os.metadataOpts,
	}, true
}

func (that *JSONNode) DebugProspect(indentlevel int, indentchar string) {
	switch that.t {
	case TypeValue:
		that.debugProspectValue(indentlevel, indentchar)
	case TypeMap:
		that.debugProspectMap(indentlevel, indentchar)
	case TypeArray:
		that.debugProspectArray(indentlevel, indentchar)
	case TypeUndefined:
		printfindent(indentlevel, indentchar, "Is of Type: TypeUndefined\n")
	}
}

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


Question:
// CreateTerraformConfigVersion creatse a new Terraform configuration
// versions and uploads a slug with it.

func (c *Client) CreateTerraformConfigVersion(
	user string, name string,
	version *TerraformConfigVersion,
	data io.Reader, size int64) (int, error) {
	log.Printf("[INFO] creating terraform configuration %s/%s", user, name)

	endpoint := fmt.Sprintf(
		"/api/v1/terraform/configurations/%s/%s/versions", user, name)
	body, err := json.Marshal(&tfConfigVersionWrapper{
		Version: version,
	})
	if err != nil {
		return 0, err
	}

	request, err := c.Request("POST", endpoint, &RequestOptions{
		Body: bytes.NewReader(body),
		Headers: map[string]string{
			"Content-Type": "application/json",
		},
	})
	if err != nil {
		return 0, err
	}

	response, err := checkResp(c.HTTPClient.Do(request))
	if err != nil {
		return 0, err
	}

	var result tfConfigVersionCreate
	if err := decodeJSON(response, &result); err != nil {
		return 0, err
	}

	if err := c.putFile(result.UploadPath, data, size); err != nil {
		return 0, err
	}

	return result.Version, nil
}

def run(self, *args):

        params = self.parser.parse_args(args)

        config_file = os.path.expanduser('~/.sortinghat')

        if params.action == 'get':
            code = self.get(params.parameter, config_file)
        elif params.action == 'set':
            code = self.set(params.parameter, params.value, config_file)
        else:
            raise RuntimeError("Not get or set action given")

        return code

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


Question: // SetMarker sets the Marker field's value.

func (s *DescribeClusterParameterGroupsOutput) SetMarker(v string) *DescribeClusterParameterGroupsOutput {
	s.Marker = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

    if (isLog(4)) {
      log("change getfield " + owner + " name:" + name);
    }
    typeQueryUser = true;
  }

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


Question:
按区间范围取值
@param int|null $min
@param int|null $max
@return array

public function range(int $min=null, int $max=null)
        {
                $min      = is_null($min) ? '-inf' : $min;
                $max      = is_null($max) ? '+inf' : $max;

                $response = $this->_redis->zrevrangebyscore($this->_key, $max, $min, 'WITHSCORES');
                $result   = [];
                for($i=0,$num=count($response);$i<$num;$i++) {
                        $result[$response[$i]] = intval($response[++$i]);
                }
                return $result;
        }

public void setRange(String range) {
        String single = range.trim();
        int hyphenIndex = range.indexOf('-');

        if (hyphenIndex > 0) {
            this.start = rangeSingle(range.substring(0, hyphenIndex));
            this.end = rangeSingle(range.substring(hyphenIndex + 1));
        } else {
            int number = rangeSingle(range);
            if (number >= 0) { // first n attributes
                this.start = 0;
                this.end = number;
            } else { // last n attributes
                this.start = this.upperLimit + number > 0 ? this.upperLimit + number : 0;
                this.end = this.upperLimit - 1;
            }
        }
    }

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


Question: // CreateSignedClient creates a client with a JWT signer which uses the Auth Service Account token

func (c jwtSASigner) createSignedClient() (*clusterclient.Client, error) {
	cln, err := c.createClient(c.ctx)
	if err != nil {
		return nil, err
	}
	m, err := manager.DefaultManager(c.config)
	if err != nil {
		return nil, err
	}
	signer := m.AuthServiceAccountSigner()
	cln.SetJWTSigner(signer)
	return cln, nil
}

public static String connectOauth2Authorize(String appid,String redirect_uri,boolean snsapi_userinfo,String state){
		return connectOauth2Authorize(appid, redirect_uri, snsapi_userinfo, state, null);
	}

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


Question:
Get Country list

@param Illuminate\Http\Request $request
@return mixed Jnaxo\CountryCodes\Country collection

public function countries(Request $request = null)
    {
        $query = Country::with('zone');

        if ($request) {
            $resource = new Collection($query, 'country', $request);
            return $this->respondWithCollection($resource);
        }
        return $query->get();
    }

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

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

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

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


Question: // UnmarshalYAML implements the Unmarshaller interface.

func (n *External) UnmarshalYAML(unmarshal func(interface{}) error) error {
	if err := unmarshal(&n.External); err == nil {
		return nil
	}
	var dummyExternal struct {
		Name string
	}

	err := unmarshal(&dummyExternal)
	if err != nil {
		return err
	}
	n.Name = dummyExternal.Name
	n.External = true

	return nil
}

def get_ymal_data(data):

    try:
        format_data = yaml.load(data)
    except yaml.YAMLError, e:
        msg = "Yaml format error: {}".format(
            unicode(str(e), "utf-8")
        )
        logging.error(msg)
        sys.exit(1)

    if not check_config(format_data):
        sys.exit(1)

    return format_data

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


Question:
/* (non-Javadoc)
@see java.io.DataOutput#writeLong(long)

@Override
  public void writeLong(long v) throws IOException {
    work[0] = (byte) (0xffL & v);
    work[1] = (byte) (0xffL & (v >> 8));
    work[2] = (byte) (0xffL & (v >> 16));
    work[3] = (byte) (0xffL & (v >> 24));
    work[4] = (byte) (0xffL & (v >> 32));
    work[5] = (byte) (0xffL & (v >> 40));
    work[6] = (byte) (0xffL & (v >> 48));
    work[7] = (byte) (0xffL & (v >> 56));
    write(work, 0, 8);
  }

public String readString()
        throws IOException
    {
        int tag = read();

        switch (tag) {
            case 'N':
                return null;

            case 'I':
                return String.valueOf(parseInt());
            case 'L':
                return String.valueOf(parseLong());
            case 'D':
                return String.valueOf(parseDouble());

            case 'S':
            case 's':
            case 'X':
            case 'x':
                _isLastChunk = tag == 'S' || tag == 'X';
                _chunkLength = (read() << 8) + read();

                _sbuf.setLength(0);
                int ch;

                while ((ch = parseChar()) >= 0)
                    _sbuf.append((char) ch);

                return _sbuf.toString();

            default:
                throw expect("string", tag);
        }
    }

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


Question:
Deserialize a new GameMessage from a given dictionary.

        :return: new GameMessage instance.
        :rtype: GameMessage

def from_array(array):

        if array is None or not array:
            return None
        # end if
        assert_type_or_raise(array, dict, parameter_name="array")
        from pytgbot.api_types.sendable.reply_markup import InlineKeyboardMarkup

        data = {}
        data['game_short_name'] = u(array.get('game_short_name'))
        if array.get('chat_id') is None:
            data['receiver'] = None
        elif isinstance(array.get('chat_id'), None):
            data['receiver'] = None(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), str):
            data['receiver'] = u(array.get('chat_id'))
        elif isinstance(array.get('chat_id'), int):
            data['receiver'] = int(array.get('chat_id'))
        else:
            raise TypeError('Unknown type, must be one of None, str, int or None.')
        # end if
        if array.get('reply_to_message_id') is None:
            data['reply_id'] = None
        elif isinstance(array.get('reply_to_message_id'), DEFAULT_MESSAGE_ID):
            data['reply_id'] = DEFAULT_MESSAGE_ID(array.get('reply_to_message_id'))
        elif isinstance(array.get('reply_to_message_id'), int):
            data['reply_id'] = int(array.get('reply_to_message_id'))
        else:
            raise TypeError('Unknown type, must be one of DEFAULT_MESSAGE_ID, int or None.')
        # end if
        data['disable_notification'] = bool(array.get('disable_notification')) if array.get('disable_notification') is not None else None
        data['reply_markup'] = InlineKeyboardMarkup.from_array(array.get('reply_markup')) if array.get('reply_markup') is not None else None
        return GameMessage(**data)

def create_event_object(self,
                            event_type,
                            code,
                            value,
                            timeval=None):
        """"""
        if not timeval:
            self.update_timeval()
            timeval = self.timeval
        try:
            event_code = self.type_codes[event_type]
        except KeyError:
            raise UnknownEventType(
                "We don't know what kind of event a %s is." % event_type)

        event = struct.pack(EVENT_FORMAT,
                            timeval[0],
                            timeval[1],
                            event_code,
                            code,
                            value)
        return event

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


Question:
// Lex Valid Json
//
//    Must start with { or [
//

func LexJson(l *Lexer) StateFn {

	l.SkipWhiteSpaces()
	if l.IsEnd() {
		return nil
	}
	r := l.Peek()
	//u.Debugf("LexJson  '%v'  %v", string(r), l.PeekX(10))
	switch r {
	case '{', '[':
		return LexJsonValue
	}
	//u.Warnf("Did not find json? %v", l.PeekX(20))
	return nil
}

def parse_yaml_from_file(path):
    '''  '''

    try:
        data = file(path).read()
        return parse_yaml(data)
    except IOError:
        raise errors.AnsibleError("file not found: %s" % path)
    except yaml.YAMLError, exc:
        if hasattr(exc, 'problem_mark'):
            mark = exc.problem_mark
            if mark.line -1 >= 0:
                before_probline = data.split("\n")[mark.line-1]
            else:
                before_probline = ''
            probline = data.split("\n")[mark.line]
            arrow = " " * mark.column + "^"
            msg = """Syntax Error while loading YAML script, %s
Note: The error may actually appear before this position: line %s, column %s

%s
%s
%s""" % (path, mark.line + 1, mark.column + 1, before_probline, probline, arrow)
        else:
            # No problem markers means we have to throw a generic
            # "stuff messed up" type message. Sry bud.
            msg = "Could not parse YAML. Check over %s again." % path
        raise errors.AnsibleYAMLValidationFailed(msg)

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


Question: Clone a remote git repo into a local directory.

def clone_from(repo_url, repo_dir):
    """"""
    repo_url = _fix_repo_url(repo_url)
    LOG.info("Cloning %s into %s." % (repo_url, repo_dir))
    cmd = GIT_CLONE_CMD.format(repo_url, repo_dir)
    resp = envoy.run(cmd)
    if resp.status_code != 0:
        LOG.error("Cloned failed: %s" % resp.std_err)
        raise GitException(resp.std_err)
    LOG.info("Clone successful.")

function lazyClone() {
      var result = new LazyWrapper(this.__wrapped__);
      result.__actions__ = copyArray(this.__actions__);
      result.__dir__ = this.__dir__;
      result.__filtered__ = this.__filtered__;
      result.__iteratees__ = copyArray(this.__iteratees__);
      result.__takeCount__ = this.__takeCount__;
      result.__views__ = copyArray(this.__views__);
      return result;
    }

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


Question: // SetSqlInjectionMatchSetId sets the SqlInjectionMatchSetId field's value.

func (s *SqlInjectionMatchSet) SetSqlInjectionMatchSetId(v string) *SqlInjectionMatchSet {
	s.SqlInjectionMatchSetId = &v
	return s
}

protected function matchedId($filter): bool
    {
        if (!$this instanceof IdentifiableEntity) {
            return false;
        }

        $id = $this->getId();

        return is_scalar($id) && is_scalar($filter) ? (string)$id === (string)$filter : $id === $filter;
    }

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


Question:
The default behavior of this method is to return setHeader(String name, String value)
on the wrapped response object.

@Override
    public void setHeader(String name, String value) {
        this._getHttpServletResponse().setHeader(name, value);
    }

def set_headers(self, headers):

        self.headers = []
        if 'order' in self.options:
            for element in self.options['order']:
                for header in headers:
                    if header['key'] == element:
                        self.headers.append(header)
                        break
        else:
            self.headers = headers

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


Question:
Set a view variable

@param string $variable
@param mixed $value
@return \JiNexus\Mvc\View\ViewInterface

public function set($variable, $value = null)
    {
        $this->variables[$variable] = array(
            'safe' => $this->htmlEncode($value),
            'unsafe' => $value
        );

        return $this;
    }

function template(templateSpec, env) {
            /* istanbul ignore next */
            if (!env) {
                throw new Exception("No environment passed to template");
            }
            if (!templateSpec || !templateSpec.main) {
                throw new Exception('Unknown template object: ' + typeof templateSpec);
            }

            // Note: Using env.VM references rather than local var references throughout this section to allow
            // for external users to override these as psuedo-supported APIs.
            env.VM.checkRevision(templateSpec.compiler);

            var invokePartialWrapper = function(partial, indent, name, context, hash, helpers, partials, data, depths) {
                if (hash) {
                    context = Utils.extend({}, context, hash);
                }

                var result = env.VM.invokePartial.call(this, partial, name, context, helpers, partials, data, depths);

                if (result == null && env.compile) {
                    var options = { helpers: helpers, partials: partials, data: data, depths: depths };
                    partials[name] = env.compile(partial, { data: data !== undefined, compat: templateSpec.compat }, env);
                    result = partials[name](context, options);
                }
                if (result != null) {
                    if (indent) {
                        var lines = result.split('\n');
                        for (var i = 0, l = lines.length; i < l; i++) {
                            if (!lines[i] && i + 1 === l) {
                                break;
                            }

                            lines[i] = indent + lines[i];
                        }
                        result = lines.join('\n');
                    }
                    return result;
                } else {
                    throw new Exception("The partial " + name + " could not be compiled when running in runtime-only mode");
                }
            };

            // Just add water
            var container = {
                lookup: function(depths, name) {
                    var len = depths.length;
                    for (var i = 0; i < len; i++) {
                        if (depths[i] && depths[i][name] != null) {
                            return depths[i][name];
                        }
                    }
                },
                lambda: function(current, context) {
                    return typeof current === 'function' ? current.call(context) : current;
                },

                escapeExpression: Utils.escapeExpression,
                invokePartial: invokePartialWrapper,

                fn: function(i) {
                    return templateSpec[i];
                },

                programs: [],
                program: function(i, data, depths) {
                    var programWrapper = this.programs[i],
                        fn = this.fn(i);
                    if (data || depths) {
                        programWrapper = program(this, i, fn, data, depths);
                    } else if (!programWrapper) {
                        programWrapper = this.programs[i] = program(this, i, fn);
                    }
                    return programWrapper;
                },

                data: function(data, depth) {
                    while (data && depth--) {
                        data = data._parent;
                    }
                    return data;
                },
                merge: function(param, common) {
                    var ret = param || common;

                    if (param && common && (param !== common)) {
                        ret = Utils.extend({}, common, param);
                    }

                    return ret;
                },

                noop: env.VM.noop,
                compilerInfo: templateSpec.compiler
            };

            var ret = function(context, options) {
                options = options || {};
                var data = options.data;

                ret._setup(options);
                if (!options.partial && templateSpec.useData) {
                    data = initData(context, data);
                }
                var depths;
                if (templateSpec.useDepths) {
                    depths = options.depths ? [context].concat(options.depths) : [context];
                }

                return templateSpec.main.call(container, context, container.helpers, container.partials, data, depths);
            };
            ret.isTop = true;

            ret._setup = function(options) {
                if (!options.partial) {
                    container.helpers = container.merge(options.helpers, env.helpers);

                    if (templateSpec.usePartial) {
                        container.partials = container.merge(options.partials, env.partials);
                    }
                } else {
                    container.helpers = options.helpers;
                    container.partials = options.partials;
                }
            };

            ret._child = function(i, data, depths) {
                if (templateSpec.useDepths && !depths) {
                    throw new Exception('must pass parent depths');
                }

                return program(container, i, templateSpec[i], data, depths);
            };
            return ret;
        }

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


Question:
/*
Fix for resolving local path
@param {Metalsmith} metalsmith The metalsmith instance
@returns The absolute path including initial globbing pattern

function resolvePath(metalsmith) {
    var globStart = false;                            // Indicator, if globbing pattern was found yet
    var cwd = metalsmith.directory();                 // Get Metalsmith working directory
    var subPath = [];
    var pattern = [];
    var directory = dir.split('/');
    directory.forEach(function parsePathElems(elem) {
      if (globStart || elem.search(/[^a-z0-9\.\-_]/gi) >= 0) {   // Search in current path segment for glob patterns
        globStart = true;                 // If true, set globStart to true
        return pattern.push(elem);        // add to pattern now and in future automatically
      }
      return subPath.push(elem);
    });

    // Now check if calculated path is existing (absolute vs relative position to Metalsmith CWD)
    var localPath = path.resolve(cwd, subPath.join('/'));   // Assume path is relative to CWD, e.g. ./src/*.json
    if (!fs.existsSync(path.resolve(cwd, localPath))) {
      localPath = path.relative(cwd, subPath.join('/'));    // Assumption false, it was absolute, e.g. ./test/fixtures/...
    }

    return path.resolve(cwd, localPath, pattern.join('/')); // return correct path
  }

public static function route() :void {

		// marker
		Profiler::setMarker('Router.route', 'framework');
		// get the requested url
		$request_url = Request::getUrl();
		// get the requested method
		$request_method = Request::getMethod();
		// Loop over each route and test to see if they are valid
		foreach(self::$_routes as $route) {
			// if the route matches
			if(self::routeMatch($request_url, $request_method, $route)) {
				// get it
				$matching_route = $route;
				// stop trying
				break;
			}
		}
		// marker
		Profiler::releaseMarker('Router.route');
		// if no match is found and we don't have an error route to fallback on
		if(!isset($matching_route)) {
			// throw a native exception since there is no cleaner alternative
			Throw new Exception('Router::route() no matching route', 404);
		}
		// send the matching route to the dispatcher
		self::forward($matching_route);

	}

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


Question: Removes the current query container.

def exitContainer(self):

        try:
            entry = self._compoundStack.pop()
        except IndexError:
            return

        container = self.currentContainer()
        entry.setQuery(container.query())

        self.slideInPrev()

public function clearInstance(string $class, string $selector = Injector::DEFAULT_SELECTOR)
    {
        if (!isset($this->objects[$class]))
            return;

        unset($this->objects[$class][$selector]);
    }

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


Question:
@param ConfigRepository $config

@return string

private function getSiteId($config)
    {
        $result = $this->siteId;
        if ($this->useSiteId) {
            $result = $config->get(Option::SITE_ID);
        }

        return $result;
    }

public function set($key, $value, \DatePeriod $period = null)
    {
        if (is_null($period)) {
            $this->repository->set($key, $value);
        } else {
            $this->setForPeriod($key, $value, $period);
        }
    }

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


Question:
Validates category translations
@return boolean|null

protected function validateTranslation()
    {
        $translations = $this->getSubmitted('translation');

        if (empty($translations)) {
            return null;
        }

        $lengths = array(
            'meta_title' => 60,
            'meta_description' => 160
        );

        foreach ($translations as $lang => $translation) {
            foreach ($translation as $field => $value) {

                if ($value === '') {
                    unset($translations[$lang][$field]);
                    continue;
                }

                $max = isset($lengths[$field]) ? $lengths[$field] : 255;

                if (mb_strlen($value) > $max) {
                    $label = ucfirst(str_replace('_', ' ', $field));
                    $this->setErrorLengthRange("translation.$lang.$field", $label, 0, $max);
                }
            }

            if (empty($translations[$lang])) {
                unset($translations[$lang]);
            }
        }

        $this->setSubmitted('translation', $translations);
        return !$this->isError('translation');
    }

public function unreviewed(LocaleEntity $locale)
    {
        $rs = $this->getUnreviewedSelectQuery($locale);

        $result = $this->buildTranslations($locale, $rs);

        $result->setHeader('Project-Id-Version', 'unreviewed');

        return $result;
    }

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


Question:
Map from GDS to Google Protocol Buffer

@param Entity $obj_gds_entity
@param \google\appengine\datastore\v4\Entity $obj_entity

public function mapToGoogle(Entity $obj_gds_entity, \google\appengine\datastore\v4\Entity $obj_entity)
    {
        // Key
        $this->configureGoogleKey($obj_entity->mutableKey(), $obj_gds_entity);

        // Properties
        $arr_field_defs = $this->obj_schema->getProperties();
        foreach($obj_gds_entity->getData() as $str_field_name => $mix_value) {
            $obj_prop = $obj_entity->addProperty();
            $obj_prop->setName($str_field_name);
            $obj_val = $obj_prop->mutableValue();
            if(isset($arr_field_defs[$str_field_name])) {
                $this->configureGooglePropertyValue($obj_val, $arr_field_defs[$str_field_name], $mix_value);
            } else {
                $arr_dynamic_data = $this->determineDynamicType($mix_value);
                $this->configureGooglePropertyValue($obj_val, ['type' => $arr_dynamic_data['type'], 'index' => TRUE], $arr_dynamic_data['value']);
            }
        }
    }

def _deserialize(s, proto):  # type: (bytes, _Proto) -> _Proto
    '''

    '''
    if not isinstance(s, bytes):
        raise ValueError('Parameter s must be bytes, but got type: {}'.format(type(s)))

    if not (hasattr(proto, 'ParseFromString') and callable(proto.ParseFromString)):
        raise ValueError('No ParseFromString method is detected. '
                         '\ntype is {}'.format(type(proto)))

    decoded = cast(Optional[int], proto.ParseFromString(s))
    if decoded is not None and decoded != len(s):
        raise google.protobuf.message.DecodeError(
            "Protobuf decoding consumed too few bytes: {} out of {}".format(
                decoded, len(s)))
    return proto

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


Question:
Calls the REST API Method by using HTTP GET
@param string $methodName        method name (ie. statuses/home_timeline)
@param array $params             key-value parameter for method
@return array

public function get($methodName, array $params = array())
    {
        $options = array_merge($this->defaultApiOptions, $this->createConfigByMethodName($methodName));
        $options['http'] = 'get';
        return $this->internalCall($methodName, $options, $params);
    }

public GitLabApiForm withParam(String name, Object value) throws IllegalArgumentException {
        return (withParam(name, value, false));
    }

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


Question:
// SetStatus updates the raw status for the identified payload to the
// provided value. If the payload is missing then payload.ErrNotFound
// is returned.

func (up UnitPayloads) SetStatus(name, status string) error {
	if err := payload.ValidateState(status); err != nil {
		return errors.Trace(err)
	}

	change := payloadSetStatusChange{
		Unit:   up.unit,
		Name:   name,
		Status: status,
	}
	if err := Apply(up.db, change); err != nil {
		return errors.Trace(err)
	}
	return nil
}

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

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


Question:
Return the extra classes as concatenated strings

@return String $classes

protected function getTableExtraClassesString()
  {
    $classes_html = '';

    if( ! empty($this->table_extra_classes) )
    {
      foreach($this->table_extra_classes as $class)
      {
        $classes_html.= "{$class} ";
      }
    }

    return $classes_html;
  }

public static function add_namespaces(array $namespaces, $prepend = false)
	{
		if ( ! $prepend)
		{
			static::$namespaces = array_merge(static::$namespaces, $namespaces);
		}
		else
		{
			static::$namespaces = $namespaces + static::$namespaces;
		}
	}

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


Question: Write a pending tag attribute from *data* to the stack.

def _push_tag_buffer(self, data):
        """"""
        if data.context & data.CX_QUOTED:
            self._emit_first(tokens.TagAttrQuote(char=data.quoter))
            self._emit_all(self._pop())
        buf = data.padding_buffer
        self._emit_first(tokens.TagAttrStart(
            pad_first=buf["first"], pad_before_eq=buf["before_eq"],
            pad_after_eq=buf["after_eq"]))
        self._emit_all(self._pop())
        for key in data.padding_buffer:
            data.padding_buffer[key] = ""

def send(self, command, payload):

        request = WorkRequest(command, payload)
        logging.info("Sending {} message to queue {}.".format(request.command, self.queue_name))
        # setting protocol to version 2 to be compatible with python2
        self.connection.send_durable_message(self.queue_name, pickle.dumps(request, protocol=2))
        logging.info("Sent {} message.".format(request.command, self.queue_name))

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


Question: InternalXtext.g:2351:1: entryRuleAssignment returns [EObject current=null] : iv_ruleAssignment= ruleAssignment EOF ;

public final EObject entryRuleAssignment() throws RecognitionException {
        EObject current = null;

        EObject iv_ruleAssignment = null;

        try {
            // InternalXtext.g:2351:51: (iv_ruleAssignment= ruleAssignment EOF )
            // InternalXtext.g:2352:2: iv_ruleAssignment= ruleAssignment EOF
            {
             newCompositeNode(grammarAccess.getAssignmentRule());
            pushFollow(FollowSets000.FOLLOW_1);
            iv_ruleAssignment=ruleAssignment();

            state._fsp--;

             current =iv_ruleAssignment;
            match(input,EOF,FollowSets000.FOLLOW_2);

            }

        }

            catch (RecognitionException re) {
                recover(input,re);
                appendSkippedTokens();
            }
        finally {
        }
        return current;
    }

func (s *state) validateType(value reflect.Value, typ reflect.Type) reflect.Value {
	if !value.IsValid() {
		if typ == nil || canBeNil(typ) {
			// An untyped nil interface{}. Accept as a proper nil value.
			return reflect.Zero(typ)
		}
		s.errorf("invalid value; expected %s", typ)
	}
	if typ != nil && !value.Type().AssignableTo(typ) {
		if value.Kind() == reflect.Interface && !value.IsNil() {
			value = value.Elem()
			if value.Type().AssignableTo(typ) {
				return value
			}
			// fallthrough
		}
		// Does one dereference or indirection work? We could do more, as we
		// do with method receivers, but that gets messy and method receivers
		// are much more constrained, so it makes more sense there than here.
		// Besides, one is almost always all you need.
		switch {
		case value.Kind() == reflect.Ptr && value.Type().Elem().AssignableTo(typ):
			value = value.Elem()
			if !value.IsValid() {
				s.errorf("dereference of nil pointer of type %s", typ)
			}
		case reflect.PtrTo(value.Type()).AssignableTo(typ) && value.CanAddr():
			value = value.Addr()
		default:
			s.errorf("wrong type for value; expected %s; got %s", typ, value.Type())
		}
	}
	return value
}

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


Question: Send email with reset password link.

def send_reset_password_link(request):
    '''

    '''
    if not registration_settings.RESET_PASSWORD_VERIFICATION_ENABLED:
        raise Http404()
    serializer = SendResetPasswordLinkSerializer(data=request.data)
    serializer.is_valid(raise_exception=True)
    login = serializer.validated_data['login']

    user = None
    for login_field in get_login_fields():
        user = get_user_by_lookup_dict(
            {login_field: login}, default=None, require_verified=False)
        if user:
            break

    if not user:
        raise UserNotFound()

    signer = ResetPasswordSigner({
        'user_id': user.pk,
    }, request=request)

    template_config = (
        registration_settings.RESET_PASSWORD_VERIFICATION_EMAIL_TEMPLATES)
    send_verification_notification(user, signer, template_config)

    return get_ok_response('Reset link sent')

func (s *Organization) SetMasterAccountEmail(v string) *Organization {
	s.MasterAccountEmail = &v
	return s
}

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


Question:
Determine content encoding by reviewing message headers.

 @raise [InvalidEncodingError] if encoding does not exist in Ruby
 @return [Encoding]

def content_encoding
      if content_type = headers["content-type"]
        mime_type, charset = content_type.split(SEMICOLON, 2)
        charset = charset[CHARSET_OFFSET] if charset
        charset ||= EMPTY

        if charset.empty? and mime_type.start_with?("text/")
          Encoding::UTF_8
        elsif charset.empty?
          Encoding::BINARY
        else
          ENCODINGS[charset] or raise StompParser::InvalidEncodingError, "invalid encoding #{charset.inspect}"
        end
      else
        Encoding::BINARY
      end
    end

def audio_type(hsh)
      if !hsh.nil? && hsh.length
        hsh['mp3'] ? mime_type('mp3') : hsh['m4a'] ? mime_type('m4a') : hsh['ogg'] ? mime_type('ogg') : mime_type('opus')
      end
    end

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


Question:
Prints debug info.
@param msg {String} the message to log.
@param {String} [cat] the log category for the message. Default
categories are 'info', 'warn', 'error', 'time' etc.
@param {String} [logger] the logger of the the message (opt)

function (msg, cat, logger) {
            if ('@DEBUG@') {
                var matched = 1;
                if (logger) {
                    var list, i, l, level, minLevel, maxLevel, reg;
                    cat = cat || 'debug';
                    level = loggerLevel[cat] || loggerLevel.debug;
                    if ((list = config.includes)) {
                        matched = 0;
                        for (i = 0; i < list.length; i++) {
                            l = list[i];
                            reg = l.logger;
                            maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error;
                            minLevel = loggerLevel[l.minLevel] || loggerLevel.debug;
                            if (minLevel <= level && maxLevel >= level && logger.match(reg)) {
                                matched = 1;
                                break;
                            }
                        }
                    } else if ((list = config.excludes)) {
                        matched = 1;
                        for (i = 0; i < list.length; i++) {
                            l = list[i];
                            reg = l.logger;
                            maxLevel = loggerLevel[l.maxLevel] || loggerLevel.error;
                            minLevel = loggerLevel[l.minLevel] || loggerLevel.debug;
                            if (minLevel <= level && maxLevel >= level && logger.match(reg)) {
                                matched = 0;
                                break;
                            }
                        }
                    }
                    if (matched) {
                        msg = logger + ': ' + msg;
                    }
                }
                /*global console*/
                if (matched) {
                    if (typeof console !== 'undefined' && console.log) {
                        console[cat && console[cat] ? cat : 'log'](msg);
                    }
                    return msg;
                }
            }
            return undefined;
        }

private function argumentsAsText()
    {
        $max = $this->getMaxWidth();
        $messages = [];

        $arguments = $this->getArguments();
        if (!empty($arguments)) {
            $messages[] = '<comment>Arguments:</comment>';
            foreach ($arguments as $argument) {
                if (null !== $argument->getDefault() && (!\is_array($argument->getDefault()) || \count($argument->getDefault()))) {
                    $default = \sprintf('<comment> (default: %s)</comment>', $this->formatDefaultValue($argument->getDefault()));
                } else {
                    $default = '';
                }

                $description = \str_replace("\n", "\n" . \str_pad('', $max + 2, ' '), $argument->getDescription());

                $messages[] = \sprintf(" <info>%-${max}s</info> %s%s", $argument->getName(), $description, $default);
            }

            $messages[] = '';
        }

        return \implode(PHP_EOL, $messages);
    }

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


Question:
Get the Message html body with embedded image urls
the resulting $body.

@param string $route_name
@param array $params

@return null|string

public function getHTMLBodyWithEmbeddedUrlImages($route_name, $params = []) {
        return $this->getCustomHTMLBody(function($body, $oAttachment) use($route_name, $params){
            /** @var \Webklex\IMAP\Attachment $oAttachment */
            if ($oAttachment->id && $oAttachment->getImgSrc() != null) {
                $oMessage = $oAttachment->getMessage();

                $image_url = route($route_name, array_merge([
                    'muid' => urlencode($oMessage->uid),
                    'mid' => urlencode($oMessage->message_id),
                    'mti' => urlencode($oMessage->date->timestamp),
                    'aid' => urlencode($oAttachment->id)
                ], $params));

                $body = str_replace('cid:'.$oAttachment->id, $image_url, $body);
            }

            return $body;
        });
    }

@Override
    public Map<String, Object> getBodyParameters() {
        HashMap<String, Object> params = new HashMap<String, Object>();
        return params;
    }

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


Question: /* [MS-CFB] 2.6.4

function namecmp(l, r) {
	var L = l.split("/"), R = r.split("/");
	for(var i = 0, c = 0, Z = Math.min(L.length, R.length); i < Z; ++i) {
		if((c = L[i].length - R[i].length)) return c;
		if(L[i] != R[i]) return L[i] < R[i] ? -1 : 1;
	}
	return L.length - R.length;
}

@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case AfplibPackage.CMR_FIDELITY__STP_CMR_EX:
				return STP_CMR_EX_EDEFAULT == null ? stpCMREx != null : !STP_CMR_EX_EDEFAULT.equals(stpCMREx);
			case AfplibPackage.CMR_FIDELITY__REP_CMR_EX:
				return REP_CMR_EX_EDEFAULT == null ? repCMREx != null : !REP_CMR_EX_EDEFAULT.equals(repCMREx);
		}
		return super.eIsSet(featureID);
	}

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


Question:
// NewEncoding creates a new base-N representation from the given alphabet.
// Panics if the alphabet is not unique. Only ASCII characters are supported.

func NewEncoding(alphabet string) *Encoding {
	return &Encoding{
		alphabet: alphabet,
		index:    newAlphabetMap(alphabet),
		base:     big.NewInt(int64(len(alphabet))),
	}
}

def write(self):

        csv_file = os.path.join(self.outdir, 'search_results.csv')
        txt_file = os.path.join(self.outdir, 'unresolved.txt')
        headers = self.key_terms
        unresolved = []
        with open(csv_file, 'w') as file:
            writer = csv.writer(file)
            writer.writerow(headers)
            for key in list(self._store.keys()):
                results = self._store[key]
                if len(results) == 0:
                    unresolved.append(key)
                else:
                    row = [key]
                    for key_term in headers[1:]:
                        element = results[0][key_term]
                        # GNR returns UTF-8, csv requires ascii
                        #
                        # *** Note ***
                        # According to all docs for csv versions >= 2.6, csv
                        # can handle either UTF-8 or ascii, just not Unicode.
                        # In py3, the following two lines result in csv printing
                        # the element with a bitstring. If GNR is actually
                        # returning UTF-8, it seems easiest to just drop these

                        # if 'encode' in dir(element):
                        #     element = element.encode('ascii')
                        row.append(element)
                    writer.writerow(row)
        if len(unresolved) > 0:
            with open(txt_file, 'w') as file:
                for name in unresolved:
                    file.write("{0}\n".format(name))

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


Question: // Point specifies a point to create the range distance facets from.

func (s GeoDistanceSort) Point(lat, lon float64) GeoDistanceSort {
	s.points = append(s.points, GeoPointFromLatLon(lat, lon))
	return s
}

def locus_features(self, locus):

        features = self.api.list_features(locus=locus)
        feat_dict = {":".join([a.locus, str(a.rank), a.term, a.sequence]): a.accession for a in features}
        return feat_dict

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


Question: Marshall the given parameter object.

public void marshall(GetDataSourceRequest getDataSourceRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getDataSourceRequest.getApiId(), APIID_BINDING);
            protocolMarshaller.marshall(getDataSourceRequest.getName(), NAME_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
    {
        $this->_prepareParamsData($data);
    }

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


Question: Returns object: .type: 0: coplanar-front 1: coplanar-back 2: front 3: back 4: spanning In case the polygon is spanning, returns: .front: a Polygon3 of the front part .back: a Polygon3 of the back part

function splitPolygonByPlane (splane, polygon) {
  let result = {
    type: null,
    front: null,
    back: null
  }
  // cache in local lets (speedup):
  let vertices = polygon.vertices
  let numvertices = vertices.length
  if (plane.equals(polygon.plane, splane)) {
    result.type = 0
  } else {
    let hasfront = false
    let hasback = false
    let vertexIsBack = []
    let MINEPS = -EPS
    for (let i = 0; i < numvertices; i++) {
      let t = vec3.dot(splane, vertices[i]) - splane[3]
      let isback = (t < 0)
      vertexIsBack.push(isback)
      if (t > EPS) hasfront = true
      if (t < MINEPS) hasback = true
    }
    if ((!hasfront) && (!hasback)) {
      // all points coplanar
      let t = vec3.dot(splane, polygon.plane)
      result.type = (t >= 0) ? 0 : 1
    } else if (!hasback) {
      result.type = 2
    } else if (!hasfront) {
      result.type = 3
    } else {
      // spanning
      result.type = 4
      let frontvertices = []
      let backvertices = []
      let isback = vertexIsBack[0]
      for (let vertexindex = 0; vertexindex < numvertices; vertexindex++) {
        let vertex = vertices[vertexindex]
        let nextvertexindex = vertexindex + 1
        if (nextvertexindex >= numvertices) nextvertexindex = 0
        let nextisback = vertexIsBack[nextvertexindex]
        if (isback === nextisback) {
          // line segment is on one side of the plane:
          if (isback) {
            backvertices.push(vertex)
          } else {
            frontvertices.push(vertex)
          }
        } else {
          // line segment intersects plane:
          let point = vertex
          let nextpoint = vertices[nextvertexindex]
          let intersectionpoint = splitLineSegmentByPlane(splane, point, nextpoint)
          if (isback) {
            backvertices.push(vertex)
            backvertices.push(intersectionpoint)
            frontvertices.push(intersectionpoint)
          } else {
            frontvertices.push(vertex)
            frontvertices.push(intersectionpoint)
            backvertices.push(intersectionpoint)
          }
        }
        isback = nextisback
      } // for vertexindex
      // remove duplicate vertices:
      let EPS_SQUARED = EPS * EPS
      if (backvertices.length >= 3) {
        let prevvertex = backvertices[backvertices.length - 1]
        for (let vertexindex = 0; vertexindex < backvertices.length; vertexindex++) {
          let vertex = backvertices[vertexindex]
          if (vec3.squaredDistance(vertex, prevvertex) < EPS_SQUARED) {
            backvertices.splice(vertexindex, 1)
            vertexindex--
          }
          prevvertex = vertex
        }
      }
      if (frontvertices.length >= 3) {
        let prevvertex = frontvertices[frontvertices.length - 1]
        for (let vertexindex = 0; vertexindex < frontvertices.length; vertexindex++) {
          let vertex = frontvertices[vertexindex]
          if (vec3.squaredDistance(vertex, prevvertex) < EPS_SQUARED) {
            frontvertices.splice(vertexindex, 1)
            vertexindex--
          }
          prevvertex = vertex
        }
      }
      if (frontvertices.length >= 3) {
        result.front = poly3.fromPoints(frontvertices, polygon.plane)
      }
      if (backvertices.length >= 3) {
        result.back = poly3.fromPoints(backvertices, polygon.plane)
      }
    }
  }
  return result
}

def fcoe_get_interface_output_fcoe_intf_list_fcoe_intf_time_since_last_change(self, **kwargs):

        config = ET.Element("config")
        fcoe_get_interface = ET.Element("fcoe_get_interface")
        config = fcoe_get_interface
        output = ET.SubElement(fcoe_get_interface, "output")
        fcoe_intf_list = ET.SubElement(output, "fcoe-intf-list")
        fcoe_intf_fcoe_port_id_key = ET.SubElement(fcoe_intf_list, "fcoe-intf-fcoe-port-id")
        fcoe_intf_fcoe_port_id_key.text = kwargs.pop('fcoe_intf_fcoe_port_id')
        fcoe_intf_time_since_last_change = ET.SubElement(fcoe_intf_list, "fcoe-intf-time-since-last-change")
        fcoe_intf_time_since_last_change.text = kwargs.pop('fcoe_intf_time_since_last_change')

        callback = kwargs.pop('callback', self._callback)
        return callback(config)

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


Question: Throws away all journaled data starting at the given changeset

def discard(self, changeset_id: uuid.UUID) -> None:

        self._validate_changeset(changeset_id)
        self.journal.pop_changeset(changeset_id)

def reset_hba(self):
        """"""
        status = self.get_status()
        if status == 'not-initialized':
            raise ClusterError(
                'cannot modify HBA records: cluster is not initialized')

        pg_hba = os.path.join(self._data_dir, 'pg_hba.conf')

        try:
            with open(pg_hba, 'w'):
                pass
        except IOError as e:
            raise ClusterError(
                'cannot modify HBA records: {}'.format(e)) from e

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


Question:
Execute command.

@param InputInterface  $input  Input
@param OutputInterface $output Output

@return int|null|void

@throws Exception

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->startCommand($output, false);
        $domains = $input->getOption('domain');
        $languages = $input->getOption('language');
        $project = $this->createProjectByInput($input);

        while (true) {
            $randomTranslation = $project->getRandomMissingTranslation(
                $domains,
                $languages
            );

            if (!($randomTranslation instanceof Translation)) {
                $this
                    ->printMessage(
                        $output,
                        'Trans Server',
                        'No more translations for you!'
                    );

                break;
            }

            $masterTranslation = $randomTranslation->getMasterTranslation();
            $translator = new TranslateClient(
                $masterTranslation->getLanguage(),
                $randomTranslation->getLanguage()
            );
            $translation = $translator->translate(
                $masterTranslation->getValue()
            );

            $this
                ->printMessage(
                    $output,
                    'Trans Server',
                    'Language : ' . $randomTranslation->getLanguage()
                );
            $this->printMessage(
                    $output,
                    'Trans Server',
                    'Key : ' . $randomTranslation->getKey()
                );
            $this->printMessage(
                    $output,
                    'Trans Server',
                    'Original : ' . $randomTranslation
                        ->getMasterTranslation()
                        ->getValue()
                );
            $this->printMessage(
                    $output,
                    'Trans Server',
                    'Translation : ' . $translation
                );

            $randomTranslation->setValue($translation);
            $masterStructure = $randomTranslation->getStructure();
            $this->overwriteLastValueFromStructure(
                $masterStructure,
                $translation
            );
            $randomTranslation->setStructure($masterStructure);

            $project
                ->addTranslation($randomTranslation)
                ->save();
            $output->writeln('');
        }

        $this->finishCommand($output);
    }

public static void main( String [] args )
    {
        if ( args.length > 0 ) {
            String filename = args[0];

            String [] bshArgs;
            if ( args.length > 1 ) {
                bshArgs = new String [ args.length -1 ];
                System.arraycopy( args, 1, bshArgs, 0, args.length-1 );
            } else
                bshArgs = new String [0];

            try {
                Interpreter interpreter = new Interpreter();
                interpreter.setu( "bsh.args", bshArgs );
                Object result =
                    interpreter.source( filename, interpreter.globalNameSpace );
                if ( result instanceof Class )
                    try {
                        invokeMain( (Class<?>)result, bshArgs );
                    } catch ( Exception e )
                    {
                        Object o = e;
                        if ( e instanceof InvocationTargetException )
                            o = e.getCause();
                        System.err.println(
                            "Class: "+result+" main method threw exception:"+o);
                    }
            } catch ( FileNotFoundException e ) {
                System.err.println("File not found: "+e);
            } catch ( TargetError e ) {
                System.err.println("Script threw exception: "+e);
                if ( e.inNativeCode() )
                    e.printStackTrace( DEBUG.get(), System.err );
            } catch ( EvalError e ) {
                System.err.println("Evaluation Error: "+e);
            } catch ( IOException e ) {
                System.err.println("I/O Error: "+e);
            }
        } else {
            @SuppressWarnings("resource")
            Interpreter interpreter =
            new Interpreter(new CommandLineReader(
                new FileReader(System.in)),
                System.out, System.err, true );
            interpreter.run();
        }
    }

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


Question: Converts a KEY/DNSKEY record into a PublicKey

static PublicKey
toPublicKey(KEYBase r) throws DNSSECException {
	int alg = r.getAlgorithm();
	try {
		switch (alg) {
		case Algorithm.RSAMD5:
		case Algorithm.RSASHA1:
		case Algorithm.RSA_NSEC3_SHA1:
		case Algorithm.RSASHA256:
		case Algorithm.RSASHA512:
			return toRSAPublicKey(r);
		case Algorithm.DSA:
		case Algorithm.DSA_NSEC3_SHA1:
			return toDSAPublicKey(r);
		case Algorithm.ECC_GOST:
			return toECGOSTPublicKey(r, GOST);
		case Algorithm.ECDSAP256SHA256:
			return toECDSAPublicKey(r, ECDSA_P256);
		case Algorithm.ECDSAP384SHA384:
			return toECDSAPublicKey(r, ECDSA_P384);
		default:
			throw new UnsupportedAlgorithmException(alg);
		}
	}
	catch (IOException e) {
		throw new MalformedKeyException(r);
	}
	catch (GeneralSecurityException e) {
		throw new DNSSECException(e.toString());
	}
}

func (s *CloudWatchEncryption) SetKmsKeyArn(v string) *CloudWatchEncryption {
	s.KmsKeyArn = &v
	return s
}

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


Question:
Read up to "len" bytes into this buffer, starting at "off".
If the layer above needs more data, it asks for more, so we
are responsible only for blocking to fill at most one buffer,
and returning "-1" on non-fault EOF status.

@Override
    public synchronized int read(final byte buf[], final int off, final int len)
            throws IOException {
        while (this.currentRecord.needsData()) {
            final byte[] data = new byte[len];
            final int read = this.inputStream.read(data);
            if (read == -1) {
                return read;
            }
            lastBuffer = ByteBuffer.wrap(data, 0, read);
            this.currentRecord.addData(lastBuffer);
        }
        final int bytesRead = this.currentRecord.drainData(buf, off, len);
        if (!this.currentRecord.hasMoreData()) {
            LOG.info("Resetting app record");
            this.currentRecord = new InputRecord(readKey);
            if (lastBuffer != null) {
                this.currentRecord.addData(lastBuffer);
            } else {
                LOG.warn("No existing buffer?");
            }
        }
        return bytesRead;
    }

@Override
    public boolean flush()
    {
        //  If there are no un-flushed items, do nothing.
        if (w == f) {
            return true;
        }

        //  Try to set 'c' to 'f'.
        if (!c.compareAndSet(w, f)) {
            //  Compare-and-swap was unsuccessful because 'c' is NULL.
            //  This means that the reader is asleep. Therefore we don't
            //  care about thread-safeness and update c in non-atomic
            //  manner. We'll return false to let the caller know
            //  that reader is sleeping.
            c.set(f);
            w = f;
            return false;
        }

        //  Reader is alive. Nothing special to do now. Just move
        //  the 'first un-flushed item' pointer to 'f'.
        w = f;
        return true;
    }

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


Question: convenience wrapper for clone. maybe add more later.

function clone(args, baseDir, privKey, cb) {
  run(baseDir, privKey, "git clone " + args, cb)
}

func (in *ReplicationControllerConfiguration) DeepCopy() *ReplicationControllerConfiguration {
	if in == nil {
		return nil
	}
	out := new(ReplicationControllerConfiguration)
	in.DeepCopyInto(out)
	return out
}

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


Question:
// Annotate creates an error wrapping another one together with a
// a code.

func Annotate(err error, code int, msgs Messages, args ...interface{}) error {
	return newErrorBox(err, code, msgs, args...)
}

protected function buildBlock($title, $informations)
    {
        $message = '<comment>'.$title.'</comment>';
        foreach ($informations as $name => $info) {
            $message .= PHP_EOL.sprintf('  <info>%-15s</info> %s', $name, $info);
        }

        return $message;
    }

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


Question: xcom-number ::= 1*DIGIT ["." 1*DIGIT]

Rule XcomNumber() {
		return Sequence(OneOrMore(DIGIT()),
						Optional(Sequence('.', OneOrMore(DIGIT())))
		).label(XcomNumber).suppressSubnodes();
	}

def cidr_check(cidr, return_cidr=True):

    try:
        if int(cidr) < 0 or int(cidr) > 32:
            good_cidr = False
        else:
            good_cidr = True
        if return_cidr:
            while not good_cidr:
                print("Sorry the CIDR value %s is not a valid value must be a value of 0 to 32.  Please try again."
                      % (cidr,))
                cidr = input("What is the mask for in CIDR format?: ")
                if int(cidr) < 0 or int(cidr) > 32:
                    good_cidr = False
                else:
                    good_cidr = True
            return cidr
        elif not return_cidr:
            return good_cidr
    except ValueError:
        LOGGER.critical('Function cidr_check expected a number but got {item}'.format(item=cidr))
        raise ValueError("The input needs to be a number!!")

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