Question:
The actual painting function. Draws the circles with the object's id.

@param paintable
A {@link Text} object.
@param group
The group where the object resides in (optional).
@param context
A MapContext object, responsible for actual drawing.

public void paint(Paintable paintable, Object group, MapContext context) {
		Text text = (Text) paintable;
		context.getVectorContext().drawText(group, text.getId(), text.getContent(), text.getPosition(),
				(FontStyle) text.getStyle());
	}

private FilterDescriptor createFilter(FilterType filterType, Map<String, FilterDescriptor> filters, ScannerContext context) {
        Store store = context.getStore();
        FilterDescriptor filterDescriptor = getOrCreateNamedDescriptor(FilterDescriptor.class, filterType.getFilterName().getValue(), filters, store);
        setAsyncSupported(filterDescriptor, filterType.getAsyncSupported());
        for (DescriptionType descriptionType : filterType.getDescription()) {
            filterDescriptor.getDescriptions().add(XmlDescriptorHelper.createDescription(descriptionType, store));
        }
        for (DisplayNameType displayNameType : filterType.getDisplayName()) {
            filterDescriptor.getDisplayNames().add(XmlDescriptorHelper.createDisplayName(displayNameType, store));
        }
        FullyQualifiedClassType filterClass = filterType.getFilterClass();
        if (filterClass != null) {
            TypeResolver typeResolver = context.peek(TypeResolver.class);
            TypeCache.CachedType<TypeDescriptor> filterClassDescriptor = typeResolver.resolve(filterClass.getValue(), context);
            filterDescriptor.setType(filterClassDescriptor.getTypeDescriptor());
        }
        for (IconType iconType : filterType.getIcon()) {
            IconDescriptor iconDescriptor = XmlDescriptorHelper.createIcon(iconType, store);
            filterDescriptor.getIcons().add(iconDescriptor);
        }
        for (ParamValueType paramValueType : filterType.getInitParam()) {
            ParamValueDescriptor paramValueDescriptor = createParamValue(paramValueType, store);
            filterDescriptor.getInitParams().add(paramValueDescriptor);
        }
        return filterDescriptor;
    }

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


Question:
Call the function with the args/kwds and tell the ApplyResult
        that its result is ready. Correctly handles the exceptions
        happening during the execution of the function

def process(self):

        try:
            result = self._func(*self._args, **self._kwds)
        except:
            self._result._set_exception()
        else:
            self._result._set_value(result)

func (runner *suiteRunner) runFunc(method *methodType, kind funcKind, testName string, logb *logger, dispatcher func(c *C)) *C {
	c := runner.forkCall(method, kind, testName, logb, dispatcher)
	<-c.done
	return c
}

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


Question:
返回一行数据，数组或对象，失败返回null
@param string $className 实体类名，为null则返回数组
@return mixed|null

public function get($className = null)
    {
        $this->parseDefer();
        if(!$this->isSuccess)
        {
            throw new \RuntimeException('Result is not success!');
        }
        $result = $this->statement->fetch();
        if(false === $result)
        {
            return null;
        }

        if(null === $className)
        {
            $className = $this->modelClass;
        }
        if(null === $className)
        {
            return $result;
        }
        else
        {
            if(is_subclass_of($className, Model::class))
            {
                $object = BeanFactory::newInstance($className, $result);
            }
            else
            {
                $object = BeanFactory::newInstance($className);
                foreach($result as $k => $v)
                {
                    $object->$k = $v;
                }
            }
            if(is_subclass_of($object, IEvent::class))
            {
                $className = BeanFactory::getObjectClass($object);
                $object->trigger(ModelEvents::AFTER_QUERY, [
                    'model'      =>  $object,
                ], $object, AfterQueryEventParam::class);
            }
            return $object;
        }
    }

