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

@Override
  public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
  {
    switch (featureID)
    {
      case SimpleAntlrPackage.AND_EXPRESSION__LEFT:
        return basicSetLeft(null, msgs);
      case SimpleAntlrPackage.AND_EXPRESSION__RIGHT:
        return basicSetRight(null, msgs);
    }
    return super.eInverseRemove(otherEnd, featureID, msgs);
  }

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

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

            config.script = wrapped_script

        return Container(config)

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


Question:
Authenticates in as the user
@return boolean

private function authenticate()
    {
        $form = new RemoteIdentityForm;
        $form->attributes = array(
            'adapter'  => $this->getUserProfile(),
            'provider' => $this->getProvider()
        );

        return $form->login();
    }

public static function current($addAuth = false)
    {
        $current = (string)self::root($addAuth) . (string)self::path();
        return $current ?: null;
    }

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


Question:
// Stats returns the statistics of channel link.
//
// NOTE: Part of the ChannelLink interface.

func (l *channelLink) Stats() (uint64, lnwire.MilliSatoshi, lnwire.MilliSatoshi) {
	snapshot := l.channel.StateSnapshot()

	return snapshot.ChannelCommitment.CommitHeight,
		snapshot.TotalMSatSent,
		snapshot.TotalMSatReceived
}

public void initialize(final int appId, final String appSecret, final String bridgeId,
      final ServerInfo serverInfo, final CallStatsInitListener callStatsInitListener) {
    if (StringUtils.isBlank(appSecret)) {
      logger.error("intialize: Arguments cannot be null ");
      throw new IllegalArgumentException("intialize: Arguments cannot be null");
    }
    initialize(appId, new TokenGeneratorHs256(appSecret.toCharArray(), appId, bridgeId), bridgeId,
        serverInfo, callStatsInitListener);
  }

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


Question:
Push a new job onto the queue.

@param  string  $job
@param  mixed   $data
@param  string  $queue
@return mixed

public function push($job, $data = '', $queue = null)
    {
        return $this->pushRaw($this->createPayload($job, $data, $queue), $queue);
    }

def addReplaceDBPage( dbid, pageid, pagename, pagetype, pagebody, ignoreError = nil )

      @dbid, @pageid, @pagename, @pagetype, @pagebody, @ignoreError = dbid, pageid, pagename, pagetype, pagebody, ignoreError

      if pageid
         xmlRequestData = toXML( :pageid, @pageid )
      elsif pagename
         xmlRequestData = toXML( :pagename, @pagename )
      else
         raise "addReplaceDBPage: missing pageid or pagename"
      end

      xmlRequestData << toXML( :pagetype, @pagetype )
      xmlRequestData << toXML( :pagebody, encodeXML( @pagebody ) )
      xmlRequestData << toXML( :ignoreError, "1" ) if @ignoreError

      sendRequest( :addReplaceDBPage, xmlRequestData )

      @pageid = getResponseValue( :pageid )
      @pageid ||= getResponseValue( :pageID ) # temporary

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
Parse the URI.

        uri is the uri to parse.
        defaults is a scheme-dependent list of values to use if there
        is no value for that part in the supplied URI.

        The return value is a tuple of scheme-dependent length.

def parse(self, uri, defaults=None):

        return tuple([self.scheme_of(uri)] + list(self.parser_for(uri)(defaults).parse(uri)))

func UnmarshalServerResource(data []byte, kind string, cfg *MarshalConfig) (Server, error) {
	if len(data) == 0 {
		return nil, trace.BadParameter("missing server data")
	}

	var h ResourceHeader
	err := utils.FastUnmarshal(data, &h)
	if err != nil {
		return nil, trace.Wrap(err)
	}

	switch h.Version {
	case "":
		var s ServerV1
		err := utils.FastUnmarshal(data, &s)
		if err != nil {
			return nil, trace.Wrap(err)
		}
		s.Kind = kind
		v2 := s.V2()
		if cfg.ID != 0 {
			v2.SetResourceID(cfg.ID)
		}
		if !cfg.Expires.IsZero() {
			v2.SetExpiry(cfg.Expires)
		}
		return v2, nil
	case V2:
		var s ServerV2

		if cfg.SkipValidation {
			if err := utils.FastUnmarshal(data, &s); err != nil {
				return nil, trace.BadParameter(err.Error())
			}
		} else {
			if err := utils.UnmarshalWithSchema(GetServerSchema(), &s, data); err != nil {
				return nil, trace.BadParameter(err.Error())
			}
		}
		s.Kind = kind
		if err := s.CheckAndSetDefaults(); err != nil {
			return nil, trace.Wrap(err)
		}
		if cfg.ID != 0 {
			s.SetResourceID(cfg.ID)
		}
		if !cfg.Expires.IsZero() {
			s.SetExpiry(cfg.Expires)
		}
		return &s, nil
	}
	return nil, trace.BadParameter("server resource version %q is not supported", h.Version)
}

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


Question:
Sets the distance from the origin to the near clipping plane for the
whole camera rig.

@param near
Distance to the near clipping plane.

public void setNearClippingDistance(float near) {
        if(leftCamera instanceof GVRCameraClippingDistanceInterface &&
           centerCamera instanceof GVRCameraClippingDistanceInterface &&
           rightCamera instanceof GVRCameraClippingDistanceInterface) {
            ((GVRCameraClippingDistanceInterface)leftCamera).setNearClippingDistance(near);
            centerCamera.setNearClippingDistance(near);
            ((GVRCameraClippingDistanceInterface)rightCamera).setNearClippingDistance(near);
        }
    }

def main():
    """"""

    parser = argparse.ArgumentParser(
        description='Tool for testing caffe to mxnet conversion layer by layer')
    parser.add_argument('--image_url', type=str,
                        default='https://github.com/dmlc/web-data/raw/master/mxnet/doc/'\
                                'tutorials/python/predict_image/cat.jpg',
                        help='input image to test inference, can be either file path or url')
    parser.add_argument('--caffe_prototxt_path', type=str,
                        default='./model.prototxt',
                        help='path to caffe prototxt')
    parser.add_argument('--caffe_model_path', type=str,
                        default='./model.caffemodel',
                        help='path to caffe weights')
    parser.add_argument('--caffe_mean', type=str,
                        default='./model_mean.binaryproto',
                        help='path to caffe mean file')
    parser.add_argument('--mean_diff_allowed', type=int, default=1e-03,
                        help='mean difference allowed between caffe blob and mxnet blob')
    parser.add_argument('--max_diff_allowed', type=int, default=1e-01,
                        help='max difference allowed between caffe blob and mxnet blob')
    parser.add_argument('--gpu', type=int, default=-1, help='the gpu id used for predict')
    args = parser.parse_args()
    convert_and_compare_caffe_to_mxnet(args.image_url, args.gpu, args.caffe_prototxt_path,
                                       args.caffe_model_path, args.caffe_mean,
                                       args.mean_diff_allowed, args.max_diff_allowed)

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


Question:
// Empty returns a bool indicating if there are any items left
// in the queue.

func (pq *PriorityQueue) Empty() bool {
	pq.lock.Lock()
	defer pq.lock.Unlock()

	return len(pq.items) == 0
}