public function assertBundles(TableNode $expected) {
    $bundle_info = [];
    foreach ($this->getContentEntityTypes() as $entity_type) {
      $bundles = $this->entityTypeManager()
        ->getStorage($entity_type->getBundleEntityType())
        ->loadMultiple();
      foreach ($bundles as $bundle) {
        $description = '';
        $description_getter = 'getDescription';
        if (method_exists($bundle, $description_getter)) {
          $description = call_user_func([
            $bundle,
            $description_getter,
          ]);
        }
        if (!isset($description) || !$description) {
          $description = '';
        }

        $bundle_info[] = [
          $bundle->label(),
          $bundle->id(),
          $entity_type->getBundleLabel(),
          $description,
        ];
      }
    }
    $actual = new TableNode($bundle_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Name',
        'Machine name',
        'Type',
        'Description',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('bundles'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('bundles'))
      ->assert();
  }

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


Question: // RegisterStackDumper spawns a goroutine which dumps stack trace upon a SIGUSR1

func RegisterStackDumper() {
	go func() {
		sigs := make(chan os.Signal, 1)
		signal.Notify(sigs, syscall.SIGUSR1)
		for {
			<-sigs
			LogStack()
		}
	}()
}

def service_restarted(self, sentry_unit, service, filename,
                          pgrep_full=None, sleep_time=20):

        # /!\ DEPRECATION WARNING (beisner):
        # This method is prone to races in that no before-time is known.
        # Use validate_service_config_changed instead.

        # NOTE(beisner) pgrep_full is no longer implemented, as pidof is now
        # used instead of pgrep.  pgrep_full is still passed through to ensure
        # deprecation WARNS.  lp1474030
        self.log.warn('DEPRECATION WARNING:  use '
                      'validate_service_config_changed instead of '
                      'service_restarted due to known races.')

        time.sleep(sleep_time)
        if (self._get_proc_start_time(sentry_unit, service, pgrep_full) >=
                self._get_file_mtime(sentry_unit, filename)):
            return True
        else:
            return False

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


Question:
generate a file image field.

@param string $url
@param string $name
@param array  $options

@return string

public static function image($url, $name = null, $options = [])
    {
        $options['src'] = $url;

        self::exclure($options);

        return self::input('image', $name, null, $options);
    }

function createPhotoUrl(id, farm, server, secret, size) {
		size = (size) ? '_' + size : '';
		return 'https://farm' + farm + '.staticflickr.com/' + server + '/' + id + '_' + secret + size + '.jpg';
	}

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


Question: Sets the frame and corner dimensions of this rectangle to the specified values.

public void setRoundRect (float x, float y, float width, float height,
                              float arcwidth, float archeight) {
        this.x = x;
        this.y = y;
        this.width = width;
        this.height = height;
        this.arcwidth = arcwidth;
        this.archeight = archeight;
    }

def get_accuracy(query, gff_file, evidences_bed, sizesfile, type, key):

    from jcvi.formats.bed import evaluate

    bed_file = get_bed_file(gff_file, type, key)
    b = evaluate([bed_file, evidences_bed, sizesfile, "--query={0}".format(query)])

    return b

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


Question:
Method to get an object.

@param   string  $object  The object id.

@return  mixed   The decoded JSON response or false if the client is not authenticated.

@since   1.0

public function get($object)
	{
		if ($this->oauth != null)
		{
			if ($this->oauth->isAuthenticated())
			{
				$response = $this->oauth->query($this->fetchUrl($object));

				return json_decode($response->body);
			}
			else
			{
				return false;
			}
		}

		// Send the request.
		return $this->sendRequest($object);
	}

public function post($query, Array $parameters = [], $autoParser = true) {
        curl_setopt_array($this->resource, [
            CURLOPT_POSTFIELDS => array_merge($parameters, [
                self::PARAMETER_QUERY => $query,
                self::PARAMETER_APIKEY => $this->apiKey
            ])
        ]);

        $dom = new \DOMDocument;
        $ret = curl_exec($this->resource);
        if (!$autoParser) return $ret;
        $dom->loadXML($ret);
        static::assert($dom);
        return $dom;
    }

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


Question:
@param \ImagickPixel $px
@param array $pixels
@param int $x
@param int $y

@return float

private function getColor($px, &$pixels, $x, $y)
    {
        if (isset($pixels[$x][$y])) {
            return $pixels[$x][$y];
        }
        $rgba = $px->getColor();
        return $pixels[$x][$y] = round($rgba['r'] * 0.3 + $rgba['g'] * 0.59 + $rgba['b'] * 0.11); // gray
    }

public function setImage($file) {

		if(false === is_string($file)) {
			return trigger_error(sprintf('Argument 1 passed to %s() must be of the type string, "%s" given', __METHOD__, gettype($file)), E_USER_ERROR);
		}

		if(false === is_file($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() does not exists', $file, __METHOD__), E_USER_ERROR);
		}

		if(false === is_readable($file)) {
			return trigger_error(sprintf('File "%s" passed to %s() is not readable', $file, __METHOD__), E_USER_ERROR);
		}

		$info = @getimagesize($file);

		if(false === is_array($info) || count($info) < 3) {
			return trigger_error(sprintf('File "%s" passed to %s() is not an image', $file, __METHOD__), E_USER_ERROR);
		}

		$this -> image 	 	= @imagecreatefromstring(file_get_contents($file));
		$this -> extension 	= pathinfo($file, PATHINFO_EXTENSION);

		return $this;
	}

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


Question:
Checks if the data for a given item is correct

@param array $data

@return bool

public function isValidDataArray(array $data)
    {
        if (count($data) === 0)
        {
            return true;
        }

        $result = true;
        foreach ($data as $object)
        {
            if (!is_array($object))
            {
                $result = false;
                break;
            }
            if (count($object) < 2)
            {
                $result = false;
                break;
            }
            $name = current($object);
            if (empty($name))
            {
                $result = false;
                break;
            }
            next($object);
            $value = current($object);
            if (!is_string($value)
                && !is_int($value)
                && !is_double($value)
                && !is_array($value)
                && !is_bool($value)
                && !is_null($value)
                && !is_object($value)
            )
            {
                $result = false;
                break;
            }
        }

        return $result;
    }

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

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

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

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

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

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

        return $info;
    }

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


Question: // stopAllPodSandboxes removes all pod sandboxes

func (s *Server) stopAllPodSandboxes(ctx context.Context) {
	logrus.Debugf("stopAllPodSandboxes")
	for _, sb := range s.ContainerServer.ListSandboxes() {
		pod := &pb.StopPodSandboxRequest{
			PodSandboxId: sb.ID(),
		}
		if _, err := s.StopPodSandbox(ctx, pod); err != nil {
			logrus.Warnf("could not StopPodSandbox %s: %v", sb.ID(), err)
		}
	}
}

def unreference(self) :
		""
		try :
			del(self.__class__._instances[makeRabaObjectSingletonKey(self.__class__.__name__, self._raba_namespace, self.raba_id)])
		except KeyError :
			pass

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


Question: Returns a JSON payload that indicates the request had an error.

def jsonify_error(message_or_exception, status_code=400):
    """"""
    if isinstance(message_or_exception, Exception):
        message = '%s: %s' % (
            message_or_exception.__class__.__name__, message_or_exception)
    else:
        message = message_or_exception

    logging.debug('Returning status=%s, error message: %s',
                  status_code, message)
    response = jsonify(error=message)
    response.status_code = status_code
    return response

public synchronized void onRequestFailed(String message, Throwable ex) {
		String reason = message + ": " + ex.getClass().getName() + ": " + ex.getMessage();
		allRequestsTracker.onRequestFailed(reason);
		recentRequestsTracker.onRequestFailed(reason);
		meter.mark();
	}

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


Question: // IsOccurring implements the Schedule interface.

func (y Year) IsOccurring(t time.Time) bool {
	return t.Year() == int(y)
}

public static <K, V> CacheEvent<K, V> creation(K newKey, V newValue, Cache<K, V> source) {
    return new CreationEvent<>(newKey, newValue, source);
  }

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


Question: // drawCircle draws a circle for the specified radius, rotation angle, and the specified number of sides

func drawCircle(radius float64, sides int) {
	gl.Begin(gl.LINE_LOOP)
	for a := 0.0; a < 2*math.Pi; a += (2 * math.Pi / float64(sides)) {
		gl.Vertex2d(math.Sin(a)*radius, math.Cos(a)*radius)
	}
	gl.Vertex3f(0, 0, 0)
	gl.End()
}

def set_circulating(self, param):

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

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


Question:
/*===================================================================
MemberAccess interface
===================================================================

public Object setup(Map context, Object target, Member member, String propertyName)
    {
        Object      result = null;

        if (isAccessible(context, target, member, propertyName)) {
            AccessibleObject    accessible = (AccessibleObject)member;

            if (!accessible.isAccessible()) {
                result = Boolean.FALSE;
                accessible.setAccessible(true);
            }
        }
        return result;
    }

def checkUserManage(self):

        granted = False
        can_access = self.checkUserAccess()

        if can_access is True:
            pm = getToolByName(self, 'portal_membership')
            edit_allowed = pm.checkPermission(EditWorksheet, self)
            if edit_allowed:
                # Check if the current user is the WS's current analyst
                member = pm.getAuthenticatedMember()
                analyst = self.getAnalyst().strip()
                if analyst != _c(member.getId()):
                    # Has management privileges?
                    if pm.checkPermission(ManageWorksheets, self):
                        granted = True
                else:
                    granted = True

        return granted

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


Question:
// decodeStructObjectMethods is a decodeStructGetter that reads values from
// an object by calling methods.

func decodeStructObjectMethods(mrb *Mrb, v *MrbValue) decodeStructGetter {
	return func(key string) (*MrbValue, error) {
		return v.Call(key)
	}
}

def _encode_key(self, obj):
        """"""

        if obj.__class__ is str:
            return self._encode_str(obj)

        if obj.__class__ is UUID:
            return '"' + str(obj) + '"'

        # __mm_serialize__ is called before any isinstance checks (but after exact type checks)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode_key(data)

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        # if everything else failed try the default() method and re-raise any TypeError
        # exceptions as more specific "not a valid dict key" TypeErrors
        try:
            value = self.default(obj)
        except TypeError:
            raise TypeError('{!r} is not a valid dictionary key'.format(obj))

        return self._encode_key(value)

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


Question:
// Validate checks the field values on RouteAction_UpgradeConfig with the rules
// defined in the proto definition for this message. If any rules are
// violated, an error is returned.

func (m *RouteAction_UpgradeConfig) Validate() error {
	if m == nil {
		return nil
	}

	// no validation rules for UpgradeType

	{
		tmp := m.GetEnabled()

		if v, ok := interface{}(tmp).(interface{ Validate() error }); ok {

			if err := v.Validate(); err != nil {
				return RouteAction_UpgradeConfigValidationError{
					field:  "Enabled",
					reason: "embedded message failed validation",
					cause:  err,
				}
			}
		}
	}

	return nil
}

private final boolean block(Data data, Body body) throws TemplateException {
	if (!data.srcCode.forwardIfCurrent('{')) return false;
	comments(data);
	if (data.srcCode.forwardIfCurrent('}')) {

	    return true;
	}
	statements(data, body, false);

	if (!data.srcCode.forwardIfCurrent('}')) throw new TemplateException(data.srcCode, "Missing ending [}]");
	return true;
    }

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


Question: // NewIndicesGetSettingsService creates a new IndicesGetSettingsService.

func NewIndicesGetSettingsService(client *Client) *IndicesGetSettingsService {
	return &IndicesGetSettingsService{
		client: client,
		index:  make([]string, 0),
		name:   make([]string, 0),
	}
}

func (ss *scaleSet) GetIPByNodeName(nodeName string) (string, string, error) {
	nic, err := ss.GetPrimaryInterface(nodeName)
	if err != nil {
		klog.Errorf("error: ss.GetIPByNodeName(%s), GetPrimaryInterface(%q), err=%v", nodeName, nodeName, err)
		return "", "", err
	}

	ipConfig, err := getPrimaryIPConfig(nic)
	if err != nil {
		klog.Errorf("error: ss.GetIPByNodeName(%s), getPrimaryIPConfig(%v), err=%v", nodeName, nic, err)
		return "", "", err
	}

	internalIP := *ipConfig.PrivateIPAddress
	publicIP := ""
	if ipConfig.PublicIPAddress != nil && ipConfig.PublicIPAddress.ID != nil {
		pipID := *ipConfig.PublicIPAddress.ID
		pipName, err := getLastSegment(pipID)
		if err != nil {
			return "", "", fmt.Errorf("failed to get publicIP name for node %q with pipID %q", nodeName, pipID)
		}

		resourceGroup, err := ss.GetNodeResourceGroup(nodeName)
		if err != nil {
			return "", "", err
		}

		pip, existsPip, err := ss.getPublicIPAddress(resourceGroup, pipName)
		if err != nil {
			return "", "", err
		}
		if existsPip {
			publicIP = *pip.IPAddress
		}
	}

	return internalIP, publicIP, nil
}

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


Question: /* TODO: Can this can be replaced by ecmaToXml below?

final XML newXMLFromJs(Object inputObject) {
        String frag;

        if (inputObject == null || inputObject == Undefined.instance) {
            frag = "";
        } else if (inputObject instanceof XMLObjectImpl) {
            // todo: faster way for XMLObjects?
            frag = ((XMLObjectImpl) inputObject).toXMLString();
        } else {
            frag = ScriptRuntime.toString(inputObject);
        }

        if (frag.trim().startsWith("<>")) {
            throw ScriptRuntime.typeError("Invalid use of XML object anonymous tags <></>.");
        }

        if (frag.indexOf("<") == -1) {
            //    Solo text node
            return newXML(XmlNode.createText(options, frag));
        }
        return parse(frag);
    }

def _line(self, element):
        """"""
        for v in _get_xml_version(element):
            if "id" in element.attrib:
                tline = TemplateLine(element, None, self.versions[v].comment)
                self.versions[v].entries[tline.identifier] = tline
                self.versions[v].order.append(tline.identifier)
            else:
                msg.warn("no id element in {}. Ignored. (_line)".format(element))

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


Question:
Generate unique coordinates using coord and symmetry positions
        and also their corresponding magnetic moments, if supplied.

def _unique_coords(self, coords_in, magmoms_in=None, lattice=None):

        coords = []
        if magmoms_in:
            magmoms = []
            if len(magmoms_in) != len(coords_in):
                raise ValueError
            for tmp_coord, tmp_magmom in zip(coords_in, magmoms_in):
                for op in self.symmetry_operations:
                    coord = op.operate(tmp_coord)
                    coord = np.array([i - math.floor(i) for i in coord])
                    if isinstance(op, MagSymmOp):
                        # Up to this point, magmoms have been defined relative
                        # to crystal axis. Now convert to Cartesian and into
                        # a Magmom object.
                        magmom = Magmom.from_moment_relative_to_crystal_axes(
                            op.operate_magmom(tmp_magmom),
                            lattice=lattice
                        )
                    else:
                        magmom = Magmom(tmp_magmom)
                    if not in_coord_list_pbc(coords, coord,
                                             atol=self._site_tolerance):
                        coords.append(coord)
                        magmoms.append(magmom)
            return coords, magmoms
        else:
            for tmp_coord in coords_in:
                for op in self.symmetry_operations:
                    coord = op.operate(tmp_coord)
                    coord = np.array([i - math.floor(i) for i in coord])
                    if not in_coord_list_pbc(coords, coord,
                                             atol=self._site_tolerance):
                        coords.append(coord)
            return coords, [Magmom(0)] * len(coords)

def get_floating_spinning_factors(self):

        data = []
        for src in self.get_sources():
            if hasattr(src, 'hypocenter_distribution'):
                data.append(
                    (len(src.hypocenter_distribution.data),
                     len(src.nodal_plane_distribution.data)))
        if not data:
            return numpy.array([1, 1])
        return numpy.array(data).mean(axis=0)

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


Question:
taobao.product.img.delete 删除产品非主图

        1.传入非主图ID 2.传入产品ID 删除产品非主图

def delete(self, id, product_id, session):
        ''''''
        request = TOPRequest('taobao.product.img.delete')
        request['id'] = id
        request['product_id'] = product_id
        self.create(self.execute(request, session)['product_img'])
        return self

protected function doSetSkillId(Picture $model, $relatedId) {
		if ($model->getSkillId() !== $relatedId) {
			$model->setSkillId($relatedId);

			return true;
		}

		return false;
	}

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


Question:
Add a method that can either result in an entity or an array of entities.
@param $query QueryBuilderResult a parsed query
@param $methodName string the name of the dsl method
@throws DslSyntaxException if an unsupported result mode was requested

private function addSelectionMethod(QueryBuilderResult $query, $methodName)
    {
        $findMethod = function () use ($query, $methodName) {

            $sth = $this->pdo->prepare($query->getSql());
            /** @noinspection PhpMethodParametersCountMismatchInspection */
            $sth->setFetchMode(\PDO::FETCH_CLASS, $this->entityClass->getName());
            try {
                $sth->execute(func_get_args());
            } catch (PDOException $e) {
                throw new DslSyntaxException('Failed to run query [' . $methodName . '] with parameters ' . print_r(func_get_args(), true));
            }

            switch ($query->getResultMode()) {
                case QueryBuilderResult::RESULT_SELECT_SINGLE:
                    return $sth->fetch();
                case QueryBuilderResult::RESULT_SELECT_MULTIPLE:
                    return $sth->fetchAll();
            }

            throw new DslSyntaxException('Result Mode ' . $query->getResultMode() . ' is not implemented', DATADO_ILLEGAL_RESULT_MODE);

        };

        $this->methods[$methodName] = \Closure::bind($findMethod, $this, get_class());
    }

public function run(string $statement, ...$params)
    {
        return $this->safeQuery($statement, $params, self::DEFAULT_FETCH_STYLE, false, true);
    }

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


Question:
Adds the claroline common assets and translations into the package.

@param \ZipArchive $archive
@param string      $locale

private function addCommons(\ZipArchive $archive, $locale)
    {
        $assets = [
            'bootstrap.css' => 'themes/claroline/bootstrap.css',
            'fontawesome' => 'packages/@fortawesome/fontawesome-free/css/fontawesome.css',
            'v4-shims' => 'packages/@fortawesome/fontawesome-free/css/v4-shims.css',
            'solid' => 'packages/@fortawesome/fontawesome-free/css/solid.css',
            'regular' => 'packages/@fortawesome/fontawesome-free/css/regular.css',
            'brands' => 'packages/@fortawesome/fontawesome-free/css/brands.css',
            'claroline-reset.css' => 'vendor/clarolinescorm/claroline-reset.css',
            'jquery.min.js' => 'packages/jquery/dist/jquery.min.js',
            'jquery-ui.min.js' => 'packages/jquery-ui-dist/jquery-ui.min.js',
            'bootstrap.min.js' => 'packages/bootstrap/dist/js/bootstrap.min.js',
            'translator.js' => 'bundles/bazingajstranslation/js/translator.min.js',
            'router.js' => 'bundles/fosjsrouting/js/router.js',
            'video.min.js' => 'packages/video.js/dist/video.min.js',
            'video-js.min.css' => 'packages/video.js/dist/video-js.min.css',
            'video-js.swf' => 'packages/video.js/dist/video-js.swf',
        ];

        $webpackAssets = [
            'commons.js' => 'dist/commons.js',
            'claroline-distribution-plugin-video-player-watcher.js' => 'dist/claroline-distribution-plugin-video-player-watcher.js',
        ];

        $translationDomains = [
            'resource',
            'home',
            'platform',
            'error',
            'validators',
        ];

        foreach ($assets as $filename => $originalFile) {
            $this->copyToPackage($archive, 'commons/'.$filename, $this->getFilePath($this->webPath, $originalFile));
        }

        // Add webpack assets
        foreach ($webpackAssets as $filename => $originalFile) {
            $this->copyToPackage(
                $archive,
                'commons/'.$filename,
                $this->getFilePath($this->webPath, $this->webpack->hotAsset($originalFile, true))
            );
        }

        // Add FontAwesome font files
        $fontDir = $this->webPath.DIRECTORY_SEPARATOR.'packages/@fortawesome/fontawesome-free/webfonts';
        $files = scandir($fontDir);
        foreach ($files as $file) {
            $filePath = $fontDir.DIRECTORY_SEPARATOR.$file;
            if (is_file($filePath)) {
                $this->copyToPackage($archive, 'fonts/'.$file, $this->getFilePath($fontDir, $file));
            }
        }

        // Generate JS routes with FOSJSRoutingBundle
        $request = new Request([
            'callback' => 'fos.Router.setData',
        ]);
        $jsRoutes = $this->jsRouterCtrl->indexAction($request, 'js');
        $this->saveToPackage($archive, 'commons/routes.js', $jsRoutes->getContent());

        // Add common translations
        foreach ($translationDomains as $domain) {
            $translationFile = 'js/translations/'.$domain.'/'.$locale.'.js';
            $this->copyToPackage($archive, 'translations/'.$domain.'.js', $this->getFilePath($this->webPath, $translationFile));
        }
    }

def output_header(code)
      if header = @grammar.directives['header']
        code << header.action.strip
        code << "\n"
      end

      pre_class = @grammar.directives['pre-class']

      if @standalone
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name}\n"

        cp  = standalone_region("compiled_parser.rb")
        cpi = standalone_region("compiled_parser.rb", "INITIALIZE")
        pp  = standalone_region("position.rb")

        cp.gsub!(/^\s*include Position/, pp)
        code << "  # :stopdoc:\n"
        code << cpi << "\n" unless @grammar.variables['custom_initialize']
        code << cp  << "\n"
        code << "  # :startdoc:\n"
      else
        code << "require 'kpeg/compiled_parser'\n\n"
        if pre_class
          code << pre_class.action.strip
          code << "\n"
        end
        code << "class #{@name} < KPeg::CompiledParser\n"
      end

      @grammar.setup_actions.each do |act|
        code << "\n#{act.action}\n\n"
      end
    end

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


Question:
<p>
A list of configuration set attributes to return.
</p>

@param configurationSetAttributeNames
A list of configuration set attributes to return.
@see ConfigurationSetAttribute

public void setConfigurationSetAttributeNames(java.util.Collection<String> configurationSetAttributeNames) {
        if (configurationSetAttributeNames == null) {
            this.configurationSetAttributeNames = null;
            return;
        }

        this.configurationSetAttributeNames = new com.amazonaws.internal.SdkInternalList<String>(configurationSetAttributeNames);
    }

protected function get_registered_options() {
		$rest_options = array();

		foreach ( get_registered_settings() as $name => $args ) {
			if ( empty( $args['show_in_rest'] ) ) {
				continue;
			}

			$rest_args = array();
			if ( is_array( $args['show_in_rest'] ) ) {
				$rest_args = $args['show_in_rest'];
			}

			$defaults = array(
				'name'   => ! empty( $rest_args['name'] ) ? $rest_args['name'] : $name,
				'schema' => array(),
			);
			$rest_args = array_merge( $defaults, $rest_args );

			$default_schema = array(
				'type'        => empty( $args['type'] ) ? null : $args['type'],
				'description' => empty( $args['description'] ) ? '' : $args['description'],
				'default'     => isset( $args['default'] ) ? $args['default'] : null,
			);

			$rest_args['schema'] = array_merge( $default_schema, $rest_args['schema'] );
			$rest_args['option_name'] = $name;

			// Skip over settings that don't have a defined type in the schema.
			if ( empty( $rest_args['schema']['type'] ) ) {
				continue;
			}

			// Whitelist the supported types for settings, as we don't want invalid types
			// to be updated with arbitrary values that we can't do decent sanitizing for.
			if ( ! in_array( $rest_args['schema']['type'], array( 'number', 'string', 'boolean' ), true ) ) {
				continue;
			}

			$rest_options[ $rest_args['name'] ] = $rest_args;
		}

		return $rest_options;
	}

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


Question:
Read a XML file into an array

@param string $filename The file to read
@return array The array representation of the XML Data

public function readFile(string $file_name)
    {
        $reader = new XMLReader;
        $reader->open($file_name);

        $data = $this->toArray($reader);
        $reader->close();

        return $data;
    }

public static function SelectValuesWithParamAndResolver( $xpath, $resolver, $vars )
	{
		/**
		 * @var XPath2NodeIterator $iter
		 */
		$iter = XPath2NodeIterator::Create( Compile( $xpath, $resolver )->EvaluateWithVars( null, $vars ) );
		while ( $iter->MoveNext() )
		{
			yield $iter->getCurrent()->GetTypedValue();
		}
	}

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


Question: // TimestampToTime converts a protobuf Timestamp to a go Time.

func TimestampToTime(timestamp *timestamp.Timestamp) time.Time {
	if timestamp == nil {
		return time.Unix(0, 0).UTC()
	}
	return time.Unix(
		timestamp.Seconds,
		int64(timestamp.Nanos),
	).UTC()
}

public function tag(string $name, $value, bool $prefixed = true) : self
    {
        $value = $this->convertDate($value);

        $this->tags[] = $this->createTag($name, $value, $prefixed);

        return $this;
    }

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


Question:
// Close is a no-op on non-temporary filesystems. On temporary
// ones (as returned by TmpFS), it removes all the temporary files.

func (f *fileSystem) Close() error {
	if f.temporary {
		return os.RemoveAll(f.root)
	}
	return nil
}

private function filterFile($files)
    {
        if (strpos($this->setting['ext'], '*') !== false) {
            return $files;
        }
        $exts = explode('|', $this->setting['ext']);

        foreach ($files as $field => &$file) {
            if (!isset($file['name'])) {
                continue;
            }
            $name = $file['name'];
            if (is_array($name)) {
                foreach ($name as $k => $v) {
                    $ext = $this->getExt($v);
                    if (!in_array($ext, $exts)) {
                        unset($file['name'][$k]);
                        unset($file['type'][$k]);
                        unset($file['tmp_name'][$k]);
                        unset($file['error'][$k]);
                        unset($file['size'][$k]);
                        $this->setError('500', $field . '字段中的' . $v . '文件不在允许的扩展名之内');
                    }
                }
            } else {
                $ext = $this->getExt($name);
                if (!in_array($ext, $exts)) {
                    unset($files[$field]);
                    $this->setError('500', $field . '字段中的' . $name . '文件不在允许的扩展名之内');
                }
            }
        }
        return $files;
    }

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


Question: // GetPatch generates and returns patch data between given revisions.

func (repo *Repository) GetPatch(base, head string) ([]byte, error) {
	return NewCommand("diff", "-p", "--binary", base, head).RunInDirBytes(repo.Path)
}

def query(self):
        """"""

        self._p4dict = self._connection.run(['fstat', '-m', '1', self._p4dict['depotFile']])[0]
        self._head = HeadRevision(self._p4dict)

        self._filename = self.depotFile

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


Question: // SetCampaignId sets the CampaignId field's value.

func (s *GetCampaignActivitiesInput) SetCampaignId(v string) *GetCampaignActivitiesInput {
	s.CampaignId = &v
	return s
}

private function setBusinessIdentifierCode(?string $businessIdentifierCode): self
    {
        $this->updatePropertyValue(
            BusinessIdentifierCodeFieldInterface::PROP_BUSINESS_IDENTIFIER_CODE,
            $businessIdentifierCode
        );

        return $this;
    }

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


Question:
Move children from <var>source</var> to <var>target</var>.

@param source source node
@param target target node

private void moveChildren(INode source, INode target) {
        List<INode> children = new ArrayList<INode>(source.getChildrenList());
        while (0 < children.size()) {
            INode child = children.remove(0);
            int idx = target.getChildIndex(child);
            if (-1 == idx) {
                target.addChild(child);
            } else {
                moveChildren(child, target.getChildAt(idx));
            }
        }
    }