def is_code?(lineno)
      unless @is_begin_comment
        @is_begin_comment = Array.new(@lines.size, false)
        pending = []
        state = :code
        @lines.each_with_index do |line, index|
          case state
          when :code
            if /^=begin\b/ =~ line
              state = :comment
              pending << index
            end
          when :comment
            pending << index
            if /^=end\b/ =~ line
              state = :code
              pending.each{|idx| @is_begin_comment[idx] = true}
              pending.clear
            end
          end
        end
      end
      @lines[lineno] && !@is_begin_comment[lineno] && @lines[lineno] !~ /^\s*(#|$)/
    end

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


Question: Marshall the given parameter object.

public void marshall(RebootWorkspacesRequest rebootWorkspacesRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(rebootWorkspacesRequest.getRebootWorkspaceRequests(), REBOOTWORKSPACEREQUESTS_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question:
Sets the new service and notifies the listener that the service was changed.

@param newService the new service

private synchronized void setService( final T newService )
    {
        if( m_service != newService )
        {
            LOG.debug( "Service changed [" + m_service + "]  -> [" + newService + "]" );
            final T oldService = m_service;
            m_service = newService;
            if( m_serviceListener != null )
            {
                m_serviceListener.serviceChanged( oldService, m_service );
            }
        }
    }

public void update(String subjectName, Object data)
   {
         Debugger.println(this,"Recieve subject="+subjectName);

         if(isStart(subjectName))
         {
            this.startData = data;
            this.startDate = LocalDateTime.now();
            Debugger.printInfo(this,"TIMER START DATE ["+Text.formatDate(startDate)+"]\n "+Text.toString(startData));

         }
         else if(isEnd(subjectName))
         {
            this.endData = data;
            this.endDate = LocalDateTime.now();

            Debugger.printInfo(this,"TIMER END DATE ["+endDate+"]\n "+endData);

            if(this.decorator != null)
               decorator.decorator(this);
         }
         else
         {
            throw new SystemException("Unknown subject "+subjectName);
         }
   }

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


Question: // getContainer retrieves a container from the docker client based on id

func (s *Server) getContainer(id string) (*docker.APIContainers, error) {
	containers, err := s.DockerClient.ListContainers(docker.ListContainersOptions{})
	if err != nil {
		return nil, err
	}
	for _, container := range containers {
		// send container to channel for processing
		if container.ID == id {
			return &container, nil
		}
	}
	return nil, fmt.Errorf("could not find container with id %v", id)
}

def _get_component(self, component_type: Type[C]) -> Iterable[Tuple[int, C]]:

        entity_db = self._entities

        for entity in self._components.get(component_type, []):
            yield entity, entity_db[entity][component_type]

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


Question:
Control low limit setting for a special sensor.

        For LS-10/LS-20 base units only.

def control_low_limit(self) -> Optional[Union[int, float]]:

        return self._get_field_value(SpecialDevice.PROP_CONTROL_LOW_LIMIT)

@Override
  public void close() {
    log.info("Updating the current state high water mark with " + this.highWatermark);
    this.workUnitState.setActualHighWatermark(new LongWatermark(this.highWatermark));
    try {
      this.closeConnection();
    } catch (Exception e) {
      log.error("Failed to close the extractor", e);
    }
  }

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


Question:
@param mixed $data Data to encode to send over a channel.

@return string Encoded data that can be parsed by this class.

@throws \Amp\Parallel\Sync\SerializationException

public function encode($data): string
    {
        try {
            $data = \serialize($data);
        } catch (\Throwable $exception) {
            throw new SerializationException(
                "The given data cannot be sent because it is not serializable.",
                0,
                $exception
            );
        }

        return \pack("CL", 0, \strlen($data)) . $data;
    }

public void marshall(VpcLink vpcLink, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(vpcLink.getId(), ID_BINDING);
            protocolMarshaller.marshall(vpcLink.getName(), NAME_BINDING);
            protocolMarshaller.marshall(vpcLink.getDescription(), DESCRIPTION_BINDING);
            protocolMarshaller.marshall(vpcLink.getTargetArns(), TARGETARNS_BINDING);
            protocolMarshaller.marshall(vpcLink.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(vpcLink.getStatusMessage(), STATUSMESSAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
/*

@description Deal with data received from the json loaded
@param data: object

function(data) {
      var segment;
      log('json loaded');

      if (!data.files[0].length) {
        data.files = [data.files];
      }

      for (var i = 0, l = data.files.length; i < l; i++) {
        _files.push([]);
        segment = data.files[i];

        for (var m = 0, n = segment.length; m < n; m++) {
          arrangeData(i, m, segment[m]);
        }
      }
    }

public static DescriptorExtensionList<ParameterDefinition,ParameterDescriptor> all() {
        return Jenkins.getInstance().<ParameterDefinition,ParameterDescriptor>getDescriptorList(ParameterDefinition.class);
    }

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


Question:
Reset instance of service

@param mixed $args Arguments which was service initialized

public function reset($args = null) {
		if ($args === null) {
			$this->service = null;
			return;
		}

		$args = $this->normalizeArgs($args);
		$id   = $this->getIdByArgs($args);

		unset($this->servicesByArgs[$id]);
	}

public function setToAccount($toAccount)
    {
        $toAccount = is_array($toAccount) ? $toAccount : [$toAccount];
        $this->setParameter('To_Account', $toAccount);
        return $this;
    }

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


Question:
onMessage.
@param TcpConnection $connection
@param string $buffer

public function onMessage($connection, $buffer)
    {
        if ($buffer === 'ping') {
            return;
        }
        $data = unserialize($buffer);
        if (!$buffer || !isset($data['cmd']) || !isset($data['key'])) {
            return $connection->close(serialize('bad request'));
        }
        $cmd = $data['cmd'];
        $key = $data['key'];
        switch ($cmd) {
            case 'get':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('N;');
                }
                return $connection->send(serialize($this->_dataArray[$key]));
                break;
            case 'set':
                $this->_dataArray[$key] = $data['value'];
                $connection->send('b:1;');
                break;
            case 'add':
                if (isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                $this->_dataArray[$key] = $data['value'];
                return $connection->send('b:1;');
                break;
            case 'increment':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_numeric($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = 0;
                }
                $this->_dataArray[$key] = $this->_dataArray[$key] + $data['step'];
                return $connection->send(serialize($this->_dataArray[$key]));
                break;
            case 'cas':
                if (isset($this->_dataArray[$key]) && md5(serialize($this->_dataArray[$key])) === $data['md5']) {
                    $this->_dataArray[$key] = $data['value'];
                    return $connection->send('b:1;');
                }
                $connection->send('b:0;');
                break;
            case 'push':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_array($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = array();
                }
                return $connection->send(serialize(array_push($this->_dataArray[$key], $data['value'])));
                break;
            case 'pushIfNotExist':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_array($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = array();
                }
                if (in_array($data['value'], $this->_dataArray[$key])) {
                    return $connection->send('b:1;');
                }
                return $connection->send(serialize(array_push($this->_dataArray[$key], $data['value'])));
                break;
            case 'pushToLeftIfNotExist':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_array($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = array();
                }
                if (in_array($data['value'], $this->_dataArray[$key])) {
                    return $connection->send('b:1;');
                }
                return $connection->send(serialize(array_unshift($this->_dataArray[$key], $data['value'])));
                break;
            case 'shift':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_array($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = array();
                }
                return $connection->send(serialize(array_shift($this->_dataArray[$key])));
                break;
            case 'pop':
                if (!isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                if (!is_array($this->_dataArray[$key])) {
                    $this->_dataArray[$key] = array();
                }
                return $connection->send(serialize(array_pop($this->_dataArray[$key])));
                break;
            case 'count':
                if (!isset($this->_dataArray[$key]) || !is_array($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                return $connection->send(serialize(count($this->_dataArray[$key])));
                break;
            case 'rand':
                if (!isset($this->_dataArray[$key]) || !is_array($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                return $connection->send(serialize($this->_dataArray[$key][array_rand($this->_dataArray[$key])]));
                break;
            case 'in':
                if (!isset($this->_dataArray[$key]) || !is_array($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                return $connection->send(serialize(in_array($data['value'], $this->_dataArray[$key])));
                break;
            case 'delete':
                unset($this->_dataArray[$key]);
                $connection->send('b:1;');
                break;
            case 'bfNew':
                if (isset($this->_dataArray[$key])) {
                    return $connection->send('b:0;');
                }
                $m = isset($data['value'][0]) ? $data['value'][0] : 40000;
                $k = isset($data['value'][1]) ? $data['value'][1] : 14;
                $this->_dataArray[$key] = new BloomFilter($m, $k);
                return $connection->send('b:1;');
                break;
            case 'bfAdd':
                if (!isset($this->_dataArray[$key]) || !($this->_dataArray[$key] instanceof BloomFilter)) {
                    return $connection->send('b:0;');
                }
                $this->_dataArray[$key]->add($data['value']);
                return $connection->send('b:1;');
                break;
            case 'bfIn':
                if (!isset($this->_dataArray[$key]) || !($this->_dataArray[$key] instanceof BloomFilter)) {
                    return $connection->send('b:0;');
                }
                return $connection->send(serialize($this->_dataArray[$key]->maybeInSet($data['value'])));
                break;
            default:
                $connection->close(serialize('bad cmd ' . $cmd));
        }
    }

async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None):
        """"""
        service_name = payload["service"]

        if "protocols" not in payload:
            raise SongpalException(
                "Unable to find protocols from payload: %s" % payload
            )

        protocols = payload["protocols"]
        _LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
        if force_protocol and force_protocol.value in protocols:
            protocol = force_protocol
        elif "websocket:jsonizer" in protocols:
            protocol = ProtocolType.WebSocket
        elif "xhrpost:jsonizer" in protocols:
            protocol = ProtocolType.XHRPost
        else:
            raise SongpalException(
                "No known protocols for %s, got: %s" % (service_name, protocols)
            )
        _LOGGER.debug("Using protocol: %s" % protocol)

        service_endpoint = "%s/%s" % (endpoint, service_name)

        # creation here we want to pass the created service class to methods.
        service = cls(service_name, service_endpoint, protocol, idgen, debug)

        sigs = await cls.fetch_signatures(
            service_endpoint, protocol, idgen
        )

        if debug > 1:
            _LOGGER.debug("Signatures: %s", sigs)
        if "error" in sigs:
            _LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
            return None

        methods = {}

        for sig in sigs["results"]:
            name = sig[0]
            parsed_sig = MethodSignature.from_payload(*sig)
            if name in methods:
                _LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
                              parsed_sig, methods[name])
            else:
                methods[name] = Method(service, parsed_sig, debug)

        service.methods = methods

        if "notifications" in payload and "switchNotifications" in methods:
            notifications = [
                Notification(
                    service_endpoint, methods["switchNotifications"], notification
                )
                for notification in payload["notifications"]
            ]
            service.notifications = notifications
            _LOGGER.debug("Got notifications: %s" % notifications)

        return service

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


Question: Create the file name of the output file.

public void setFileName() {
        String type = "";
        // lenskit does not provide a factorizer class. This check is to actually see if it's a Mahout or Lenskit SVD.
        if (properties.containsKey(RecommendationRunner.FACTORIZER) || properties.containsKey(RecommendationRunner.SIMILARITY)) {
            if (properties.containsKey(RecommendationRunner.FACTORIZER)) {
                type = properties.getProperty(RecommendationRunner.FACTORIZER);
            } else {
                type = properties.getProperty(RecommendationRunner.SIMILARITY);
            }
            type = type.substring(type.lastIndexOf(".") + 1) + ".";
        }
        String num = "";
        if (properties.containsKey(RecommendationRunner.FACTORS) || properties.containsKey(RecommendationRunner.NEIGHBORHOOD)) {
            if (properties.containsKey(RecommendationRunner.FACTORS)) {
                num = properties.getProperty(RecommendationRunner.FACTORS);
            } else {
                num = properties.getProperty(RecommendationRunner.NEIGHBORHOOD);
            }
            num += ".";
        }

        String trainingSet = properties.getProperty(RecommendationRunner.TRAINING_SET);
        trainingSet = trainingSet.substring(trainingSet.lastIndexOf("/") + 1, trainingSet.lastIndexOf("_train"));

        fileName = trainingSet + "."
                + properties.getProperty(RecommendationRunner.FRAMEWORK) + "."
                + properties.getProperty(RecommendationRunner.RECOMMENDER).substring(properties.getProperty(RecommendationRunner.RECOMMENDER).lastIndexOf(".") + 1) + "."
                + type
                + num
                + "tsv";

        System.out.println(fileName);
    }

def variable_outfile_iterator(outfiles, infiles, arggroups, engine):
    """"""
    assert len(outfiles) == 1

    template = engine(outfiles[0], tolerant=False)

    for infile in infiles:
        properties = make_path_properties(infile, prefix='')

        for arggroup in arggroups:
            outfile = template.apply(dict(arggroup, **properties))
            yield (outfile, infile, arggroup)

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


Question:
Converts an INDArray to a BufferedImage. Only intended for images with rank 3.

@param array to convert
@param dataType from JavaCV (DEPTH_FLOAT, DEPTH_UBYTE, etc), or -1 to use same type as the INDArray
@return data copied to a Frame

public BufferedImage asBufferedImage(INDArray array, int dataType) {
        return converter2.convert(asFrame(array, dataType));
    }

public static Object fromBytes(byte[] b, Class<?> clazz)
    {

        if (clazz.isAssignableFrom(String.class))
        {
            return Bytes.toString(b);
        }
        else if (clazz.equals(int.class) || clazz.isAssignableFrom(Integer.class))
        {
            return Bytes.toInt(b);
        }
        else if (clazz.equals(long.class) || clazz.isAssignableFrom(Long.class))
        {
            return Bytes.toLong(b);
        }
        else if (clazz.equals(boolean.class) || clazz.isAssignableFrom(Boolean.class))
        {
            return Bytes.toBoolean(b);
        }
        else if (clazz.equals(double.class) || clazz.isAssignableFrom(Double.class))
        {
            return Bytes.toDouble(b);
        }
        else if (clazz.equals(float.class) || clazz.isAssignableFrom(Float.class))
        {
            return Bytes.toFloat(b);
        }
        else if (clazz.equals(short.class) || clazz.isAssignableFrom(Short.class))
        {
            return Bytes.toShort(b);
        }
        else if (clazz.equals(BigDecimal.class))
        {
            return Bytes.toBigDecimal(b);
        }
        else
        {
            return PropertyAccessorFactory.getPropertyAccessor(clazz).fromBytes(clazz, b);
        }
    }

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


Question: // ResourceLocation returns a URL to which one can send traffic for the specified pod.

func ResourceLocation(getter ResourceGetter, rt http.RoundTripper, ctx context.Context, id string) (*url.URL, http.RoundTripper, error) {
	// Allow ID as "podname" or "podname:port" or "scheme:podname:port".
	// If port is not specified, try to use the first defined port on the pod.
	scheme, name, port, valid := utilnet.SplitSchemeNamePort(id)
	if !valid {
		return nil, nil, errors.NewBadRequest(fmt.Sprintf("invalid pod request %q", id))
	}
	// TODO: if port is not a number but a "(container)/(portname)", do a name lookup.

	pod, err := getPod(getter, ctx, name)
	if err != nil {
		return nil, nil, err
	}

	// Try to figure out a port.
	if port == "" {
		for i := range pod.Spec.Containers {
			if len(pod.Spec.Containers[i].Ports) > 0 {
				port = fmt.Sprintf("%d", pod.Spec.Containers[i].Ports[0].ContainerPort)
				break
			}
		}
	}

	if err := proxyutil.IsProxyableIP(pod.Status.PodIP); err != nil {
		return nil, nil, errors.NewBadRequest(err.Error())
	}

	loc := &url.URL{
		Scheme: scheme,
	}
	if port == "" {
		loc.Host = pod.Status.PodIP
	} else {
		loc.Host = net.JoinHostPort(pod.Status.PodIP, port)
	}
	return loc, rt, nil
}

def _update_limits_from_api(self):

        logger.info("Querying Route53 GetHostedZoneLimits for limits")
        self.connect()
        self._find_limit_hosted_zone()
        logger.debug('Done setting limits from API.')

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


Question: // SetTaskStartToCloseTimeout sets the TaskStartToCloseTimeout field's value.

func (s *WorkflowExecutionStartedEventAttributes) SetTaskStartToCloseTimeout(v string) *WorkflowExecutionStartedEventAttributes {
	s.TaskStartToCloseTimeout = &v
	return s
}

def check_spinning_children(self):
        ''''''
        child_jobs = self.task_master.get_child_work_units(self.worker_id)
        # We will kill off any jobs that are due before "now".  This
        # isn't really now now, but now plus a grace period to make
        # sure spinning jobs don't get retried.
        now = time.time() + self.stop_jobs_early
        for child, wul in child_jobs.iteritems():
            if not isinstance(wul, (list, tuple)):
                # Support old style get_child_work_units which returns
                # single WorkUnit objects instead of list of them.
                wul = [wul]
            if not wul:
                # This worker is idle, but oddly, still present; it should
                # clean up after itself
                continue
            # filter on those actually assigned to the child worker
            wul = filter(lambda wu: wu.worker_id == child, wul)
            # check for any still active not-overdue job
            if any(filter(lambda wu: wu.expires > now, wul)):
                continue
            # So either someone else is doing its work or it's just overdue
            environment = self.task_master.get_heartbeat(child)
            if not environment:
                continue  # derp
            if 'pid' not in environment:
                continue  # derp
            if environment['pid'] not in self.children:
                continue  # derp
            os.kill(environment['pid'], signal.SIGTERM)
            # This will cause the child to die, and do_some_work will
            # reap it; but we'd also like the job to fail if possible
            for wu in wul:
                if wu.data is None:
                    logger.critical('how did wu.data become: %r' % wu.data)
                else:
                    wu.data['traceback'] = 'job expired'
                wu.fail(exc=Exception('job expired'))

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


Question: Marshall the given parameter object.

public void marshall(DescribeNotificationsForBudgetRequest describeNotificationsForBudgetRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(describeNotificationsForBudgetRequest.getAccountId(), ACCOUNTID_BINDING);
            protocolMarshaller.marshall(describeNotificationsForBudgetRequest.getBudgetName(), BUDGETNAME_BINDING);
            protocolMarshaller.marshall(describeNotificationsForBudgetRequest.getMaxResults(), MAXRESULTS_BINDING);
            protocolMarshaller.marshall(describeNotificationsForBudgetRequest.getNextToken(), NEXTTOKEN_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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

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


Question: Parse the available options.

def parse_options(self, prog_name, arguments):
        """"""
        # Don't want to load configuration to just print the version,
        # so we handle --version manually here.
        if '--version' in arguments:
            self.exit_status(self.version, fh=sys.stdout)
        parser = self.create_parser(prog_name)
        options, args = parser.parse_args(arguments)
        return options, args

func hasMountinfoOption(opts string, vals ...string) bool {
	for _, opt := range strings.Split(opts, " ") {
		for _, val := range vals {
			if strings.HasPrefix(opt, val) {
				return true
			}
		}
	}
	return false
}

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


Question:
Dismisses the hovered item when the tree is exited.

        :param      event | <QEvent>

def leaveEvent( self, event ):

        hitem = self.hoveredItem()
        hcol  = self.hoveredColumn()

        if ( hitem != None ):
            self._hoveredItem   = None
            self._hoveredColumn = -1

            rect = self.visualItemRect(hitem)
            rect.setWidth(self.viewport().width())
            self.viewport().update(rect)

        super(XTreeWidget, self).leaveEvent(event)

public function removeChild(string $name): bool
    {
        foreach ($this->children as $key => $child) {
            if ($child->appliesTo($name)) {
                $child->removeParentPath();
                unset($this->children[$key]);
                $this->updateModifications();
                return true;
            }
        }

        return false;
    }

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


Question: // Delete takes name of the group and deletes it. Returns an error if one occurs.

func (c *FakeGroups) Delete(name string, options *v1.DeleteOptions) error {
	_, err := c.Fake.
		Invokes(testing.NewRootDeleteAction(groupsResource, name), &user.Group{})
	return err
}

public function removeNode( $nodePath )
	{
		$pathNodes	= explode( "/", $nodePath );
		$nodeName	= array_pop( $pathNodes );
		$nodePath	= implode( "/", $pathNodes );
		$nodeNumber	= 0;
		$branch		= $this->getNode( $nodePath );
		if( preg_match_all( "@^(.*)\[([0-9]+)\]$@", $nodeName, $matches ) )
		{
			$nodeName	= $matches[1][0];
			$nodeNumber	= $matches[2][0];
		}
		$nodes		=& $branch->getChildren();
		$index		= -1;
		for( $i=0; $i<count( $nodes ); $i++ )
		{
			if( !$nodeName || $nodes[$i]->getNodeName() == $nodeName )
			{
				$index++;
				if( $index != $nodeNumber )
					continue;
				unset( $nodes[$i] );
				return (bool) $this->write();
			}
		}
		throw new InvalidArgumentException( 'Node not found.' );
	}

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


Question:
Replace the spectrum of an existing source with a
        FileFunction.

def _create_filefunction(self, name, spectrum_pars):
        """"""

        spectrum_pars = {} if spectrum_pars is None else spectrum_pars

        if 'loge' in spectrum_pars:
            loge = spectrum_pars.get('loge')
        else:
            ebinsz = (self.log_energies[-1] -
                      self.log_energies[0]) / self.enumbins
            loge = utils.extend_array(self.log_energies, ebinsz, 0.5, 6.5)

        # Get the values
        dnde = np.zeros(len(loge))
        if 'dnde' in spectrum_pars:
            dnde = spectrum_pars.get('dnde')
        else:
            dnde = np.array([self.like[name].spectrum()(pyLike.dArg(10 ** egy))
                             for egy in loge])

        filename = \
            os.path.join(self.workdir,
                         '%s_filespectrum.txt' % (name.lower().replace(' ', '_')))

        # Create file spectrum txt file
        np.savetxt(filename, np.vstack((10**loge, dnde)).T)
        self.like.setSpectrum(name, str('FileFunction'))

        self.roi[name]['Spectrum_Filename'] = filename
        # Update
        for c in self.components:
            src = c.like.logLike.getSource(str(name))
            spectrum = src.spectrum()

            spectrum.getParam(str('Normalization')).setBounds(1E-3, 1E3)

            file_function = pyLike.FileFunction_cast(spectrum)
            file_function.readFunction(str(filename))
            c.roi[name]['Spectrum_Filename'] = filename

func NewAttach(opts ...Opt) Attach {
	streams := &Streams{}
	for _, opt := range opts {
		opt(streams)
	}
	return func(fifos *FIFOSet) (IO, error) {
		if fifos == nil {
			return nil, fmt.Errorf("cannot attach, missing fifos")
		}
		return copyIO(fifos, streams)
	}
}

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


Question: // ContainsGTID implements GTIDSet.

func (set Mysql56GTIDSet) ContainsGTID(gtid GTID) bool {
	gtid56, ok := gtid.(Mysql56GTID)
	if !ok {
		return false
	}

	for _, iv := range set[gtid56.Server] {
		if iv.start > gtid56.Sequence {
			// We assume intervals are sorted, so we can skip the rest.
			return false
		}
		if gtid56.Sequence <= iv.end {
			// Now we know that: start <= Sequence <= end.
			return true
		}
	}
	// Server wasn't in the set, or no interval contained gtid.
	return false
}

public function isGaiaObject($id)
    {
        return $id >= Unit::CLIFF1 && $id <= Unit::CLIFF10
            || $id === Unit::GOLDMINE
            || $id === Unit::STONEMINE
            || $id === Unit::FORAGEBUSH;
    }

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


Question: // GetUsers returns all the users in the targeted environment

func GetUsers() []User {
	var userPagesResponse struct {
		NextURL   *string `json:"next_url"`
		Resources []struct {
			Metadata struct {
				GUID      string    `json:"guid"`
				CreatedAt time.Time `json:"created_at"`
			} `json:"metadata"`
			Entity struct {
				Username string `json:"username"`
			} `json:"entity"`
		} `json:"resources"`
	}

	var allUsers []User
	nextURL := "/v2/users?results-per-page=50"

	for {
		session := CF("curl", nextURL)
		Eventually(session).Should(Exit(0))

		err := json.Unmarshal(session.Out.Contents(), &userPagesResponse)
		Expect(err).NotTo(HaveOccurred())
		for _, resource := range userPagesResponse.Resources {
			allUsers = append(allUsers, User{
				GUID:      resource.Metadata.GUID,
				CreatedAt: resource.Metadata.CreatedAt,
				Username:  resource.Entity.Username,
			})
		}

		if userPagesResponse.NextURL == nil {
			break
		}
		nextURL = *userPagesResponse.NextURL
	}

	return allUsers
}

func loginWithContext(ctx context.Context, st *state, info *Info) error {
	result := make(chan error, 1)
	go func() {
		result <- st.Login(info.Tag, info.Password, info.Nonce, info.Macaroons)
	}()
	select {
	case err := <-result:
		return errors.Trace(err)
	case <-ctx.Done():
		return errors.Annotatef(ctx.Err(), "cannot log in")
	}
}

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


Question:
Assert that the size of two arrays (or `Countable` or `Traversable` objects)
is the same.

@param array|Countable|Traversable $expected
@param string $message
@return $this

public function assertSameSize($expected, $message = '')
    {
        Assert::assertSameSize($expected, $this->getData(), $message);

        return $this;
    }

public static <T, R, C extends Collection<R>, E extends Exception> C map(final T[] a, final int fromIndex, final int toIndex,
            final Try.Function<? super T, ? extends R, E> func, final IntFunction<? extends C> supplier) throws E {
        checkFromToIndex(fromIndex, toIndex, len(a));
        N.checkArgNotNull(func);

        if (N.isNullOrEmpty(a)) {
            return supplier.apply(0);
        }

        final C result = supplier.apply(toIndex - fromIndex);

        for (int i = fromIndex; i < toIndex; i++) {
            result.add(func.apply(a[i]));
        }

        return result;
    }

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


Question:
// GetBlockHash returns the block hash for the given height, or an error if the
// client has been shut down or the hash at the block height doesn't exist or
// is unknown.

func (s *NeutrinoClient) GetBlockHash(height int64) (*chainhash.Hash, error) {
	return s.CS.GetBlockHash(height)
}

def common_header(frame)
      header = []

      unless FRAME_TYPES[frame[:type]]
        fail CompressionError, "Invalid frame type (#{frame[:type]})"
      end

      if frame[:length] > @max_frame_size
        fail CompressionError, "Frame size is too large: #{frame[:length]}"
      end

      if frame[:length] < 0
        fail CompressionError, "Frame size is invalid: #{frame[:length]}"
      end

      if frame[:stream] > MAX_STREAM_ID
        fail CompressionError, "Stream ID (#{frame[:stream]}) is too large"
      end

      if frame[:type] == :window_update && frame[:increment] > MAX_WINDOWINC
        fail CompressionError, "Window increment (#{frame[:increment]}) is too large"
      end

      header << (frame[:length] >> FRAME_LENGTH_HISHIFT)
      header << (frame[:length] & FRAME_LENGTH_LOMASK)
      header << FRAME_TYPES[frame[:type]]
      header << frame[:flags].reduce(0) do |acc, f|
        position = FRAME_FLAGS[frame[:type]][f]
        unless position
          fail CompressionError, "Invalid frame flag (#{f}) for #{frame[:type]}"
        end

        acc | (1 << position)
      end

      header << frame[:stream]
      header.pack(HEADERPACK) # 8+16,8,8,32
    end

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


Question:
Sanitizes the given untrusted CSS style property value (i.e. not an entire object, just a single
value) and returns a value that is safe to use in a browser environment.
@param {?} value
@return {?}

function sanitizeStyle(value) {
    value = String(value).trim(); // Make sure it's actually a string.
    if (!value)
        return '';
    // Single url(...) values are supported, but only for URLs that sanitize cleanly. See above for
    // reasoning behind this.
    var /** @type {?} */ urlMatch = value.match(URL_RE);
    if ((urlMatch && sanitizeUrl(urlMatch[1]) === urlMatch[1]) ||
        value.match(SAFE_STYLE_VALUE) && hasBalancedQuotes(value)) {
        return value; // Safe style values.
    }
    if (__webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__angular_core__["t" /* isDevMode */])()) {
        getDOM().log("WARNING: sanitizing unsafe style value " + value + " (see http://g.co/ng/security#xss).");
    }
    return 'unsafe';
}

def _load_data(self):

        url = self.parent.build_url(self.parent._endpoints.get('format'))
        response = self.parent.session.get(url)
        if not response:
            return False
        data = response.json()

        self._bold = data.get('bold', False)
        self._color = data.get('color', '#000000')  # default black
        self._italic = data.get('italic', False)
        self._name = data.get('name', 'Calibri')  # default Calibri
        self._size = data.get('size', 10)  # default 10
        self._underline = data.get('underline', 'None')

        self._loaded = True
        return True

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


Question: // SetAction sets the Action field's value.

func (s *StackSetOperation) SetAction(v string) *StackSetOperation {
	s.Action = &v
	return s
}

public void addGetFieldIntercept(String owner, String name) {

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

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


Question:
Deserialize the stored information if it was serialized before.

@param string $value The serialized element to deserialize
@param \Cake\Database\Driver $driver Database connection driver
@return mixed

public function toPHP($value, Driver $driver)
    {
        if ($this->_isSerialized($value)) {
            $value = unserialize($value);
        }

        return $value;
    }

public function listCommand($services = [], $table_pattern = '')
    {
        foreach ($services ?: $this->_getDbServices() as $service) {
            /** @var \ManaPHP\DbInterface $db */
            $db = $this->_di->getShared($service);

            $this->console->writeLn(['service: `:service`', 'service' => $service], Console::FC_CYAN);
            foreach ($this->_getTables($service, $table_pattern) as $row => $table) {
                $columns = (array)$db->getMetadata($table)[Db::METADATA_ATTRIBUTES];
                $primaryKey = $db->getMetadata($table)[Db::METADATA_PRIMARY_KEY];
                foreach ($columns as $i => $column) {
                    if (in_array($column, $primaryKey, true)) {
                        $columns[$i] = $this->console->colorize($column, Console::FC_RED);
                    }
                }

                $this->console->writeLn([' :row :table(:columns)',
                    'row' => sprintf('%2d ', $row + 1),
                    'table' => $this->console->colorize($table, Console::FC_GREEN),
                    'columns' => implode(', ', $columns)]);
            }
        }
    }

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


Question:
Check if the node is returning JSX

@param {ASTNode} node The AST node being checked (must be a ReturnStatement).
@returns {Boolean} True if the node is returning JSX, false if not

function (node) {
      let property;
      switch (node.type) {
        case 'ReturnStatement':
          property = 'argument';
          break;
        case 'ArrowFunctionExpression':
          property = 'body';
          break;
        default:
          return false;
      }

      const returnsJSX =
        node[property] &&
        node[property].type === 'JSXElement'
      ;
      const returnsReactCreateElement =
        node[property] &&
        node[property].callee &&
        node[property].callee.property &&
        node[property].callee.property.name === 'createElement'
      ;

      return Boolean(returnsJSX || returnsReactCreateElement);
    }

function walk (router, transform) {
  assert.equal(typeof router, 'function', 'wayfarer.walk: router should be an function')
  assert.equal(typeof transform, 'function', 'wayfarer.walk: transform should be a function')

  var trie = router._trie
  assert.equal(typeof trie, 'object', 'wayfarer.walk: trie should be an object')

  // (str, obj) -> null
  ;(function walk (route, trie) {
    if (trie.cb) {
      trie.cb = transform(route, trie.cb)
    }

    if (trie.nodes) {
      var nodes = trie.nodes
      Object.keys(nodes).forEach(function (key) {
        var node = nodes[key]
        var newRoute = (key === '$$')
          ? route + '/:' + trie.name
          : route + '/' + key
        walk(newRoute, node)
      })
    }
  })('', trie.trie)
}

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


Question: Parse a salt:// URL; return the path and a possible saltenv query.

def parse(url):
    '''

    '''
    if not url.startswith('salt://'):
        return url, None

    # urlparse will split on valid filename chars such as '?' and '&'
    resource = url.split('salt://', 1)[-1]

    if '?env=' in resource:
        # "env" is not supported; Use "saltenv".
        path, saltenv = resource.split('?env=', 1)[0], None
    elif '?saltenv=' in resource:
        path, saltenv = resource.split('?saltenv=', 1)
    else:
        path, saltenv = resource, None

    if salt.utils.platform.is_windows():
        path = salt.utils.path.sanitize_win_path(path)

    return path, saltenv

public void marshall(GetBasePathMappingsRequest getBasePathMappingsRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(getBasePathMappingsRequest.getDomainName(), DOMAINNAME_BINDING);
            protocolMarshaller.marshall(getBasePathMappingsRequest.getPosition(), POSITION_BINDING);
            protocolMarshaller.marshall(getBasePathMappingsRequest.getLimit(), LIMIT_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
Implementation of the 'release' workflow action.<p>

@param userCms the current user's CMS context
@param resources the resources which should be released

@return the workflow response for this action

@throws CmsException if something goes wrong

protected CmsWorkflowResponse actionRelease(CmsObject userCms, List<CmsResource> resources) throws CmsException {

        checkNewParentsInList(userCms, resources);
        String projectName = generateProjectName(userCms);
        String projectDescription = generateProjectDescription(userCms);
        CmsObject offlineAdminCms = OpenCms.initCmsObject(m_adminCms);
        offlineAdminCms.getRequestContext().setCurrentProject(userCms.getRequestContext().getCurrentProject());
        String managerGroup = getWorkflowProjectManagerGroup();
        String userGroup = getWorkflowProjectUserGroup();
        CmsProject workflowProject = m_adminCms.createProject(
            projectName,
            projectDescription,
            userGroup,
            managerGroup,
            CmsProject.PROJECT_TYPE_WORKFLOW);
        CmsObject newProjectCms = OpenCms.initCmsObject(offlineAdminCms);
        newProjectCms.getRequestContext().setCurrentProject(workflowProject);
        newProjectCms.getRequestContext().setSiteRoot("");
        newProjectCms.copyResourceToProject("/");
        CmsUser admin = offlineAdminCms.getRequestContext().getCurrentUser();
        clearLocks(userCms.getRequestContext().getCurrentProject(), resources);
        for (CmsResource resource : resources) {
            CmsLock lock = offlineAdminCms.getLock(resource);
            if (lock.isUnlocked()) {
                offlineAdminCms.lockResource(resource);
            } else if (!lock.isOwnedBy(admin)) {
                offlineAdminCms.changeLock(resource);
            }
            offlineAdminCms.writeProjectLastModified(resource, workflowProject);
            offlineAdminCms.unlockResource(resource);
        }
        for (CmsUser user : getNotificationMailRecipients()) {
            sendNotification(userCms, user, workflowProject, resources);
        }
        return new CmsWorkflowResponse(
            true,
            "",
            new ArrayList<CmsPublishResource>(),
            new ArrayList<CmsWorkflowAction>(),
            workflowProject.getUuid());
    }

public void marshall(FailedWorkspaceChangeRequest failedWorkspaceChangeRequest, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(failedWorkspaceChangeRequest.getWorkspaceId(), WORKSPACEID_BINDING);
            protocolMarshaller.marshall(failedWorkspaceChangeRequest.getErrorCode(), ERRORCODE_BINDING);
            protocolMarshaller.marshall(failedWorkspaceChangeRequest.getErrorMessage(), ERRORMESSAGE_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question:
@param PageDocumentDescriptor $descriptor

@return null|PageDocument

public function build(PageDocumentDescriptor $descriptor)
    {
        if (IndexibleVoterInterface::VOTE_DENY === $this->indexibleVoter->isIndexible($descriptor)) {
            return null;
        }

        $document = $this->createDocument();

        $this->mapper->mapDocument($document, $descriptor);

        $event = new MapDocumentEvent($document, $descriptor);
        $this->dispatcher->dispatch(IndexerPageEvents::MAP_DOCUMENT, $event);

        return $document;
    }

def write_layout(layout = nil, type = nil) # :nodoc:
      tag = 'c:layout'

      if layout
        @writer.tag_elements(tag)  { write_manual_layout(layout, type) }
      else
        @writer.empty_tag(tag)
      end
    end

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


Question: Get an artist name and song title from a string.

function getSongArtistTitle (str, options, plugins) {
  if (options) {
    if (options.defaultArtist) {
      plugins.push(fallBackToArtist(options.defaultArtist))
    }
    if (options.defaultTitle) {
      plugins.push(fallBackToTitle(options.defaultTitle))
    }
  }

  var plugin = reducePlugins(plugins)

  checkPlugin(plugin)

  var split = plugin.split(plugin.before(str))
  if (!split) return

  return plugin.after(split)
}

public function getLicenseByIdentifier($identifier)
    {
        if (!isset($this->licenses[$identifier])) {
            return;
        }

        $license = $this->licenses[$identifier];

        // add URL for the license text (it's not included in the json)
        $license[2] = 'http://spdx.org/licenses/' . $identifier . '#licenseText';

        return $license;
    }

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


Question: End-to-end renew of access keys for a specific profile in local awscli config

def main(operation, profile, auto, debug, user_name=''):

    if user_name:
        logger.info('user_name parameter given (%s) as surrogate' % user_name)
    try:
        if operation in VALID_INSTALL:
            print(operation)
        elif operation == 'list':
            print(operation)
            return True
        elif not operation:
            msg_accent = (Colors.BOLD + 'list' + Colors.RESET + ' | ' + Colors.BOLD + 'up' + Colors.RESET)
            msg = """You must provide a valid OPERATION for --operation parameter:

                    --operation { """ + msg_accent + """ }
            """
            stdout_message(msg)
            logger.warning('%s: No valid operation provided. Exit' % (inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
        else:
            msg = 'Unknown operation. Exit'
            stdout_message(msg)
            logger.warning('%s: %s' % (msg, inspect.stack()[0][3]))
            sys.exit(exit_codes['E_MISC']['Code'])
    except KeyError as e:
        logger.critical(
            '%s: Cannot find Key %s' %
            (inspect.stack()[0][3], str(e)))
        return False
    except OSError as e:
        logger.critical(
            '%s: problem writing to file %s. Error %s' %
            (inspect.stack()[0][3], output_file, str(e)))
        return False
    except Exception as e:
        logger.critical(
            '%s: Unknown error. Error %s' %
            (inspect.stack()[0][3], str(e)))
        raise e

func (client *Client) UpdateOrganizationManager(guid string, uaaID string) (Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.PutOrganizationManagerRequest,
		URIParams:   Params{"organization_guid": guid, "manager_guid": uaaID},
	})
	if err != nil {
		return nil, err
	}

	response := cloudcontroller.Response{}
	err = client.connection.Make(request, &response)

	return response.Warnings, err
}

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


Question: // Implements the net.Conn SetReadDeadline method

func (c *throttledConn) SetReadDeadline(t time.Time) error {
	return c.originalConn.SetReadDeadline(t)
}

def poll(self, timeout):

        timeout = float(timeout)
        end_time = time.time() + timeout
        while True:
            # Keep reading until data is received or timeout
            incoming = self.stream.read(self._max_read)
            if incoming:
                return incoming
            if (end_time - time.time()) < 0:
                raise ExpectTimeout()
            time.sleep(self._poll_period)

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


Question:
// regionSpec returns a suitable environs.CloudRegionSpec for use in
// regionInheritedConfig.

func (st *State) regionSpec() (*environs.CloudRegionSpec, error) {
	model, err := st.Model()
	if err != nil {
		return nil, errors.Trace(err)
	}
	rspec := &environs.CloudRegionSpec{
		Cloud:  model.Cloud(),
		Region: model.CloudRegion(),
	}
	return rspec, nil
}

private static void setupStormCode(Map conf, String topologyId, String topologyRoot, Set<String> activeKeys)
            throws Exception {
        Map<String, String> blobKeysToLocation = getBlobKeysToLocation(topologyRoot, topologyId);
        for (Map.Entry<String, String> entry : blobKeysToLocation.entrySet()) {
            String key = entry.getKey();
            String location = entry.getValue();
            if (!activeKeys.contains(key)) {
                blobStore.createBlob(key, new FileInputStream(location), new SettableBlobMeta());
                if (isLocalBlobStore) {
                    int versionInfo = BlobStoreUtils.getVersionForKey(key, nimbusInfo, conf);
                    clusterState.setup_blobstore(key, nimbusInfo, versionInfo);
                }
            }
        }

        System.out.println("Successfully create blobstore for topology " + topologyId);
    }

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


Question:
Renders an HTML attribute from an associative array

@param   array $attributes Associative array of attributes

@return  string The HTML attribute string

@since   2.1

protected function renderAttributes($attributes)
    {
        if (count((array) $attributes) == 0) {
            return '';
        }

        $return = [];

        foreach ($attributes as $key => $value) {
            $return[] = $key . '="' . $value . '"';
        }

        return ' ' . implode(' ', $return);
    }

def provide_attr(attr)
      list_item_attr_value = list_item.public_send(attr)

      # Provide user supplied attr
      return list_item_attr_value if list_item_attr_value.present?

      # Provide object supplied attr
      return object_data[attr] if object_available?

      # Provide error - Object is linked but has been deleted
      return 'Object Unavailable' if list_item.object? && !object_available?

      # Provide empty string - no attr supplied and no object linked
      ''
    end

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


Question: InternalXbase.g:347:1: ruleXOrExpression returns [EObject current=null] : (this_XAndExpression_0= ruleXAndExpression ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )* ) ;

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

        EObject this_XAndExpression_0 = null;

        EObject lv_rightOperand_3_0 = null;

        	enterRule();

        try {
            // InternalXbase.g:353:2: ( (this_XAndExpression_0= ruleXAndExpression ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )* ) )
            // InternalXbase.g:354:2: (this_XAndExpression_0= ruleXAndExpression ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )* )
            {
            // InternalXbase.g:354:2: (this_XAndExpression_0= ruleXAndExpression ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )* )
            // InternalXbase.g:355:3: this_XAndExpression_0= ruleXAndExpression ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )*
            {
            if ( state.backtracking==0 ) {

              			newCompositeNode(grammarAccess.getXOrExpressionAccess().getXAndExpressionParserRuleCall_0());

            }
            pushFollow(FOLLOW_9);
            this_XAndExpression_0=ruleXAndExpression();

            state._fsp--;
            if (state.failed) return current;
            if ( state.backtracking==0 ) {

              			current = this_XAndExpression_0;
              			afterParserOrEnumRuleCall();

            }
            // InternalXbase.g:363:3: ( ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) ) )*
            loop5:
            do {
                int alt5=2;
                int LA5_0 = input.LA(1);

                if ( (LA5_0==22) ) {
                    int LA5_2 = input.LA(2);

                    if ( (synpred2_InternalXbase()) ) {
                        alt5=1;
                    }

                }

                switch (alt5) {
            	case 1 :
            	    // InternalXbase.g:364:4: ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) ) ( (lv_rightOperand_3_0= ruleXAndExpression ) )
            	    {
            	    // InternalXbase.g:364:4: ( ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) ) )
            	    // InternalXbase.g:365:5: ( ( () ( ( ruleOpOr ) ) ) )=> ( () ( ( ruleOpOr ) ) )
            	    {
            	    // InternalXbase.g:375:5: ( () ( ( ruleOpOr ) ) )
            	    // InternalXbase.g:376:6: () ( ( ruleOpOr ) )
            	    {
            	    // InternalXbase.g:376:6: ()
            	    // InternalXbase.g:377:7:
            	    {
            	    if ( state.backtracking==0 ) {

            	      							current = forceCreateModelElementAndSet(
            	      								grammarAccess.getXOrExpressionAccess().getXBinaryOperationLeftOperandAction_1_0_0_0(),
            	      								current);

            	    }

            	    }

            	    // InternalXbase.g:383:6: ( ( ruleOpOr ) )
            	    // InternalXbase.g:384:7: ( ruleOpOr )
            	    {
            	    // InternalXbase.g:384:7: ( ruleOpOr )
            	    // InternalXbase.g:385:8: ruleOpOr
            	    {
            	    if ( state.backtracking==0 ) {

            	      								if (current==null) {
            	      									current = createModelElement(grammarAccess.getXOrExpressionRule());
            	      								}

            	    }
            	    if ( state.backtracking==0 ) {

            	      								newCompositeNode(grammarAccess.getXOrExpressionAccess().getFeatureJvmIdentifiableElementCrossReference_1_0_0_1_0());

            	    }
            	    pushFollow(FOLLOW_4);
            	    ruleOpOr();

            	    state._fsp--;
            	    if (state.failed) return current;
            	    if ( state.backtracking==0 ) {

            	      								afterParserOrEnumRuleCall();

            	    }

            	    }

            	    }

            	    }

            	    }

            	    // InternalXbase.g:401:4: ( (lv_rightOperand_3_0= ruleXAndExpression ) )
            	    // InternalXbase.g:402:5: (lv_rightOperand_3_0= ruleXAndExpression )
            	    {
            	    // InternalXbase.g:402:5: (lv_rightOperand_3_0= ruleXAndExpression )
            	    // InternalXbase.g:403:6: lv_rightOperand_3_0= ruleXAndExpression
            	    {
            	    if ( state.backtracking==0 ) {

            	      						newCompositeNode(grammarAccess.getXOrExpressionAccess().getRightOperandXAndExpressionParserRuleCall_1_1_0());

            	    }
            	    pushFollow(FOLLOW_9);
            	    lv_rightOperand_3_0=ruleXAndExpression();

            	    state._fsp--;
            	    if (state.failed) return current;
            	    if ( state.backtracking==0 ) {

            	      						if (current==null) {
            	      							current = createModelElementForParent(grammarAccess.getXOrExpressionRule());
            	      						}
            	      						set(
            	      							current,
            	      							"rightOperand",
            	      							lv_rightOperand_3_0,
            	      							"org.eclipse.xtext.xbase.Xbase.XAndExpression");
            	      						afterParserOrEnumRuleCall();

            	    }

            	    }

            	    }

            	    }
            	    break;

            	default :
            	    break loop5;
                }
            } while (true);

            }

            }

            if ( state.backtracking==0 ) {

              	leaveRule();

            }
        }

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

private function bitwise(string $operator, string $a, string $b) : string
    {
        $this->init($a, $b, $aDig, $bDig, $aNeg, $bNeg);

        $aBin = $this->toBinary($aDig);
        $bBin = $this->toBinary($bDig);

        $aLen = \strlen($aBin);
        $bLen = \strlen($bBin);

        if ($aLen > $bLen) {
            $bBin = \str_repeat("\x00", $aLen - $bLen) . $bBin;
        } elseif ($bLen > $aLen) {
            $aBin = \str_repeat("\x00", $bLen - $aLen) . $aBin;
        }

        if ($aNeg) {
            $aBin = $this->twosComplement($aBin);
        }
        if ($bNeg) {
            $bBin = $this->twosComplement($bBin);
        }

        switch ($operator) {
            case 'and':
                $value = $aBin & $bBin;
                $negative = ($aNeg and $bNeg);
                break;

            case 'or':
                $value = $aBin | $bBin;
                $negative = ($aNeg or $bNeg);
                break;

            case 'xor':
                $value = $aBin ^ $bBin;
                $negative = ($aNeg xor $bNeg);
                break;

            // @codeCoverageIgnoreStart
            default:
                throw new \InvalidArgumentException('Invalid bitwise operator.');
            // @codeCoverageIgnoreEnd
        }

        if ($negative) {
            $value = $this->twosComplement($value);
        }

        $result = $this->toDecimal($value);

        return $negative ? $this->neg($result) : $result;
    }

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


Question:
\
        Returns the language is by the article or
        the configuration language

def get_language(self):

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

protected function checkBehat() {
    $this->checkLocalConfig();
    if ($this->behatLocalYmlExists()) {
      $behatDefaultLocalConfig = $this->getInspector()->getLocalBehatConfig()->export();
      $this->checkDrupalVm($behatDefaultLocalConfig);
      $this->checkBaseUrl($behatDefaultLocalConfig);
    }
  }

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


boolean pred(final WorkItem w) {
	if (w.dev == PollThread.dev_to_del) {
	    if (w.type == PollThread.type_to_del) {
		return w.name.equals(PollThread.name_to_del);
	    } else {
		return false;
	    }
	} else {
	    return false;
	}
    }

def text message
      @suggested_w = @width || (FFI::NCurses.COLS * 0.80).floor
      @suggested_h = @height || (FFI::NCurses.LINES * 0.80).floor

      message_col = 3
      r = 2
      display_length = @suggested_w-4
      display_length -= message_col
      clr = @color || :white
      bgclr = @bgcolor || :black

      if message.is_a? Array
        l = longest_in_list message
        if l > @suggested_w
          if l < FFI::NCurses.COLS
            #@suggested_w = l
            @suggested_w = FFI::NCurses.COLS-2
          else
            @suggested_w = FFI::NCurses.COLS-2
          end
          display_length = @suggested_w-6
        end
        # reduce width and height if you can based on array contents
      else
        message = wrap_text(message, display_length).split("\n")
      end
      # now that we have moved to textpad that +8 was causing black lines to remain after the text
      message_height = message.size #+ 8
      # reduce if possible if its not required.
      #
      r1 = (FFI::NCurses.LINES-@suggested_h)/2
      r1 = r1.floor
      w = @suggested_w
      c1 = (FFI::NCurses.COLS-w)/2
      c1 = c1.floor
      @suggested_row = r1
      @suggested_col = c1
      brow = @button_row || @suggested_h-4
      available_ht = brow - r + 1
      message_height = [message_height, available_ht].min
      # replaced 2014-04-14 - 23:51
      message_label = Canis::TextPad.new @form, {:name=>"message_label", :text => message,
        :row => r, :col => message_col, :width => display_length, :suppress_borders => true,
        :height => message_height, :bgcolor => bgclr , :color => clr}
      #message_label.set_content message
      yield message_label if block_given?

    end

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


Question: postorder adding scan nodes

public void getScanNodeList_recurse(ArrayList<AbstractScanPlanNode> collected,
            HashSet<AbstractPlanNode> visited) {
        if (visited.contains(this)) {
            assert(false): "do not expect loops in plangraph.";
            return;
        }
        visited.add(this);
        for (AbstractPlanNode n : m_children) {
            n.getScanNodeList_recurse(collected, visited);
        }

        for (AbstractPlanNode node : m_inlineNodes.values()) {
            node.getScanNodeList_recurse(collected, visited);
        }
    }

public function setAvailablePostage($country, $code)
    {
        $postage_areas = new ShippingCalculator($code, $country);

        $postage_areas
            ->setCost($this->SubTotalCost)
            ->setWeight($this->TotalWeight)
            ->setItems($this->TotalItems);

        $postage_areas = $postage_areas->getPostageAreas();

        Session::set("Checkout.AvailablePostage", $postage_areas);

        return $this;
    }

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


Question:
/*
Reify a Blueprint as a Row. Optionally use an array
of associated objects to set fk columns.

@param array $associated  [table name] => [Row]

public function create($overrides = array(), $associated = array()) {
        $built = $this->build($overrides, $associated);

        // process any many-to-many associations
        $many_to_many = array();
        foreach($associated as $name => $row) {
            $association = $this->_associations[$name];
            if($association instanceof Association\ManyToMany) {
                if(!is_array($row)) {
                    $row = array($row);
                }
                $many_to_many[$name] = array($row, $association);
            }
        }

        $built->save();

        if($many_to_many) {
            $this->_associateManyToMany($built, $many_to_many);
        }

        return $built;
    }

def adapt_step_table!(parsed_step_table)
      # Saving off the original data
      parsed_step_table['cuke_modeler_parsing_data'] = Marshal::load(Marshal.dump(parsed_step_table))

      # Removing parsed data for child elements in order to avoid duplicating data
      parsed_step_table['cuke_modeler_parsing_data'][:rows] = nil

      parsed_step_table['rows'] = []
      parsed_step_table[:rows].each do |row|
        adapt_table_row!(row)
      end
      parsed_step_table['rows'].concat(parsed_step_table.delete(:rows))
      parsed_step_table['line'] = parsed_step_table.delete(:location)[:line]
    end

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


Question:
Get the public key corresponding to a fingerprint.

@param string $fingerprint
@return string
@throws \Crypt_GPG_Exception
@throws \Crypt_GPG_FileException
@throws GPGMailerException
@throws \PEAR_Exception

public function export(string $fingerprint): string
    {
        $gnupg = new \Crypt_GPG($this->options);
        try {
            $gnupg->addEncryptKey($fingerprint);
            return $gnupg->exportPublicKey($fingerprint, true);
        } catch (\PEAR_Exception $ex) {
            throw new GPGMailerException(
                'Could not export fingerprint "' . $fingerprint . '": ' .
                    $ex->getMessage(),
                $ex->getCode(),
                $ex
            );
        }
    }

def retrieve_and_parse_diaspora_webfinger(handle):

    try:
        host = handle.split("@")[1]
    except AttributeError:
        logger.warning("retrieve_and_parse_diaspora_webfinger: invalid handle given: %s", handle)
        return None
    document, code, exception = fetch_document(
        host=host, path="/.well-known/webfinger?resource=acct:%s" % quote(handle),
    )
    if document:
        return parse_diaspora_webfinger(document)
    hostmeta = retrieve_diaspora_host_meta(host)
    if not hostmeta:
        return None
    url = hostmeta.find_link(rels="lrdd").template.replace("{uri}", quote(handle))
    document, code, exception = fetch_document(url)
    if exception:
        return None
    return parse_diaspora_webfinger(document)

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


Question:
Publishes the {@code event} to the {@link WanReplicationPublisher} configured for this map.

@param mapName the map name
@param event   the event

protected void publishWanEvent(String mapName, ReplicationEventObject event) {
        MapContainer mapContainer = mapServiceContext.getMapContainer(mapName);
        WanReplicationPublisher wanReplicationPublisher = mapContainer.getWanReplicationPublisher();
        if (isOwnedPartition(event.getKey())) {
            wanReplicationPublisher.publishReplicationEvent(SERVICE_NAME, event);
        } else {
            wanReplicationPublisher.publishReplicationEventBackup(SERVICE_NAME, event);
        }
    }

protected function execute(InputInterface $input, OutputInterface $output)
    {
        $this->input = $input;
        $this->output = $output;
        $configurationPath = $input->getOption('configurationPath');
        $deploymentName = $input->getArgument('deploymentName');
        $deployment = $this->factory->getDeployment($deploymentName, $configurationPath);
        $workflow = $deployment->getWorkflow();

        if (! $deployment instanceof FailedDeployment) {
            $output->writeln('<success>Deployment ' . $deployment->getName() . '</success>');
            $output->writeln('');
            $output->writeln('Workflow: <success>' . $workflow->getName() . '</success>');

            if ($workflow instanceof SimpleWorkflow) {
                $value = $workflow->isEnableRollback() ? 'true' : 'false';
                $output->writeln('    <comment>Rollback enabled:</comment> <info>' . $value . '</info>');
            }

            $output->writeln('');

            $this->printNodes($deployment->getNodes());

            $this->printApplications($deployment->getApplications(), $deployment->getWorkflow());
        }
    }

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


Question: Creates the mode and arm state text.

def createStateText(self):
        ''''''
        self.modeText = self.axes.text(self.leftPos+(self.vertSize/10.0),0.97,'UNKNOWN',color='grey',size=1.5*self.fontSize,ha='left',va='top')
        self.modeText.set_path_effects([PathEffects.withStroke(linewidth=self.fontSize/10.0,foreground='black')])

function setModeScriptText($script, $multicall = false)
    {
        if (!is_string($script)) {
            throw new InvalidArgumentException('script = ' . print_r($script, true));
        }

        return $this->execute(ucfirst(__FUNCTION__), array($script), $multicall);
    }

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


Question:
TODO: This function is not yet implemented. It acts as a placeholder until it is
extracted and implemented in its own repository, ObjectDocument.

public function loadJSON(string $jsonString):void {
		$json = json_decode($jsonString);

		foreach($json as $key => $value) {
			$node = $this->createElement($key, $value);
			$this->appendChild($node);
		}
	}

def CreateHunt(hunt_obj):
  """"""
  data_store.REL_DB.WriteHuntObject(hunt_obj)

  if hunt_obj.HasField("output_plugins"):
    output_plugins_states = flow.GetOutputPluginStates(
        hunt_obj.output_plugins,
        source="hunts/%s" % hunt_obj.hunt_id,
        token=access_control.ACLToken(username=hunt_obj.creator))
    data_store.REL_DB.WriteHuntOutputPluginsStates(hunt_obj.hunt_id,
                                                   output_plugins_states)

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


Question:
Create a wily cache.

    :param config: The configuration
    :type  config: :class:`wily.config.WilyConfig`

    :return: The path to the cache
    :rtype: ``str``

def create(config):

    if exists(config):
        logger.debug("Wily cache exists, skipping")
        return config.cache_path
    logger.debug(f"Creating wily cache {config.cache_path}")
    pathlib.Path(config.cache_path).mkdir(parents=True, exist_ok=True)
    create_index(config)
    return config.cache_path

private function load_command_config_file($file, $prefix) {

    $yaml = $this->sm->get('pegase.component.yaml.spyc');
    $data = $yaml->parse($file);
    $mm = $this->sm->get('pegase.core.module_manager');

    foreach($data as $command_name => $command) {

      if(key_exists('prefix', $command)) {
        $prefix_to_add = $command['prefix'];
      }
      else
        $prefix_to_add = $command_name;

      if(key_exists('class', $command) && key_exists('method', $command)) {

        if(!key_exists('parameters', $command))
          $command['parameters'] = null;

        if(!key_exists('options', $command))
          $command['options'] = null;

        $this->add_command(array(
          'name' => $prefix . $prefix_to_add,
          'class' => $command['class'],
          'method' => $command['method'],
          'parameters' => $command['parameters'],
          'options' => $command['options']
        ));
      }
      else if(key_exists('import', $command)) {
        $this->load_command_config_file(
          $mm->get_file($command['import']['module'], $command['import']['file']),
          $prefix . $prefix_to_add);
      }
    }
  }

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


Question: journey recommendations from an origin to a destination station

def journey_options(origin:      str,
                    destination: str,
                    via:         t.Optional[str]=None,
                    before:      t.Optional[int]=None,
                    after:       t.Optional[int]=None,
                    time:        t.Optional[datetime]=None,
                    hsl:         t.Optional[bool]=None,
                    year_card:   t.Optional[bool]=None) -> (
                        snug.Query[t.List[Journey]]):
    """"""
    return snug.GET('treinplanner', params={
        'fromStation':     origin,
        'toStation':       destination,
        'viaStation':      via,
        'previousAdvices': before,
        'nextAdvices':     after,
        'dateTime':        time,
        'hslAllowed':      hsl,
        'yearCard':        year_card,
    })

func (s *RemoteApplication) Endpoint(relationName string) (Endpoint, error) {
	eps, err := s.Endpoints()
	if err != nil {
		return Endpoint{}, err
	}
	for _, ep := range eps {
		if ep.Name == relationName {
			return ep, nil
		}
	}
	return Endpoint{}, fmt.Errorf("remote application %q has no %q relation", s, relationName)
}

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


Question:
// CompleteWithOptions updates the store with the provided options and
// defaults common fields.

func (e *Store) CompleteWithOptions(options *generic.StoreOptions) error {
	if e.DefaultQualifiedResource.Empty() {
		return fmt.Errorf("store %#v must have a non-empty qualified resource", e)
	}
	if e.NewFunc == nil {
		return fmt.Errorf("store for %s must have NewFunc set", e.DefaultQualifiedResource.String())
	}
	if e.NewListFunc == nil {
		return fmt.Errorf("store for %s must have NewListFunc set", e.DefaultQualifiedResource.String())
	}
	if (e.KeyRootFunc == nil) != (e.KeyFunc == nil) {
		return fmt.Errorf("store for %s must set both KeyRootFunc and KeyFunc or neither", e.DefaultQualifiedResource.String())
	}

	var isNamespaced bool
	switch {
	case e.CreateStrategy != nil:
		isNamespaced = e.CreateStrategy.NamespaceScoped()
	case e.UpdateStrategy != nil:
		isNamespaced = e.UpdateStrategy.NamespaceScoped()
	default:
		return fmt.Errorf("store for %s must have CreateStrategy or UpdateStrategy set", e.DefaultQualifiedResource.String())
	}

	if e.DeleteStrategy == nil {
		return fmt.Errorf("store for %s must have DeleteStrategy set", e.DefaultQualifiedResource.String())
	}

	if options.RESTOptions == nil {
		return fmt.Errorf("options for %s must have RESTOptions set", e.DefaultQualifiedResource.String())
	}

	attrFunc := options.AttrFunc
	if attrFunc == nil {
		if isNamespaced {
			attrFunc = storage.DefaultNamespaceScopedAttr
		} else {
			attrFunc = storage.DefaultClusterScopedAttr
		}
	}
	if e.PredicateFunc == nil {
		e.PredicateFunc = func(label labels.Selector, field fields.Selector) storage.SelectionPredicate {
			return storage.SelectionPredicate{
				Label:    label,
				Field:    field,
				GetAttrs: attrFunc,
			}
		}
	}

	opts, err := options.RESTOptions.GetRESTOptions(e.DefaultQualifiedResource)
	if err != nil {
		return err
	}

	// ResourcePrefix must come from the underlying factory
	prefix := opts.ResourcePrefix
	if !strings.HasPrefix(prefix, "/") {
		prefix = "/" + prefix
	}
	if prefix == "/" {
		return fmt.Errorf("store for %s has an invalid prefix %q", e.DefaultQualifiedResource.String(), opts.ResourcePrefix)
	}

	// Set the default behavior for storage key generation
	if e.KeyRootFunc == nil && e.KeyFunc == nil {
		if isNamespaced {
			e.KeyRootFunc = func(ctx context.Context) string {
				return NamespaceKeyRootFunc(ctx, prefix)
			}
			e.KeyFunc = func(ctx context.Context, name string) (string, error) {
				return NamespaceKeyFunc(ctx, prefix, name)
			}
		} else {
			e.KeyRootFunc = func(ctx context.Context) string {
				return prefix
			}
			e.KeyFunc = func(ctx context.Context, name string) (string, error) {
				return NoNamespaceKeyFunc(ctx, prefix, name)
			}
		}
	}

	// We adapt the store's keyFunc so that we can use it with the StorageDecorator
	// without making any assumptions about where objects are stored in etcd
	keyFunc := func(obj runtime.Object) (string, error) {
		accessor, err := meta.Accessor(obj)
		if err != nil {
			return "", err
		}

		if isNamespaced {
			return e.KeyFunc(genericapirequest.WithNamespace(genericapirequest.NewContext(), accessor.GetNamespace()), accessor.GetName())
		}

		return e.KeyFunc(genericapirequest.NewContext(), accessor.GetName())
	}

	triggerFunc := options.TriggerFunc
	if triggerFunc == nil {
		triggerFunc = storage.NoTriggerPublisher
	}

	if e.DeleteCollectionWorkers == 0 {
		e.DeleteCollectionWorkers = opts.DeleteCollectionWorkers
	}

	e.EnableGarbageCollection = opts.EnableGarbageCollection

	if e.ObjectNameFunc == nil {
		e.ObjectNameFunc = func(obj runtime.Object) (string, error) {
			accessor, err := meta.Accessor(obj)
			if err != nil {
				return "", err
			}
			return accessor.GetName(), nil
		}
	}

	if e.Storage.Storage == nil {
		e.Storage.Codec = opts.StorageConfig.Codec
		e.Storage.Storage, e.DestroyFunc = opts.Decorator(
			opts.StorageConfig,
			prefix,
			keyFunc,
			e.NewFunc,
			e.NewListFunc,
			attrFunc,
			triggerFunc,
		)
		e.StorageVersioner = opts.StorageConfig.EncodeVersioner

		if opts.CountMetricPollPeriod > 0 {
			stopFunc := e.startObservingCount(opts.CountMetricPollPeriod)
			previousDestroy := e.DestroyFunc
			e.DestroyFunc = func() {
				stopFunc()
				if previousDestroy != nil {
					previousDestroy()
				}
			}
		}
	}

	return nil
}

func (v replaceStrategy) doReplace(e apply.Element) (apply.Result, error) {

	if result, done := v.doAddOrDelete(e); done {
		return result, nil
	}
	if err := v.doConflictDetect(e); err != nil {
		return apply.Result{}, err
	}
	if e.HasLocal() {
		// Specified locally, set the local value
		return apply.Result{Operation: apply.SET, MergedResult: e.GetLocal()}, nil
	} else if e.HasRemote() {
		// Not specified locally, set the remote value
		return apply.Result{Operation: apply.SET, MergedResult: e.GetRemote()}, nil
	} else {
		// Only specified in the recorded, drop the field.
		return apply.Result{Operation: apply.DROP, MergedResult: e.GetRemote()}, nil
	}
}

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


Question: // Get returns information about current kernel activity.

func (prof *Profiler) Get() (stats *CPUStats, err error) {
	err = prof.Reset()
	if err != nil {
		return nil, err
	}
	var (
		i, j, pos, fieldNum int
		n                   uint64
		v                   byte
		stop                bool
	)

	stats = &CPUStats{Timestamp: time.Now().UTC().UnixNano(), ClkTck: prof.ClkTck, CPU: make([]CPU, 0, 2)}

	// read each line until eof
	for {
		prof.Line, err = prof.ReadSlice('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, &joe.ReadError{Err: err}
		}
		prof.Val = prof.Val[:0]
		// Get everything up to the first space, this is the key.  Not all keys are processed.
		for i, v = range prof.Line {
			if v == 0x20 {
				prof.Val = prof.Line[:i]
				pos = i + 1
				break
			}
		}
		// skip the intr line
		if prof.Val[0] == 'i' {
			continue
		}
		if prof.Val[0] == 'c' {
			if prof.Val[1] == 'p' { // process CPU
				cpu := CPU{ID: string(prof.Val[:])}
				j = 0
				// skip over any remaining spaces
				for i, v = range prof.Line[pos:] {
					if v != 0x20 {
						break
					}
					j++
				}
				fieldNum = 0
				pos, j = j+pos, j+pos
				// space is the field separator
				for i, v = range prof.Line[pos:] {
					if v == '\n' {
						stop = true
					}
					if v == 0x20 || stop {
						fieldNum++
						n, err = helpers.ParseUint(prof.Line[j : pos+i])
						if err != nil {
							return stats, &joe.ParseError{Info: string(prof.Val[:]), Err: err}
						}
						j = pos + i + 1
						if fieldNum < 6 {
							if fieldNum < 4 {
								if fieldNum == 1 {
									cpu.User = int64(n)
									continue
								}
								if fieldNum == 2 {
									cpu.Nice = int64(n)
									continue
								}
								cpu.System = int64(n) // 3
								continue
							}
							if fieldNum == 4 {
								cpu.Idle = int64(n)
								continue
							}
							cpu.IOWait = int64(n) // 5
							continue
						}
						if fieldNum < 8 {
							if fieldNum == 6 {
								cpu.IRQ = int64(n)
								continue
							}
							cpu.SoftIRQ = int64(n) // 7
							continue
						}
						if fieldNum == 8 {
							cpu.Steal = int64(n)
							continue
						}
						if fieldNum == 9 {
							cpu.Quest = int64(n)
							continue
						}
						cpu.QuestNice = int64(n) // 10
					}
				}
				stats.CPU = append(stats.CPU, cpu)
				stop = false
				continue
			}
			// Otherwise it's ctxt info; rest of the line is the data.
			n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
			if err != nil {
				return stats, &joe.ParseError{Info: string(prof.Val[:]), Err: err}
			}
			stats.Ctxt = int64(n)
			continue
		}
		if prof.Val[0] == 'b' {
			// rest of the line is the data
			n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
			if err != nil {
				return stats, &joe.ParseError{Info: string(prof.Val[:]), Err: err}
			}
			stats.BTime = int64(n)
			continue
		}
		if prof.Val[0] == 'p' && prof.Val[4] == 'e' { // processes info
			// rest of the line is the data
			n, err = helpers.ParseUint(prof.Line[pos : len(prof.Line)-1])
			if err != nil {
				return stats, &joe.ParseError{Info: string(prof.Val[:]), Err: err}
			}
			stats.Processes = int64(n)
			continue
		}
	}
	return stats, nil
}

protected function queryMore()
    {
        $result = $this->client->queryMore($this->queryResult->getQueryLocator());
        $this->setQueryResult($result);
        $this->rewind();
    }

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


Question:
/*
Compiler recovery in case of internal AbortCompilation event

protected void handleInternalException(
        AbortCompilation abortException,
        CompilationUnitDeclaration unit) {

        /* special treatment for SilentAbort: silently cancelling the compilation process */
        if (abortException.isSilent) {
            if (abortException.silentException == null) {
                return;
            }
            throw abortException.silentException;
        }

        /* uncomment following line to see where the abort came from */
        // abortException.printStackTrace();

        // Exception may tell which compilation result it is related, and which problem caused it
        CompilationResult result = abortException.compilationResult;
        if (result == null && unit != null) {
            result = unit.compilationResult; // current unit being processed ?
        }
        // Lookup environment may be in middle of connecting types
        if (result == null && this.lookupEnvironment.unitBeingCompleted != null) {
            result = this.lookupEnvironment.unitBeingCompleted.compilationResult;
        }
        if (result == null) {
            synchronized (this) {
                if (this.unitsToProcess != null && this.totalUnits > 0)
                    result = this.unitsToProcess[this.totalUnits - 1].compilationResult;
            }
        }
        // last unit in beginToCompile ?
        if (result != null && !result.hasBeenAccepted) {
            /* distant problem which could not be reported back there? */
            if (abortException.problem != null) {
                recordDistantProblem: {
                CategorizedProblem distantProblem = abortException.problem;
                CategorizedProblem[] knownProblems = result.problems;
                    for (int i = 0; i < result.problemCount; i++) {
                        if (knownProblems[i] == distantProblem) { // already recorded
                            break recordDistantProblem;
                        }
                    }
                    if (distantProblem instanceof DefaultProblem) { // fixup filename TODO (philippe) should improve API to make this official
                        ((DefaultProblem) distantProblem).setOriginatingFileName(result.getFileName());
                    }
                    result.record(distantProblem, unit, true);
                }
            } else {
                /* distant internal exception which could not be reported back there */
                if (abortException.exception != null) {
                    this.handleInternalException(abortException.exception, null, result);
                    return;
                }
            }
            /* hand back the compilation result */
            if (!result.hasBeenAccepted) {
                this.requestor.acceptResult(result.tagAsAccepted());
            }
        } else {
            abortException.printStackTrace();
        }
    }

private int minLimit(int input, int min) {
        if (input < min) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "Config: " + input + " too small.");
            }
            return min;
        }
        return input;
    }

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


Question:
/*
   |-> WHERE
	   |-> email
		   |-> =
		   |-> foo@bar.com
*/

func whereExecutor(whereDecl *parser.Decl, fromTableName string) ([]Predicate, error) {
	var predicates []Predicate
	var err error
	whereDecl.Stringy(0)

	for i := range whereDecl.Decl {
		var p Predicate
		tableName := fromTableName
		cond := whereDecl.Decl[i]

		// 1 PREDICATE
		if cond.Lexeme == "1" {
			predicates = append(predicates, TruePredicate)
			continue
		}

		if len(cond.Decl) == 0 {
			log.Debug("whereExecutor: HUm hum you must be AND or OR: %v", cond)
			continue
		}

		switch cond.Decl[0].Token {
		case parser.EqualityToken, parser.LeftDipleToken, parser.RightDipleToken, parser.LessOrEqualToken, parser.GreaterOrEqualToken:
			log.Debug("whereExecutor: it's = < > <= >=\n")
			break
		case parser.InToken:
			log.Debug("whereExecutor: it's IN\n")
			break
		case parser.IsToken:
			log.Debug("whereExecutor: it's IS token\n")
			log.Debug("whereExecutor: %+v\n", cond.Decl[0])
			break
		default:
			log.Debug("it's the table name ! -> %s", cond.Decl[0].Lexeme)
			tableName = cond.Decl[0].Lexeme
			cond.Decl = cond.Decl[1:]
			break
		}

		p.LeftValue.lexeme = whereDecl.Decl[i].Lexeme

		// Handle IN keyword
		if cond.Decl[0].Token == parser.InToken {
			err := inExecutor(cond.Decl[0], &p)
			if err != nil {
				return nil, err
			}
			p.LeftValue.table = tableName
			predicates = append(predicates, p)
			continue
		}

		// Handle IS NULL and IS NOT NULL
		if cond.Decl[0].Token == parser.IsToken {
			err := isExecutor(cond.Decl[0], &p)
			if err != nil {
				return nil, err
			}
			p.LeftValue.table = tableName
			predicates = append(predicates, p)
			continue
		}

		if len(cond.Decl) < 2 {
			return nil, fmt.Errorf("Malformed predicate \"%s\"", cond.Lexeme)
		}

		// The first element of the list is then the relation of the attribute
		op := cond.Decl[0]
		val := cond.Decl[1]

		p.Operator, err = NewOperator(op.Token, op.Lexeme)
		if err != nil {
			return nil, err
		}
		p.RightValue.lexeme = val.Lexeme
		p.RightValue.valid = true

		p.LeftValue.table = tableName

		predicates = append(predicates, p)
	}

	if len(predicates) == 0 {
		return nil, fmt.Errorf("No predicates provided")
	}

	return predicates, 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: // SetApplicationName sets the ApplicationName field's value.

func (s *EventDescription) SetApplicationName(v string) *EventDescription {
	s.ApplicationName = &v
	return s
}

func (s *DescribeActivityTypeInput) SetActivityType(v *ActivityType) *DescribeActivityTypeInput {
	s.ActivityType = v
	return s
}

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


Question: // String returns a string representation of receiver that can be used for debugging.

func (node *ContentStatement) String() string {
	return fmt.Sprintf("Content{Value:'%s', Pos:%d}", node.Value, node.Loc.Pos)
}

public void enableReceiveNormalMsg(boolean enable, EnableReceiveNormalMsgHandler handler) {
        HMSAgentLog.i("enableReceiveNormalMsg:enable=" + enable + "  handler=" + StrUtils.objDesc(handler));
        this.enable = enable;
        this.handler = handler;
        connect();
    }

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


Question: // SetKeyframeKey invokes the CSS method. Modifies the keyframe rule key text.

func (d *domainClient) SetKeyframeKey(ctx context.Context, args *SetKeyframeKeyArgs) (reply *SetKeyframeKeyReply, err error) {
	reply = new(SetKeyframeKeyReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "CSS.setKeyframeKey", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "CSS.setKeyframeKey", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "CSS", Op: "SetKeyframeKey", Err: err}
	}
	return
}

def on_palette_name_changed(self, combo):

        palette_name = combo.get_active_text()
        if palette_name not in PALETTES:
            return
        self.settings.styleFont.set_string('palette', PALETTES[palette_name])
        self.settings.styleFont.set_string('palette-name', palette_name)
        self.set_palette_colors(PALETTES[palette_name])
        self.update_demo_palette(PALETTES[palette_name])

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


Question:
Add the `verify` extension to the builder.

@param \Illuminate\Database\Eloquent\Builder $builder
@return void

protected function addVerify(Builder $builder): void
    {
        $builder->macro('verify', function (Builder $builder) {
            $builder->withNotVerified();

            return $builder->update(['is_verified' => 1]);
        });
    }

public function createQuery(Query $query): Query
    {
        $dbQuery = $this->connection->createQueryBuilder()
            ->insert('ngbm_collection_query')
            ->values(
                [
                    'id' => ':id',
                    'status' => ':status',
                    'collection_id' => ':collection_id',
                    'type' => ':type',
                ]
            )
            ->setValue(
                'id',
                $query->id !== null ?
                    (int) $query->id :
                    $this->connectionHelper->getAutoIncrementValue('ngbm_collection_query')
            )
            ->setParameter('status', $query->status, Type::INTEGER)
            ->setParameter('collection_id', $query->collectionId, Type::INTEGER)
            ->setParameter('type', $query->type, Type::STRING);

        $dbQuery->execute();

        $query->id = $query->id ?? (int) $this->connectionHelper->lastInsertId('ngbm_collection_query');

        return $query;
    }

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