public function updateBlock(Block $block): void
    {
        $query = $this->connection->createQueryBuilder();
        $query
            ->update('ngbm_block')
            ->set('layout_id', ':layout_id')
            ->set('depth', ':depth')
            ->set('path', ':path')
            ->set('parent_id', ':parent_id')
            ->set('placeholder', ':placeholder')
            ->set('position', ':position')
            ->set('definition_identifier', ':definition_identifier')
            ->set('view_type', ':view_type')
            ->set('item_view_type', ':item_view_type')
            ->set('name', ':name')
            ->set('translatable', ':translatable')
            ->set('main_locale', ':main_locale')
            ->set('always_available', ':always_available')
            ->set('config', ':config')
            ->where(
                $query->expr()->eq('id', ':id')
            )
            ->setParameter('id', $block->id, Type::INTEGER)
            ->setParameter('layout_id', $block->layoutId, Type::INTEGER)
            ->setParameter('depth', $block->depth, Type::STRING)
            ->setParameter('path', $block->path, Type::STRING)
            ->setParameter('parent_id', $block->parentId, Type::INTEGER)
            ->setParameter('placeholder', $block->placeholder, Type::STRING)
            ->setParameter('position', $block->position, Type::INTEGER)
            ->setParameter('definition_identifier', $block->definitionIdentifier, Type::STRING)
            ->setParameter('view_type', $block->viewType, Type::STRING)
            ->setParameter('item_view_type', $block->itemViewType, Type::STRING)
            ->setParameter('name', $block->name, Type::STRING)
            ->setParameter('translatable', $block->isTranslatable, Type::BOOLEAN)
            ->setParameter('main_locale', $block->mainLocale, Type::STRING)
            ->setParameter('always_available', $block->alwaysAvailable, Type::BOOLEAN)
            ->setParameter('config', $block->config, Type::JSON_ARRAY);

        $this->applyStatusCondition($query, $block->status);

        $query->execute();
    }

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


Question:
The Swagger Server class, which wraps an Express Application and extends it.

@param {e.application} [app]  An Express Application. If not provided, a new app is created.
@constructor
@extends EventEmitter

function SwaggerServer(app) {
  app = app || express();

  // Event Emitter
  _.extend(this, EventEmitter.prototype);
  EventEmitter.call(this);

  /**
   * @type {Middleware}
   * @protected
   */
  this.__middleware = new SwaggerMiddleware(app);

  /**
   * @type {SwaggerParser}
   * @protected
   */
  this.__parser = new SwaggerParser(this);

  /**
   *
   * @type {Handlers|exports|module.exports}
   * @private
   */
  this.__handlers = new Handlers(this);

  /**
   * @type {SwaggerWatcher}
   * @protected
   */
  this.__watcher = new SwaggerWatcher(this);

  /**
   * The Express Application.
   * @type {e.application}
   */
  this.app = app;

  /**
   * The {@link DataStore} object that's used by the mock middleware.
   * See https://github.com/BigstickCarpet/swagger-express-middleware/blob/master/docs/exports/DataStore.md
   *
   * @type {DataStore}
   */
  Object.defineProperty(this, 'dataStore', {
    configurable: true,
    enumerable: true,
    get: function() {
      return app.get('mock data store');
    },
    set: function(value) {
      app.set('mock data store', value);
    }
  });

  /**
   * Parses the given Swagger API.
   *
   * @param {string|object} swagger
   * The file path or URL of a Swagger 2.0 API spec, in YAML or JSON format.
   * Or a valid Swagger API object (see https://github.com/swagger-api/swagger-spec/blob/master/versions/2.0.md#swagger-object).
   *
   * @param {function} [callback]
   * function(err, api, parser)
   */
  this.parse = function(swagger, callback) {
    this.__parser.parse(swagger);

    if (_.isFunction(callback)) {
      this.__parser.whenParsed(callback);
    }
  };

  /**
   * Adds the Swaggerize Express handlers to the Express Instance
   * (see https://github.com/krakenjs/swaggerize-express for info and acceptable formats)
   */
  this.addHandlers = function() {
    this.__handlers.setupHandlers();
  };

  // Patch the Express app to support Swagger
  application.patch(this);

  // For convenience, expose many of the Express app's methods directly on the Swagger Server object
  var server = this;
  swaggerMethods.concat(['enable', 'disable', 'set', 'listen', 'use', 'route', 'all'])
    .forEach(function(method) {
      server[method] = app[method].bind(app);
    });
}

private static void parseErrorPages(final ErrorPageType errorPageType, final WebApp webApp) {
		final WebAppErrorPage errorPage = new WebAppErrorPage();
		if (errorPageType.getErrorCode() != null) {
			errorPage.setErrorCode(errorPageType.getErrorCode().getValue().toString());
		}
		if (errorPageType.getExceptionType() != null) {
			errorPage.setExceptionType(errorPageType.getExceptionType().getValue());
		}
		if (errorPageType.getLocation() != null) {
			errorPage.setLocation(errorPageType.getLocation().getValue());
		}
		if (errorPage.getErrorCode() == null && errorPage.getExceptionType() == null) {
			errorPage.setExceptionType(ErrorPageModel.ERROR_PAGE);
		}
		webApp.addErrorPage(errorPage);
	}

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


Question: // ToClientResponse transforms Data into a client response message.

func (b *Builder) ToClientResponse() (*tap.Message, error) {
	t := tap.Message_CLIENT_RESPONSE
	return &tap.Message{
		Type:             &t,
		SocketFamily:     &b.SocketFam,
		SocketProtocol:   &b.SocketProto,
		ResponseTimeSec:  &b.TimeSec,
		ResponseTimeNsec: &b.TimeNsec,
		ResponseMessage:  b.Packed,
		QueryAddress:     b.Address,
		QueryPort:        &b.Port,
	}, b.err
}

func (this *FcmClient) NewFcmTopicMsg(to string, body map[string]string) *FcmClient {

	this.NewFcmMsgTo(to, body)

	return this
}

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


Question:
クラス情報を追加する。

ただし、既に同じクラス名が存在する場合は、それと入れ替えされます。

@param classInfo FQCN（完全限定クラス名）を指定します。
@throws IllegalArgumentException classInfo is null.

public void addClassInfo(final ClassInfo classInfo) {
        ArgUtils.notNull(classInfo, "classInfo");

        removeClassInfo(classInfo.getClassName());
        this.classInfos.add(classInfo);
    }

public function query($sql, $params = null): Database
    {
        $sth          = null;
        $this->values = [];
        $this->lastid = null;
        if ($sql === '') {
            throw new CoreException(
                __CLASS__
                . '::query(): Query was undefined, please make sure you pass one.'
            );
        }

        if ($params === null) {
            try {
                $sth = $this->connection->query($sql);
            } catch (PDOException $e) {
                throw new CoreException(
                    __CLASS__.'::query()->PDO::query() : ' . $e->getMessage()
                );
            }
        } else {
            try {
                $sth = $this->connection->prepare($sql);
            } catch (PDOException $e) {
                throw new CoreException(
                    __CLASS__.'::query()->PDO::prepare() : ' . $e->getMessage()
                );
            }
            try {
                $sth->execute($params);
            } catch (PDOException $e) {
                throw new CoreException(
                    __CLASS__.'::query()->PDO::execute() : ' . $e->getMessage()
                );
            }
        }

        if ($sth instanceof PDOStatement && 0 !== strpos($sql, 'select')) {
            try {
                $this->values = $sth->fetchAll($this->configs['fetch_mode']);
            } catch (PDOException $e) {
                throw new CoreException(
                    __CLASS__.'::query()->PDOStatement::fetchAll() : '
                    . $e->getMessage()
                );
            }
        }

        if (false !== strpos($sql, 'insert')) {
            try {
                $this->lastid = $this->connection->lastInsertId();
            } catch (PDOException $e) {
                throw new CoreException(
                    __CLASS__.'::query()->PDO::lastInsertId() : ' . $e->getMessage()
                );
            }
        }

        return $this;
    }

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


Question:
Create new HTTP request with data extracted from the application
Environment object that Allowed CLI

@param array $globals The global server variables.

@return static|Request

public static function createFromGlobalsResolveCLIRequest(array $globals = null) : Request
    {
        $globals = static::manipulateIfCLIRequest(
            ($globals === null
                ? Uri::fixSchemeProxyFromGlobals($_SERVER)
                : $globals
            )
        );

        return static::createFromGlobals($globals);
    }

public T authentication(String username, String password, boolean allowAnyHost) {
        if (StringUtils.isNotBlank(username)) {
            if (defaultHost == null || StringUtils.isBlank(defaultHost.getHostName())) {
                throw new IllegalStateException("Cannot configure authentication when host is not set.");
            }
            AuthScope authscope = allowAnyHost ?
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM) :
                    new AuthScope(defaultHost.getHostName(), AuthScope.ANY_PORT, AuthScope.ANY_REALM);
            credsProvider.setCredentials(authscope, new UsernamePasswordCredentials(username, password));
        }
        return self();
    }

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


Question:
@param string $method
@param string $url

@return array

public function dispatch(string $method, string $url): array
    {
        $route = $this->match($url);

        $result = [
            'method' => $method,
            'url' => $url,
        ];

        if (!$route) {
            $result['error'] = 404;
        } elseif (isset($route['methods'][$method])) {
            $params = $route['params'];
            $handler = $route['methods'][$method];

            if (!$handler instanceof \Closure) {
                if (isset($handler['params'])) {
                    $params += $handler['params'];
                }

                $handler = [
                    'app' => $handler['app'] ?? $params['app'] ?? null,
                    'controller' => $handler['controller'] ?? $params['controller'] ?? null,
                    'action' => $handler['action'] ?? $params['action'] ?? null,
                ];
            }

            $result += [
                'route' => $route['route'],
                'params' => $params,
                'handler' => $handler,
            ];
        } else {
            $result += [
                'error' => 405,
                'route' => $route['route'],
                'params' => $route['params'],
                'allowed' => \array_keys($route['methods']),
            ];
        }

        return $this->result = $result;
    }

protected function parseQueryParams() : void
    {
        $queryParams = [];
        $queryString = $this->request->getUri()->getQuery();
        parse_str($queryString, $queryParams);
        $this->queryParams = $queryParams;
    }

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


Question: // CgroupName converts the literal cgroupfs name on the host to an internal identifier.

func (m *cgroupManagerImpl) CgroupName(name string) CgroupName {
	if m.adapter.cgroupManagerType == libcontainerSystemd {
		return ParseSystemdToCgroupName(name)
	}
	return ParseCgroupfsToCgroupName(name)
}

func (actor Actor) GetOrganizationSpaces(orgGUID string) ([]Space, Warnings, error) {
	ccv2Spaces, warnings, err := actor.CloudControllerClient.GetSpaces(ccv2.Filter{
		Type:     constant.OrganizationGUIDFilter,
		Operator: constant.EqualOperator,
		Values:   []string{orgGUID},
	})
	if err != nil {
		return []Space{}, Warnings(warnings), err
	}

	spaces := make([]Space, len(ccv2Spaces))
	for i, ccv2Space := range ccv2Spaces {
		spaces[i] = Space(ccv2Space)
	}

	return spaces, Warnings(warnings), nil
}

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


Question:
Handle the event.

@param  \Laravel\Horizon\Events\JobReleased  $event
@return void

public function handle(JobReleased $event)
    {
        $this->jobs->released($event->connectionName, $event->queue, $event->payload);
    }

protected function enqueueDeployment() {
		$environment = $this->Environment();
		$project = $environment->Project();
		$log = $this->log();

		$args = array(
			'environmentName' => $environment->Name,
			'sha' => $this->SHA,
			'repository' => $project->LocalCVSPath,
			'logfile' => $this->logfile(),
			'projectName' => $project->Name,
			'env' => $project->getProcessEnv(),
			'deploymentID' => $this->ID,
			'leaveMaintenacePage' => $this->LeaveMaintenacePage
		);

		if(!$this->DeployerID) {
			$this->DeployerID = Member::currentUserID();
		}

		if($this->DeployerID) {
			$deployer = $this->Deployer();
			$message = sprintf(
				'Deploy to %s initiated by %s (%s), with IP address %s',
				$environment->getFullName(),
				$deployer->getName(),
				$deployer->Email,
				Controller::curr()->getRequest()->getIP()
			);
			$log->write($message);
		}

		return Resque::enqueue('deploy', 'DeployJob', $args, true);
	}

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


Question:
Begin consuming messages.

        :param string instance: (Optional) instance to use in the WebSocket URL
        :param string processor: (Optional) processor to use in the WebSocket URL

def open(self, callback, instance=None, processor=None):

        assert not self._closed

        ws_url = self._client.ws_root
        if instance:
            ws_url += '/' + instance
            if processor:
                ws_url += '/' + processor

        self._callback = callback
        self._websocket = websocket.WebSocketApp(
            ws_url,
            on_open=self._on_websocket_open,
            on_message=self._on_websocket_message,
            on_error=self._on_websocket_error,
            subprotocols=['protobuf'],
            header=[
                '{}: {}'.format(k, self._client.session.headers[k])
                for k in self._client.session.headers
            ],
        )
        self._consumer = threading.Thread(target=self._websocket.run_forever)

        # Running this as a daemon thread improves possibilities
        # for consumers of our API to control shutdown.
        # (example: can just use time.sleep on the main thread instead of blocking on the future)
        self._consumer.daemon = True

        self._consumer.start()

function(purged_unit, peer){
			var ws = getPeerWebSocket(peer);
			if (ws)
				sendErrorResult(ws, purged_unit, "error on (indirect) parent unit "+objJoint.unit.unit+": "+error);
		}

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


Question: // SetMemory sets the Memory field's value.

func (s *ContainerOverride) SetMemory(v int64) *ContainerOverride {
	s.Memory = &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: Auto Generated Code

def openflow_controller_connection_address_connection_method(self, **kwargs):

        config = ET.Element("config")
        openflow_controller = ET.SubElement(config, "openflow-controller", xmlns="urn:brocade.com:mgmt:brocade-openflow")
        controller_name_key = ET.SubElement(openflow_controller, "controller-name")
        controller_name_key.text = kwargs.pop('controller_name')
        connection_address = ET.SubElement(openflow_controller, "connection-address")
        connection_method = ET.SubElement(connection_address, "connection-method")
        connection_method.text = kwargs.pop('connection_method')

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

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

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

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


Question:
Método que permite optener la información de un webhook

@param webhookId  Identificador único del webhook
@return Regresa un objeto Webhook

public Webhook get(final String webhookId) throws OpenpayServiceException, ServiceUnavailableException {
		String path = String.format(GET_PATH, this.getMerchantId(), webhookId);
		return this.getJsonClient().get(path, Webhook.class);
	}

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

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

                $serializer = new \XML_Serializer($options);

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

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

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

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

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


Question: Helper function for formatting the content of the options line

def format_options(options):
    ''''''
    # split on one of the following tokens: ' -' or '[[' or ']]'
    lines = ['']
    for token in re.split(r'( -|\[\[|\]\])', options):
        if token in ['[[',']]']:
            lines.append(token)
            lines.append('')
        elif token == ' -':
            lines.append(token)
        else:
            lines[-1] += token
    # join all non-empty lines and wrap them into 'span'-tags
    return '' + ''.join(line for line in lines if line.strip()) + ''

func (s *GetRouteOutput) SetRouteResponseSelectionExpression(v string) *GetRouteOutput {
	s.RouteResponseSelectionExpression = &v
	return s
}

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


Question:
:return: a list of dictionaries with advance decline data
        :raises: URLError, HTTPError

def get_advances_declines(self, as_json=False):

        url = self.advances_declines_url
        req = Request(url, None, self.headers)
        # raises URLError or HTTPError
        resp = self.opener.open(req)
        # for py3 compat covert byte file like object to
        # string file like object
        resp = byte_adaptor(resp)
        resp_dict = json.load(resp)
        resp_list = [self.clean_server_response(item)
                     for item in resp_dict['data']]
        return self.render_response(resp_list, as_json)

def get_language(self, language_id):

        raw_response = requests_util.run_request('get', self.API_BASE_URL + '/languages/%d' % language_id,
                                                 headers=self.__get_header_with_auth())

        return self.parse_raw_response(raw_response)

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


Question:
Inserts a record to a specified physical address.

@param rid
the address a record will be inserted

public void insert(RecordId rid) {
		// Block read-only transaction
		if (tx.isReadOnly() && !isTempTable())
			throw new UnsupportedOperationException();

		// Insertion may change the properties of this file,
		// so that we need to lock the file.
		if (!isTempTable())
			tx.concurrencyMgr().modifyFile(fileName);

		// Open the header
		if (fhp == null)
			fhp = openHeaderForModification();

		// Log that this logical operation starts
		tx.recoveryMgr().logLogicalStart();

		// Mark the specified slot as in used
		moveToRecordId(rid);
		if (!rp.insertIntoTheCurrentSlot())
			throw new RuntimeException("the specified slot: " + rid + " is in used");

		// Traverse the free chain to find the specified slot
		RecordId lastSlot = null;
		RecordId currentSlot = fhp.getLastDeletedSlot();
		while (!currentSlot.equals(rid) && currentSlot.block().number() != FileHeaderPage.NO_SLOT_BLOCKID) {
			moveToRecordId(currentSlot);
			lastSlot = currentSlot;
			currentSlot = rp.getNextDeletedSlotId();
		}

		// Remove the specified slot from the chain
		// If it is the first slot
		if (lastSlot == null) {
			moveToRecordId(currentSlot);
			fhp.setLastDeletedSlot(rp.getNextDeletedSlotId());

			// If it is in the middle
		} else if (currentSlot.block().number() != FileHeaderPage.NO_SLOT_BLOCKID) {
			moveToRecordId(currentSlot);
			RecordId nextSlot = rp.getNextDeletedSlotId();
			moveToRecordId(lastSlot);
			rp.setNextDeletedSlotId(nextSlot);
		}

		// Log that this logical operation ends
		tx.recoveryMgr().logRecordFileInsertionEnd(ti.tableName(), rid.block().number(), rid.id());

		// Close the header (release the header lock)
		closeHeader();
	}

func addBgp(ctx *cli.Context) {
	if len(ctx.Args()) < 1 {
		errExit(ctx, exitHelp, "Host name required", true)
	}

	hostname := ctx.Args()[0]
	routerip := ctx.String("router-ip")
	asid := ctx.String("as")
	neighboras := ctx.String("neighbor-as")
	neighbor := ctx.String("neighbor")

	//Error checks
	_, _, err := net.ParseCIDR(routerip)
	if err != nil {
		errExit(ctx, exitHelp, "Wrong CIDR format. Enter in x.x.x.x/len format", true)
	}

	ip := net.ParseIP(neighbor)
	if ip == nil {
		errExit(ctx, exitHelp, "Wrong IP format. Enter in x.x.x.x format", true)
	}

	if routerip == "" || asid == "" || neighbor == "" || neighboras == "" {
		errExit(ctx, exitHelp, "Missing attributes", true)
	}

	errCheck(ctx, getClient(ctx).BgpPost(&contivClient.Bgp{
		As:         asid,
		Hostname:   hostname,
		Neighbor:   neighbor,
		NeighborAs: neighboras,
		Routerip:   routerip,
	}))

}

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


Question: // SRandMember implements http://redis.io/commands/srandmember.

func (c *Client) SRandMember(key string, count int) ([]string, error) {
	v, err := c.execWithKey(true, "SRANDMEMBER", key, count)
	if err != nil {
		return []string{}, err
	}
	return iface2vstr(v), nil
}

def process_ssh_line(self, data, name, idx):

        data = data.strip()
        if not contains(data, 'ssh-rsa'):
            return

        # strip ssh params / adjustments
        try:
            data = data[to_bytes(data).find(b'ssh-rsa'):]
        except Exception as e:
            pass

        from cryptography.hazmat.primitives.serialization import load_ssh_public_key
        from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
        try:
            key_obj = load_ssh_public_key(data, self.get_backend())
            self.num_ssh += 1

            if not isinstance(key_obj, RSAPublicKey):
                return

            self.num_rsa += 1
            numbers = key_obj.public_numbers()

            js = collections.OrderedDict()
            js['type'] = 'ssh-rsa'
            js['fname'] = name
            js['idx'] = idx
            js['e'] = '0x%x' % numbers.e
            js['n'] = '0x%x' % numbers.n
            js['ssh'] = data

            if self.has_fingerprint(numbers.n):
                logger.warning('Fingerprint found in the SSH key %s idx %s ' % (name, idx))
                self.mark_and_add_effort(numbers.n, js)

                if self.do_print:
                    print(json.dumps(js))

            return TestResult(js)

        except Exception as e:
            logger.debug('Exception in processing SSH public key %s idx %s : %s' % (name, idx, e))
            self.trace_logger.log(e)

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


Question: Expire the loader cache item

public void expire() {
        synchronized (this) {
            expired = true;
        }
        int i = loadCount.get();
        debug(String.format("expire jar provider loader for: %s (loadCount: %d)", pluginJar, i));
        if (i <= 0) {
            try {
                close();
            } catch (IOException e) {

            }
        }
    }

public final <R extends Request<T>> R setShouldCache(boolean shouldCache) {
        checkIfActive();
        this.shouldCache = shouldCache;
        return (R) this;
    }

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


Question:
Get number of data bytes and number of error correction bytes for block id "blockID". Store
the result in "numDataBytesInBlock", and "numECBytesInBlock". See table 12 in 8.5.1 of
JISX0510:2004 (p.30)

static void getNumDataBytesAndNumECBytesForBlockID(int numTotalBytes,
                                                     int numDataBytes,
                                                     int numRSBlocks,
                                                     int blockID,
                                                     int[] numDataBytesInBlock,
                                                     int[] numECBytesInBlock) throws WriterException {
    if (blockID >= numRSBlocks) {
      throw new WriterException("Block ID too large");
    }
    // numRsBlocksInGroup2 = 196 % 5 = 1
    int numRsBlocksInGroup2 = numTotalBytes % numRSBlocks;
    // numRsBlocksInGroup1 = 5 - 1 = 4
    int numRsBlocksInGroup1 = numRSBlocks - numRsBlocksInGroup2;
    // numTotalBytesInGroup1 = 196 / 5 = 39
    int numTotalBytesInGroup1 = numTotalBytes / numRSBlocks;
    // numTotalBytesInGroup2 = 39 + 1 = 40
    int numTotalBytesInGroup2 = numTotalBytesInGroup1 + 1;
    // numDataBytesInGroup1 = 66 / 5 = 13
    int numDataBytesInGroup1 = numDataBytes / numRSBlocks;
    // numDataBytesInGroup2 = 13 + 1 = 14
    int numDataBytesInGroup2 = numDataBytesInGroup1 + 1;
    // numEcBytesInGroup1 = 39 - 13 = 26
    int numEcBytesInGroup1 = numTotalBytesInGroup1 - numDataBytesInGroup1;
    // numEcBytesInGroup2 = 40 - 14 = 26
    int numEcBytesInGroup2 = numTotalBytesInGroup2 - numDataBytesInGroup2;
    // Sanity checks.
    // 26 = 26
    if (numEcBytesInGroup1 != numEcBytesInGroup2) {
      throw new WriterException("EC bytes mismatch");
    }
    // 5 = 4 + 1.
    if (numRSBlocks != numRsBlocksInGroup1 + numRsBlocksInGroup2) {
      throw new WriterException("RS blocks mismatch");
    }
    // 196 = (13 + 26) * 4 + (14 + 26) * 1
    if (numTotalBytes !=
        ((numDataBytesInGroup1 + numEcBytesInGroup1) *
            numRsBlocksInGroup1) +
            ((numDataBytesInGroup2 + numEcBytesInGroup2) *
                numRsBlocksInGroup2)) {
      throw new WriterException("Total bytes mismatch");
    }

    if (blockID < numRsBlocksInGroup1) {
      numDataBytesInBlock[0] = numDataBytesInGroup1;
      numECBytesInBlock[0] = numEcBytesInGroup1;
    } else {
      numDataBytesInBlock[0] = numDataBytesInGroup2;
      numECBytesInBlock[0] = numEcBytesInGroup2;
    }
  }

long readTag(long bucketIndex, int posInBucket) {
		long tagStartIdx = getTagOffset(bucketIndex, posInBucket);
		long tag = 0;
		long tagEndIdx = tagStartIdx + bitsPerTag;
		// looping over true bits per nextBitSet javadocs
		for (long i = memBlock.nextSetBit(tagStartIdx); i >= 0 && i < tagEndIdx; i = memBlock.nextSetBit(i + 1L)) {
			// set corresponding bit in tag
			tag |= 1 << (i - tagStartIdx);
		}
		return tag;
	}

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


Question: ========== PROPERTY (FROM) ==========

protected function fromArrayProperty($v, $p, $pn, $policy,
                                         Reader $ar,
                                         PolicyResolver $pr,
                                         EntityManagerInterface $em,
                                         \ReflectionClass $refClass) {
        $setter = $policy->setter ?: 'set'.ucfirst($pn);
        $getter = $policy->getter ?: 'get'.ucfirst($pn);

        if($policy instanceof Policy\Interfaces\CustomFrom) {
            if(call_user_func_array($policy->closure, [$v, $pn, $this, $em])) { return; }
        }

        // ========== SCALAR TYPES ==========
        if($column = $ar->getPropertyAnnotation($p, 'Doctrine\ORM\Mapping\Column')) {
            $oldV = $this->$getter();

            if($policy instanceof Policy\Interfaces\DenyUnsetFrom) {
                if($v === null) { return; } // deny set to null
                if(!$pr->isNumberType($column->type) && !$v) {
                    // numbers can never be "empty": deny unset for non-numbers only
                    return;
                }
            }

            if($policy instanceof Policy\Interfaces\DenyNewFrom) {
                if($pr->isNumberType($column->type)) {
                    // numbers can never be "empty": deny new for nullable only
                    if($oldV === null) { return; }
                } else if($v && !$oldV) {
                    return; // deny new for other types
                }
            }

            if($policy instanceof Policy\Interfaces\DenyUpdateFrom) {
                if($pr->isNumberType($column->type)) {
                    // numbers can never be "empty": deny update for non-nullable only
                    if($v !== null && $oldV !== null) { return; }
                } else if($v && $oldV) {
                    return; // deny update for other types
                }
            }

            switch($column->type) {
                case 'string':
                case 'text':
                case 'guid':
                    if(is_string($v)) { $this->$setter($v); return; } break;
                case 'object':
                case 'array':
                    if(! $pr->hasOption(PolicyResolver::OPT_IGNORE_CVE_2015_0231)) {
                        throw new Exceptions\FromArrayException('Column type "'.$column->type.'" is disabled due to CVE-2015-0231.'
                                                                .'Use PolicyResolver::IGNORE_CVE_2015_0231 to ignore.');
                    }
                case 'simple_array':
                    if(is_array($v)) {
                        // @see https://github.com/doctrine/doctrine2/issues/4673
                        if((count($v) === 0) && !$column->nullable && $pr->hasOption(PolicyResolver::SIMPLE_ARRAY_FIX)) {
                            $this->$setter([null]);
                            return;
                        }
                        $this->$setter($v); return;
                    } break;
                case 'json_array':  if(is_array($v)) { $this->$setter($v); return; } break;
                case 'blob':
                    if(is_resource($v) && get_resource_type($v) == 'stream') {
                        $this->$setter($v);
                        return;
                    } else if(is_string($v)) {
                        $stream = fopen('php://memory','r+');
                        fwrite($stream, $v);
                        rewind($stream);
                        $this->$setter($stream);
                        return;
                    }
                    break;
                case 'integer':
                case 'smallint':    if(is_integer($v)) { $this->$setter($v); return; } break;
                case 'bigint':      if(is_numeric($v)) { $this->$setter($v); return; } break;
                case 'boolean':     if(is_bool($v)) { $this->$setter($v); return; } break;
                case 'decimal':     if(is_numeric($v)) { $this->$setter($v); return; } break;
                case 'float':       if(is_integer($v) || is_double($v)) { $this->$setter((double)$v); return; } break;
                case 'date':
                case 'time':
                case 'datetime':
                case 'detetimez':
                    $dt = $v;
                    if($dt) {
                        if(is_string($dt)) {
                            $dt = \DateTime::createFromFormat('Y-m-d\TH:i:s+', substr($dt, 0, 19), new \DateTimeZone('UTC'));
                        }
                        if(! $dt instanceof \DateTime) {
                            throw new Exceptions\FromArrayException('Field "'.$pn.'" must be an ISO8601 string'.($column->nullable ? ' or null' : ''));
                        }
                    } else if($column->nullable || $pr->hasOption(PolicyResolver::ALLOW_NON_NULLABLE)) {
                        $dt = null;
                    } else {
                        throw new Exceptions\FromArrayException('Field "'.$pn.'" must be an ISO8601 string');
                    }
                    $this->$setter($dt);
                    return;
            }
            if($v === null) {
                if($column->nullable || $pr->hasOption(PolicyResolver::ALLOW_NON_NULLABLE)) {
                    $this->$setter(null);
                    return;
                } else {
                    throw new Exceptions\FromArrayException('Field "'.$pn.'" cannot be null. Use PolicyResolver::ALLOW_NON_NULLABLE to ignore.');
                }
            }
            throw new Exceptions\FromArrayException('Field "'.$pn.'" must be a type of "'.$column->type.'"');

        // ========== RELATIONS ==========
        } else if($association = static::getPropertyAssociation($p, $ar)) {
            $this->fromArrayRelation($v, $p, $pn, $getter, $setter, $association, $policy, $ar, $pr, $em, $refClass);

        // ========== NON-DOCTRINE TYPE ==========
        } else {
            $this->$setter($v);
        }
    }

func (bc BarChart) box() Box {
	dpr := bc.Background.Padding.GetRight(10)
	dpb := bc.Background.Padding.GetBottom(50)

	return Box{
		Top:    bc.Background.Padding.GetTop(20),
		Left:   bc.Background.Padding.GetLeft(20),
		Right:  bc.GetWidth() - dpr,
		Bottom: bc.GetHeight() - dpb,
	}
}

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


Question: // Delete Object deletes from cache as well if backend operation succeeds

func (c cacheObjects) DeleteObject(ctx context.Context, bucket, object string) (err error) {
	if err = c.DeleteObjectFn(ctx, bucket, object); err != nil {
		return
	}
	if c.isCacheExclude(bucket, object) {
		return
	}
	dcache, cerr := c.cache.getCachedFSLoc(ctx, bucket, object)
	if cerr == nil {
		_ = dcache.DeleteObject(ctx, bucket, object)
	}
	return
}

protected function action($method, array $data = [], $flush = null)
    {
        $data = $this->data($data);

        $this->clearCache($flush);

        return $this->client->$method($data);
    }

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


Question: // Validate inspects the fields of the type to determine if they are valid.

func (s *RecipientDsnFields) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RecipientDsnFields"}
	if s.Action == nil {
		invalidParams.Add(request.NewErrParamRequired("Action"))
	}
	if s.Status == nil {
		invalidParams.Add(request.NewErrParamRequired("Status"))
	}
	if s.ExtensionFields != nil {
		for i, v := range s.ExtensionFields {
			if v == nil {
				continue
			}
			if err := v.Validate(); err != nil {
				invalidParams.AddNested(fmt.Sprintf("%s[%v]", "ExtensionFields", i), err.(request.ErrInvalidParams))
			}
		}
	}

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

func (s *messageStoreImpl) CheckValid(message interface{}) bool {
	s.lock.RLock()
	defer s.lock.RUnlock()

	for _, m := range s.messages {
		if s.pol(message, m.data) == common.MessageInvalidated {
			return false
		}
	}
	return true
}

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


Question:
List submitted batch-processing jobs.

Lists batch-processing jobs submitted by users.

@param listBatchesOptions the {@link ListBatchesOptions} containing the options for the call
@return a {@link ServiceCall} with a response type of {@link Batches}

public ServiceCall<Batches> listBatches(ListBatchesOptions listBatchesOptions) {
    String[] pathSegments = { "v1/batches" };
    RequestBuilder builder = RequestBuilder.get(RequestBuilder.constructHttpUrl(getEndPoint(), pathSegments));
    builder.query("version", versionDate);
    Map<String, String> sdkHeaders = SdkCommon.getSdkHeaders("compare-comply", "v1", "listBatches");
    for (Entry<String, String> header : sdkHeaders.entrySet()) {
      builder.header(header.getKey(), header.getValue());
    }
    builder.header("Accept", "application/json");
    if (listBatchesOptions != null) {
    }
    return createServiceCall(builder.build(), ResponseConverterUtils.getObject(Batches.class));
  }

def show_input(self, template_helper, language, seed):

        choices = []
        limit = self._limit
        if limit == 0:
            limit = len(self._choices)  # no limit

        rand = Random("{}#{}#{}".format(self.get_task().get_id(), self.get_id(), seed))

        # Ensure that the choices are random
        # we *do* need to copy the choices here
        random_order_choices = list(self._choices)
        rand.shuffle(random_order_choices)

        if self._multiple:
            # take only the valid choices in the first pass
            for entry in random_order_choices:
                if entry['valid']:
                    choices.append(entry)
                    limit = limit - 1
            # take everything else in a second pass
            for entry in random_order_choices:
                if limit == 0:
                    break
                if not entry['valid']:
                    choices.append(entry)
                    limit = limit - 1
        else:
            # need to have ONE valid entry
            for entry in random_order_choices:
                if not entry['valid'] and limit > 1:
                    choices.append(entry)
                    limit = limit - 1
            for entry in random_order_choices:
                if entry['valid'] and limit > 0:
                    choices.append(entry)
                    limit = limit - 1

        rand.shuffle(choices)

        header = ParsableText(self.gettext(language, self._header), "rst",
                              translation=self._translations.get(language, gettext.NullTranslations()))

        return str(DisplayableMultipleChoiceProblem.get_renderer(template_helper).tasks.multiple_choice(
            self.get_id(), header, self._multiple, choices,
            lambda text: ParsableText(self.gettext(language, text) if text else "", "rst",
                                      translation=self._translations.get(language, gettext.NullTranslations()))))

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


Question:
Immediately executes an event with the provided executor. If an event
is already executing for the identical key, queue the event and execute
the event with FIFO scheme, preserving the order of the arrival.

public void queue(final AsyncEvent<K> _event) {
    final K key = _event.getKey();
    synchronized (getLockObject(key)) {
      Queue<AsyncEvent<K>> q = keyQueue.get(key);
      if (q != null) {
        q.add(_event);
        return;
      }
      q = new LinkedList<AsyncEvent<K>>();
      keyQueue.put(key, q);
    }
    Runnable r = new Runnable() {
      @Override
      public void run() {
        runMoreOrStop(_event);
      }
    };
    executor.execute(r);
  }

func (qm *QuotaMonitor) Run(stopCh <-chan struct{}) {
	klog.Infof("QuotaMonitor running")
	defer klog.Infof("QuotaMonitor stopping")

	// Set up the stop channel.
	qm.monitorLock.Lock()
	qm.stopCh = stopCh
	qm.running = true
	qm.monitorLock.Unlock()

	// Start monitors and begin change processing until the stop channel is
	// closed.
	qm.StartMonitors()
	wait.Until(qm.runProcessResourceChanges, 1*time.Second, stopCh)

	// Stop any running monitors.
	qm.monitorLock.Lock()
	defer qm.monitorLock.Unlock()
	monitors := qm.monitors
	stopped := 0
	for _, monitor := range monitors {
		if monitor.stopCh != nil {
			stopped++
			close(monitor.stopCh)
		}
	}
	klog.Infof("QuotaMonitor stopped %d of %d monitors", stopped, len(monitors))
}

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


Question: Parse a {@link SocketAddress} from the given string.

public static SocketAddress parseSocketAddress(String value) {
    if (value.startsWith(UNIX_DOMAIN_SOCKET_PREFIX)) {
      // Unix Domain Socket address.
      // Create the underlying file for the Unix Domain Socket.
      String filePath = value.substring(UNIX_DOMAIN_SOCKET_PREFIX.length());
      File file = new File(filePath);
      if (!file.isAbsolute()) {
        throw new IllegalArgumentException("File path must be absolute: " + filePath);
      }
      try {
        if (file.createNewFile()) {
          // If this application created the file, delete it when the application exits.
          file.deleteOnExit();
        }
      } catch (IOException ex) {
        throw new RuntimeException(ex);
      }
      // Create the SocketAddress referencing the file.
      return new DomainSocketAddress(file);
    } else {
      // Standard TCP/IP address.
      String[] parts = value.split(":", 2);
      if (parts.length < 2) {
        throw new IllegalArgumentException(
            "Address must be a unix:// path or be in the form host:port. Got: " + value);
      }
      String host = parts[0];
      int port = Integer.parseInt(parts[1]);
      return new InetSocketAddress(host, port);
    }
  }

def create_context_location(source_input,
                                document: nil,
                                pointer_segments: [])
      source = if !document
                 Openapi3Parser::Document.new(source_input).root_source
               else
                 Openapi3Parser::Source.new(
                   source_input,
                   document,
                   Openapi3Parser::Document::ReferenceRegister.new
                 )
               end

      Openapi3Parser::Context::Location.new(source, pointer_segments)
    end

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


Question: // SetDescription sets the Description field's value.

func (s *Patch) SetDescription(v string) *Patch {
	s.Description = &v
	return s
}

def _descr_str(descr, data, region):

    if data:
        name = dd.get_sample_name(data)
        if name:
            descr = "{0} : {1}".format(descr, name)
        elif "work_bam" in data:
            descr = "{0} : {1}".format(descr, os.path.basename(data["work_bam"]))
    if region:
        descr = "{0} : {1}".format(descr, region)
    return descr

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


Question: Return the node for a path, or None.

def find(self, path):
        """"""
        path = path.split('.')
        node = self
        while node._parent:
            node = node._parent
        for name in path:
            node = node._tree.get(name, None)
            if node is None or type(node) is float:
                return None
        return node

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

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


Question: // obj could be an *v1.Service, or a DeletionFinalStateUnknown marker item.

func (s *ServiceController) enqueueService(obj interface{}) {
	key, err := controller.KeyFunc(obj)
	if err != nil {
		klog.Errorf("Couldn't get key for object %#v: %v", obj, err)
		return
	}
	s.queue.Add(key)
}

function mapObject(key, value) {
		var c = key.charAt(0);
		if (c === "_" || c === "$") {
			return undefined;
		} else if (isArray(this) && key.match(INTRINSIC)) {
			return undefined;
		} else if (isType(value)) {
			return parse(value);
		} else if (gui.Type.isComplex(value)) {
			switch (value.constructor) {
				case Object:
				case Array:
					return value;
			}
			return undefined;
		} else {
			if (isType(this)) {
				var base = this.constructor.prototype;
				var desc = Object.getOwnPropertyDescriptor(base, key);
				if (desc && (desc.set || desc.get)) {
					return undefined;
				}
			}
			return value;
		}
	}

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


Question:
Return the 'back' link that normally appears in the footer.

@return string HTML fragment.

public function home_link() {
        global $CFG, $SITE;

        if ($this->page->pagetype == 'site-index') {
            // Special case for site home page - please do not remove
            return '
' .
                   '' .
                   'image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" />
';

        } else if (!empty($CFG->target_release) && $CFG->target_release != $CFG->release) {
            // Special case for during install/upgrade.
            return '
'.
                   '' .
                   'image_url('moodlelogo') . '" alt="'.get_string('moodlelogo').'" />
';

        } else if ($this->page->course->id == $SITE->id || strpos($this->page->pagetype, 'course-view') === 0) {
            return '
wwwroot . '/">' .
                    get_string('home') . '
';

        } else {
            return '
wwwroot . '/course/view.php?id=' . $this->page->course->id . '">' .
                    format_string($this->page->course->shortname, true, array('context' => $this->page->context)) . '
';
        }
    }

function fetch(params) {
    let fetchObj = null;
    if (/^http(s{0,1}):\/\//.test(params.url)) {
        const pageLoc = location.href.match(/^https{0,1}:\/\/(.+?)(?=\/|$)/);
        const ajaxLoc = params.url.match(/^https{0,1}:\/\/(.+?)(?=\/|$)/);
        if (pageLoc.length === 2 && ajaxLoc.length === 2 && ajaxLoc[1] === pageLoc[1]) {
            fetchObj = this.ajax(params);
        } else {
            fetchObj = this.jsonp(params);
        }
    } else {
        fetchObj = this.ajax(params);
    }
    return fetchObj;
}

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


Question:
Probe constructor.

@constructor
@param {Collector} collector instance
@api public

function Probe(collector) {
    this.fuse();

    //
    // Name of the probe, the registries the probe should run against
    // and how often it should run.
    //
    this.readable('name', name);
    this.readable('collector', collector);
    this.readable('list', Object.keys(require('../registries')));

    //
    // How often should the probe run.
    //
    this.readable('interval', interval);
  }

def create(self, **kwargs):
        """"""
        if 'monitor' in kwargs:
            value = self._format_monitor_parameter(kwargs['monitor'])
            kwargs['monitor'] = value
        return super(Pool, self)._create(**kwargs)

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


Question: // CreateUser adds a user to Influx Enterprise

func (m *MetaClient) CreateUser(ctx context.Context, name, passwd string) error {
	return m.CreateUpdateUser(ctx, "create", name, passwd)
}

public function injectSettings(array $settings) {
		if (isset($settings['server'])) {
			if (!is_array($settings['server'])) {
				throw new Exception('Invalid Flowpack.SingleSignOn.Client.server configuration', 1351688261);
			}
			$this->serverConfigurations = $settings['server'];
		}
	}

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


Question:
Event listener to listen broadcast

@param string $event
@param mixed $handler

public function listen($event, $handler)
    {
        if(array_key_exists($event, $this->broadcast)) {

            $eventObject = $this->getEventObject($event, $this->broadcast[$event]);

            if(is_callable($handler)) {
                call_user_func_array($handler, [$eventObject]);
            } else {
                call_user_func_array([$this->app->make($handler), 'listen'], [$eventObject]);
            }
        }
    }

func (s Server) Handle(data []byte) ([]byte, error) {
	request, err := s.p.DecodeEnveloped(bytes.NewReader(data))
	if err != nil {
		return nil, err
	}

	response := wire.Envelope{
		Name:  request.Name,
		SeqID: request.SeqID,
		Type:  wire.Reply,
	}

	response.Value, err = s.h.Handle(request.Name, request.Value)
	if err != nil {
		response.Type = wire.Exception
		switch err.(type) {
		case ErrUnknownMethod:
			response.Value, err = tappExc(err, exception.ExceptionTypeUnknownMethod)
		default:
			response.Value, err = tappExc(err, exception.ExceptionTypeInternalError)
		}

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

	var buff bytes.Buffer
	if err := s.p.EncodeEnveloped(response, &buff); err != nil {
		return nil, err
	}

	return buff.Bytes(), nil
}

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


Question:
Perform lookup for series

        :param str series_name: series name found within filename
        :returns: instance of series
        :rtype: object

def get_series_by_name(self, series_name):

        try:
            return self.api.search_series(name=series_name), None
        except exceptions.TVDBRequestException as err:
            LOG.exception('search for series %s failed', series_name)
            return None, _as_str(err)

def reporter(self):

        # Initialise variables
        combinedrow = ''
        reportdirset = set()
        # Populate a set of all the report directories to use. A standard analysis will only have a single report
        # directory, while pipeline analyses will have as many report directories as there are assembled samples
        for sample in self.metadata:
            # Ignore samples that lack a populated reportdir attribute
            if sample[self.analysistype].reportdir != 'NA':
                make_path(sample[self.analysistype].reportdir)
                # Add to the set - I probably could have used a counter here, but I decided against it
                reportdirset.add(sample[self.analysistype].reportdir)
        # Create a report for each sample from :self.resultprofile
        for sample in self.metadata:
            if sample[self.analysistype].reportdir != 'NA':
                if type(sample[self.analysistype].allelenames) == list:
                    # Populate the header with the appropriate data, including all the genes in the list of targets
                    row = 'Strain,Genus,SequenceType,Matches,{},\n' \
                        .format(','.join(sorted(sample[self.analysistype].allelenames)))
                    # Set the sequence counter to 0. This will be used when a sample has multiple best sequence types.
                    # The name of the sample will not be written on subsequent rows in order to make the report clearer
                    seqcount = 0
                    # Iterate through the best sequence types for the sample (only occurs if update profile is disabled)
                    for seqtype in self.resultprofile[sample.name]:
                        """
                        {
                            "OLF15230-1_2015-SEQ-0783": {
                                "1000004_CFIA": {
                                    "7": {
                                        "dnaE": {
                                            "47": "100.00"
                                        },
                                        "dtdS": {
                                            "19": "100.00"
                                        },
                                        "gyrB": {
                                            "359": "100.00"
                                        },
                                        "pntA": {
                                            "50": "100.00"
                                        },
                                        "pyrC": {
                                            "143": "100.00"
                                        },
                                        "recA": {
                                            "31": "100.00"
                                        },
                                        "tnaA": {
                                            "26": "100.00"
                                        }
                                    }
                                }
                            }
                        }
                        """
                        # Becomes
                        """
                        Strain,SequenceType,Matches,dnaE,gyrB,recA,dtdS,pntA,pyrC,tnaA
                        OLF15230-1_2015-SEQ-0783,1000004_CFIA,7,26 (100.00%),359 (100.00%),31 (100.00%),50 (100.00%),
                            19 (100.00%),47 (100.00%),143 (100.00%)
                        """
                        sample[self.analysistype].sequencetype = seqtype
                        # The number of matches to the profile
                        matches = list(self.resultprofile[sample.name][seqtype].keys())[0]
                        # If this is the first of one or more sequence types, include the sample name
                        if seqcount == 0:
                            row += '{},{},{},{},'.format(sample.name, sample.general.referencegenus, seqtype, matches)
                        # Otherwise, skip the sample name
                        else:
                            row += ',,{},{},'.format(seqtype, matches)
                        # Iterate through all the genes present in the analyses for the sample
                        for gene in sorted(sample[self.analysistype].allelenames):
                            # refallele = self.profiledata[self.analysistype][seqtype][gene]
                            refallele = sample[self.analysistype].profiledata[seqtype][gene]
                            # Set the allele and percent id from the dictionary's keys and values, respectively
                            allele = list(self.resultprofile[sample.name][seqtype][matches][gene].keys())[0]
                            percentid = list(self.resultprofile[sample.name][seqtype][matches][gene].values())[0]
                            if refallele and refallele != allele:
                                if 0 < float(percentid) < 100:
                                    row += '{} ({:.2f}%),'.format(allele, float(percentid))
                                else:
                                    row += '{} ({}),'.format(allele, refallele)
                            else:
                                # Add the allele and % id to the row (only add the percent identity if it is not 100%)
                                if 0 < float(percentid) < 100:
                                    row += '{} ({:.2f}%),'.format(allele, float(percentid))
                                else:
                                    row += '{},'.format(allele)
                            self.referenceprofile[sample.name][gene] = allele
                        # Add a newline
                        row += '\n'
                        # Increment the number of sequence types observed for the sample
                        seqcount += 1
                    combinedrow += row
                    # If the length of the # of report directories is greater than 1 (script is being run as part of
                    # the assembly pipeline) make a report for each sample
                    if self.pipeline:
                        # Open the report
                        with open('{}{}_{}.csv'.format(sample[self.analysistype].reportdir, sample.name,
                                                       self.analysistype), 'w') as report:
                            # Write the row to the report
                            report.write(row)
                dotter()
            # Create the report folder
            make_path(self.reportpath)
            # Create the report containing all the data from all samples
            if self.pipeline:
                with open('{}{}.csv'.format(self.reportpath, self.analysistype), 'w') \
                        as combinedreport:
                    # Write the results to this report
                    combinedreport.write(combinedrow)
            else:
                with open('{}{}_{:}.csv'.format(self.reportpath, self.analysistype, time.strftime("%Y.%m.%d.%H.%M.%S")),
                          'w') as combinedreport:
                    # Write the results to this report
                    combinedreport.write(combinedrow)
            # Remove the raw results csv
            [os.remove(rawresults) for rawresults in glob('{}*rawresults*'.format(self.reportpath))]

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


Question:
// ContentWithMoreMentionsReplaced will replace all @<id> mentions with the
// username of the mention, but also role IDs and more.

func (m *Message) ContentWithMoreMentionsReplaced(s *Session) (content string, err error) {
	content = m.Content

	if !s.StateEnabled {
		content = m.ContentWithMentionsReplaced()
		return
	}

	channel, err := s.State.Channel(m.ChannelID)
	if err != nil {
		content = m.ContentWithMentionsReplaced()
		return
	}

	for _, user := range m.Mentions {
		nick := user.Username

		member, err := s.State.Member(channel.GuildID, user.ID)
		if err == nil && member.Nick != "" {
			nick = member.Nick
		}

		content = strings.NewReplacer(
			"<@"+user.ID+">", "@"+user.Username,
			"<@!"+user.ID+">", "@"+nick,
		).Replace(content)
	}
	for _, roleID := range m.MentionRoles {
		role, err := s.State.Role(channel.GuildID, roleID)
		if err != nil || !role.Mentionable {
			continue
		}

		content = strings.Replace(content, "<@&"+role.ID+">", "@"+role.Name, -1)
	}

	content = patternChannels.ReplaceAllStringFunc(content, func(mention string) string {
		channel, err := s.State.Channel(mention[2 : len(mention)-1])
		if err != nil || channel.Type == ChannelTypeGuildVoice {
			return mention
		}

		return "#" + channel.Name
	})
	return
}

def _formatEvidence(self, elements):

        elementClause = None
        filters = []
        for evidence in elements:
            if evidence.description:
                elementClause = 'regex(?{}, "{}")'.format(
                    'environment_label', evidence.description)
            if (hasattr(evidence, 'externalIdentifiers') and
                    evidence.externalIdentifiers):
                # TODO will this pick up > 1 externalIdentifiers ?
                for externalIdentifier in evidence['externalIdentifiers']:
                    exid_clause = self._formatExternalIdentifier(
                        externalIdentifier, 'environment')
                    # cleanup parens from _formatExternalIdentifier method
                    elementClause = exid_clause[1:-1]
            if elementClause:
                filters.append(elementClause)
        elementClause = "({})".format(" || ".join(filters))
        return elementClause

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


Question:
Convert csv to json.

    csv:  filename or file-like object
    json: filename  or file-like object

    if csv is '-' or None:
        stdin is used for input
    if json is '-' or None:
        stdout is used for output

def convert(csv, json, **kwargs):
    '''
    '''

    csv_local, json_local = None, None
    try:
        if csv == '-' or csv is None:
            csv = sys.stdin
        elif isinstance(csv, str):
            csv = csv_local = open(csv, 'r')

        if json == '-' or json is None:
            json = sys.stdout
        elif isinstance(json, str):
            json = json_local = open(json, 'w')

        data = load_csv(csv, **kwargs)
        save_json(data, json, **kwargs)
    finally:
        if csv_local is not None:
            csv_local.close()
        if json_local is not None:
            json_local.close()

func (cli *Client) VolumeInspectWithRaw(ctx context.Context, volumeID string) (types.Volume, []byte, error) {
	if volumeID == "" {
		return types.Volume{}, nil, objectNotFoundError{object: "volume", id: volumeID}
	}

	var volume types.Volume
	resp, err := cli.get(ctx, "/volumes/"+volumeID, nil, nil)
	defer ensureReaderClosed(resp)
	if err != nil {
		return volume, nil, wrapResponseError(err, resp, "volume", volumeID)
	}

	body, err := ioutil.ReadAll(resp.body)
	if err != nil {
		return volume, nil, err
	}
	rdr := bytes.NewReader(body)
	err = json.NewDecoder(rdr).Decode(&volume)
	return volume, body, err
}

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