Question:
获取全局禁言
@return BaseResponse|GetNoSpeakingBaseResponse
@throws Exception\TIMException

public function getNoSpeaking()
    {
        $request = new GetNoSpeakingRequest($this->identifier);
        $response = new GetNoSpeakingBaseResponse();
        return $this->client->sendRequest($request, $response);
    }

def infer_msg(self, tts, rsp):

        # rsp should be <requests.Response>
        # http://docs.python-requests.org/en/master/api/
        status = rsp.status_code
        reason = rsp.reason

        cause = "Unknown"
        if status == 403:
            cause = "Bad token or upstream API changes"
        elif status == 404 and not tts.lang_check:
            cause = "Unsupported language '%s'" % self.tts.lang
        elif status >= 500:
            cause = "Uptream API error. Try again later."

        return "%i (%s) from TTS API. Probable cause: %s" % (
            status, reason, cause)

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


Question: Compute the length of the shared prefix between two byte sequences.

static int sharedPrefixLength(ByteBuffer a, int aStart, ByteBuffer b, int bStart) {
    int i = 0;
    final int max = Math.min(a.remaining() - aStart, b.remaining() - bStart);
    aStart += a.position();
    bStart += b.position();
    while (i < max && a.get(aStart++) == b.get(bStart++)) {
      i++;
    }
    return i;
  }

def construct_wal_name(sysinfo):

    log_hex, seg_hex = sysinfo["xlogpos"].split("/", 1)
    # seg_hex's topmost 8 bits are filename, low 24 bits are position in
    # file which we are not interested in
    return name_for_tli_log_seg(
        tli=int(sysinfo["timeline"]),
        log=int(log_hex, 16),
        seg=int(seg_hex, 16) >> 24)

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


Question:
Query a geotools source for features using the criterion as a filter.

@param source
@param criterion
@param attributeNames
@param crs
@return
@throws IOException
@throws GeomajasException

protected Query createQuery(String typeName, List<AttributeDescriptor> schema, Criterion criterion,
			int maxFeatures, int startIndex, List<String> attributeNames, String crs) throws IOException {
		CriterionToFilterConverter converter = criterionToFilterFactory.createConverter();
		Filter filter = converter.convert(criterion, schema);
		Query query = null;
		if (attributeNames == null) {
			query = new Query(typeName, filter, maxFeatures > 0 ? maxFeatures : Integer.MAX_VALUE, Query.ALL_NAMES,
					null);
		} else {
			query = new Query(typeName, filter, maxFeatures > 0 ? maxFeatures : Integer.MAX_VALUE,
					attributeNames.toArray(new String[attributeNames.size()]), null);
		}
		if (startIndex > 0) {
			query.setStartIndex(startIndex);
		}
		if (null != crs) {
			try {
				// always use the urn version as otherwise servers disagree on axis order
				if (crs.equalsIgnoreCase("EPSG:4326")) {
					crs = "urn:x-ogc:def:crs:EPSG:4326";
				}
				query.setCoordinateSystem(CRS.decode(crs));
			} catch (NoSuchAuthorityCodeException e) { // assume non-fatal
				log.warn("Problem getting CRS for id " + crs + ": " + e.getMessage());
			} catch (FactoryException e) {
				// assume non-fatal
				log.warn("Problem getting CRS for id " + crs + ": " + e.getMessage());
			}
		}
		return query;
	}

public Observable<ServiceResponse<LuisApp>> exportWithServiceResponseAsync(UUID appId, String versionId) {
        if (this.client.endpoint() == null) {
            throw new IllegalArgumentException("Parameter this.client.endpoint() is required and cannot be null.");
        }
        if (appId == null) {
            throw new IllegalArgumentException("Parameter appId is required and cannot be null.");
        }
        if (versionId == null) {
            throw new IllegalArgumentException("Parameter versionId is required and cannot be null.");
        }
        String parameterizedHost = Joiner.on(", ").join("{Endpoint}", this.client.endpoint());
        return service.export(appId, versionId, this.client.acceptLanguage(), parameterizedHost, this.client.userAgent())
            .flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponse<LuisApp>>>() {
                @Override
                public Observable<ServiceResponse<LuisApp>> call(Response<ResponseBody> response) {
                    try {
                        ServiceResponse<LuisApp> clientResponse = exportDelegate(response);
                        return Observable.just(clientResponse);
                    } catch (Throwable t) {
                        return Observable.error(t);
                    }
                }
            });
    }

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


Question:
Clear a horizontal tab stop.

        :param int how: defines a way the tab stop should be cleared:

            * ``0`` or nothing -- Clears a horizontal tab stop at cursor
              position.
            * ``3`` -- Clears all horizontal tab stops.

def clear_tab_stop(self, how=0):

        if how == 0:
            # Clears a horizontal tab stop at cursor position, if it's
            # present, or silently fails if otherwise.
            self.tabstops.discard(self.cursor.x)
        elif how == 3:
            self.tabstops = set()

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:
Ping Redis Server and return Round-Trip-Time in seconds.

        @return: Round-trip-time in seconds as float.

def ping(self):

        start = time.time()
        self._conn.ping()
        return (time.time() - start)

def hold_absent(name, snapshot, recursive=False):
    '''

    '''
    ret = {'name': name,
           'changes': {},
           'result': True,
           'comment': ''}

    ## log configuration
    log.debug('zfs.hold_absent::%s::config::snapshot = %s',
              name, snapshot)
    log.debug('zfs.hold_absent::%s::config::recursive = %s',
              name, recursive)

    ## check we have a snapshot/tag name
    if not __utils__['zfs.is_snapshot'](snapshot):
        ret['result'] = False
        ret['comment'] = 'invalid snapshot name: {0}'.format(snapshot)
        return ret

    if __utils__['zfs.is_snapshot'](name) or \
       __utils__['zfs.is_bookmark'](name) or \
       name == 'error':
        ret['result'] = False
        ret['comment'] = 'invalid tag name: {0}'.format(name)
        return ret

    ## release hold if required
    holds = __salt__['zfs.holds'](snapshot)
    if name in holds:
        ## NOTE: hold found for snapshot, release it
        if not __opts__['test']:
            mod_res = __salt__['zfs.release'](name, snapshot, **{'recursive': recursive})
        else:
            mod_res = OrderedDict([('released', True)])

        ret['result'] = mod_res['released']
        if ret['result']:
            ret['changes'] = {snapshot: {name: 'released'}}
            ret['comment'] = 'hold {0} released'.format(
                name,
            )
        else:
            ret['comment'] = 'failed to release hold {0}'.format(
                name,
            )
            if 'error' in mod_res:
                ret['comment'] = mod_res['error']
    elif 'error' in holds:
        ## NOTE: we have an error
        ret['result'] = False
        ret['comment'] = holds['error']
    else:
        ## NOTE: no hold found with name for snapshot
        ret['comment'] = 'hold {0} is absent'.format(
            name,
        )

    return ret

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


Question:
Remove all assigned values and reset defaults

@return Response Returns the current object instance

public function clear()
    {
        $this->status = 200;
        $this->reasonPhrase = '';
        $this->headers = [];
        $this->ucHeaders = [];
        $this->cookies = [];
        $this->body = null;
        $this->asgiMap = [];

        return $this;
    }

def _setup_rest_dispatcher(self):

        for _, method in inspect.getmembers(self, inspect.isroutine):
            try:
                config = getattr(method, HTTP_ROUTE_ATTRIBUTE)
            except AttributeError:
                # Not a REST method
                continue

            for route in config["routes"]:
                pattern, arguments = self.__convert_route(route)
                self.__methods_args.setdefault(method, {}).update(arguments)
                for http_verb in config["methods"]:
                    self.__routes.setdefault(http_verb, {})[pattern] = method

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


Question:
Decides which Entry should be indexed.
@access		public
@return		bool

public function accept()
	{
		if( $this->getInnerIterator()->isDot() )
			return FALSE;

		$isDir	= $this->getInnerIterator()->isDir();
		if( !$this->showFiles && !$isDir )
			return FALSE;

		if( $this->stripDotEntries )															//  skip all folders and files starting with a dot
		{
			if( substr( $this->getFilename(), 0, 1 ) == "." )									//  found file or folder is hidden
				return FALSE;

			if( substr( $this->getSubPathname(), 0, 1 ) == "." )								//  inner path is hidden
				return FALSE;

			$subPath	= str_replace( "\\", "/", $this->getSubPathname() );					//  be nice to Windows
			if( preg_match( '/\/\.\w/', $subPath ) )											//  atleast 1 folder in inner path is hidden
				return FALSE;
		}
		return TRUE;
	}

public function addBooleanAccessorOpen(&$script, Column $column)
    {
        $name = self::getBooleanAccessorName($column);
        $visibility = $column->getAccessorVisibility();

        $script .= "
    ".$visibility." function $name(";
        if ($column->isLazyLoad()) {
            $script .= "ConnectionInterface \$con = null";
        }

        $script .= ")
    {";
    }

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


Question: prepend header and sort lines before closing output

def with_output
      super do |out|
        out.puts header
        @queued_write = []
        yield out
        @queued_write.sort.each do |line|
          out.puts(line)
        end
      end
    end

def write_source(self, source, comment=None, reject=False):

        if not self._header_written:
            observations = [reading.get_observation() for reading in source.get_readings()]
            self.write_headers(observations, self.sys_header)

        self._write_source(source, comment=comment, reject=reject)

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


Question:
Returns the servlet for the passed URL mapping.

@param string $urlMapping The URL mapping to return the servlet for

@return \AppserverIo\Psr\Servlet\ServletInterface The servlet instance

public function getServletByMapping($urlMapping)
    {
        if (isset($this->servletMappings[$urlMapping])) {
            return $this->getServlet($this->servletMappings[$urlMapping]);
        }
    }

private static Map<String, String> findServiceBeanDefinitions(ConfigurableListableBeanFactory beanFactory) {
		final Map<String, String> serviceBeanNames = new HashMap<>();

		for (String beanName : beanFactory.getBeanDefinitionNames()) {
			AutoJsonRpcServiceImpl autoJsonRpcServiceImplAnnotation = beanFactory.findAnnotationOnBean(beanName, AutoJsonRpcServiceImpl.class);
			JsonRpcService jsonRpcServiceAnnotation = beanFactory.findAnnotationOnBean(beanName, JsonRpcService.class);

			if (null != autoJsonRpcServiceImplAnnotation) {

				if (null == jsonRpcServiceAnnotation) {
					throw new IllegalStateException("on the bean [" + beanName + "], @" +
							AutoJsonRpcServiceImpl.class.getSimpleName() + " was found, but not @" +
							JsonRpcService.class.getSimpleName() + " -- both are required");
				}

				List<String> paths = new ArrayList<>();
				Collections.addAll(paths, autoJsonRpcServiceImplAnnotation.additionalPaths());
				paths.add(jsonRpcServiceAnnotation.value());

				for (String path : paths) {
					if (!PATTERN_JSONRPC_PATH.matcher(path).matches()) {
						throw new RuntimeException("the path [" + path + "] for the bean [" + beanName + "] is not valid");
					}

					logger.info("exporting bean [{}] ---> [{}]", beanName, path);
					if (isNotDuplicateService(serviceBeanNames, beanName, path)) {
                        serviceBeanNames.put(path, beanName);
                    }
				}

			}
		}

		collectFromParentBeans(beanFactory, serviceBeanNames);
		return serviceBeanNames;
	}

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


Question:
Return month calendar of specified date, with optional setting for
first day of week (0 for Sunday)
@return array
@param $date string|int
@param $first int

function calendar($date='now',$first=0) {
		$out=FALSE;
		if (extension_loaded('calendar')) {
			if (is_string($date))
				$date=strtotime($date);
			$parts=getdate($date);
			$days=cal_days_in_month(CAL_GREGORIAN,$parts['mon'],$parts['year']);
			$ref=date('w',strtotime(date('Y-m',$parts[0]).'-01'))+(7-$first)%7;
			$out=[];
			for ($i=0;$i<$days;$i++)
				$out[floor(($ref+$i)/7)][($ref+$i)%7]=$i+1;
		}
		return $out;
	}

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

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

        return $this;
    }

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


Question:
Check if class matches the expected one.

@param object $object
@param array $expectedClasses

@throws \InvalidArgumentException

private function checkVariableType($object, array $expectedClasses)
    {
        if (!is_object($object)) {
            $msg = 'Expected variable of type object, got ' . gettype($object) . ". (field isn't multiple)";
            throw new \InvalidArgumentException($msg);
        }

        $classes = class_parents($object);
        $classes[] = $class = get_class($object);
        if (empty(array_intersect($classes, $expectedClasses))) {
            throw new \InvalidArgumentException("Expected object of type {$expectedClasses[0]}, got {$class}.");
        }
    }

protected String argumentTypeString(final Type type) {
        if (type instanceof ParameterizedType) {
            final ParameterizedType parameterizedType = (ParameterizedType) type;
            final List<String> subs = new ArrayList<>();
            for (final Type actualType : parameterizedType.getActualTypeArguments())
                subs.add(argumentTypeString(actualType));
            return argumentTypeString(((ParameterizedType) type).getRawType()) + "[" + String.join(",", subs) + "]";
        } else if (type instanceof GenericArrayType) {
            return argumentTypeString(((GenericArrayType) type).getGenericComponentType()) + "[]";
        } else if (type instanceof WildcardType) {
            throw new RuntimeException("We don't support wildcards in arguments: " + type);
        } else if (type instanceof Class<?>) {
            return ((Class) type).getSimpleName();
        } else {
            throw new DocException("Unknown type: " + type);
        }
    }

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


Question: /// Function emptyp //////////////////////////////////////////////////////  (obj:Obj) ↦ Bool  Checks if an object has any own properties.

function emptyp(obj) { var key
        for (key in obj)
            if (hasp(obj, key)) return false

        return true
    }

def _any(objs, query):
    '''

    '''
    for obj in objs:
        if isinstance(obj, Document):
            if _any(obj.roots, query):
                return True
        else:
            if any(query(ref) for ref in obj.references()):
                return True
    else:
        return False

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


Question:
{@inheritDoc}

@see java.sql.ResultSet#updateBlob(java.lang.String, java.io.InputStream, long)

@Override
	public void updateBlob(final String columnLabel, final InputStream inputStream, final long length)
			throws SQLException {
		wrapped.updateBlob(columnLabel, inputStream, length);
	}

def _parse_blob(self):
        """"""
        lineno = self.lineno
        mark = self._get_mark_if_any()
        data = self._get_data(b'blob')
        return commands.BlobCommand(mark, data, lineno)

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


Question: // NewChainMonitor creates a new ChainMonitor

func (db *StakeDatabase) NewChainMonitor(ctx context.Context, wg *sync.WaitGroup,
	reorgChan chan *txhelpers.ReorgData) *ChainMonitor {
	return &ChainMonitor{
		ctx:       ctx,
		db:        db,
		wg:        wg,
		reorgChan: reorgChan,
	}
}

public void add(Collection<NrqlAlertCondition> conditions)
    {
        for(NrqlAlertCondition condition : conditions)
            this.conditions.put(condition.getId(), condition);
    }

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


Question:
Returns rendered category tree.

@param \Twig_Environment $environment
@param string            $template
@param int               $maxLevel
@param null|string       $selectedCategory

@return null|string

public function getCategoryTree(
        \Twig_Environment $environment,
        $template = 'ONGRContentBundle:Category:inc/categorytree.html.twig',
        $maxLevel = 0,
        $selectedCategory = null
    ) {
        $this->setMaxLevel($maxLevel);
        $this->setTemplate($template);

        $this->categoryService->setCurrentCategoryId($selectedCategory);
        $tree = $this->categoryService->getTree($this->getMaxLevel(), true);
        $currentCategory = $this->categoryService->getCurrentCategoryDocument();

        return $this->renderCategoryTree($environment, $tree, $selectedCategory, $currentCategory);
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question:
Create a new Template expression

@deprecated Use {@link #enumTemplate(Class, Template, List)} instead.

@param cl type of expression
@param template template
@param args template parameters
@return template expression

@Deprecated
    public static <T extends Enum<T>> EnumTemplate<T> enumTemplate(Class<? extends T> cl,
                                                                   Template template, ImmutableList<?> args) {
        return new EnumTemplate<T>(cl, template, args);
    }

public List<Type> union(List<Type> cl1, List<Type> cl2) {
        if (cl1.isEmpty()) {
            return cl2;
        } else if (cl2.isEmpty()) {
            return cl1;
        } else if (cl1.head.tsym == cl2.head.tsym) {
            return union(cl1.tail, cl2.tail).prepend(cl1.head);
        } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) {
            return union(cl1.tail, cl2).prepend(cl1.head);
        } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) {
            return union(cl1, cl2.tail).prepend(cl2.head);
        } else {
            // unrelated types
            return union(cl1.tail, cl2).prepend(cl1.head);
        }
    }

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


Question:
Creates a Link
@param href an href value
@param rel a rel value
@return a link instance

public static Link link(String href, String rel) {
        return link(href, rel, null, null, null);
    }

def comicPageLink(self, comic, url, prevUrl):
        """"""
        pageInfo = self.getPageInfo(comic, url)
        pageInfo['prev'] = prevUrl

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


Question:
Builds an exchange name from a messaging context.
@param ctx a non-null context
@return a non-null string

public static String buildExchangeName( MessagingContext ctx ) {

		String exchangeName;
		if( ctx.getKind() == RecipientKind.DM )
			exchangeName = buildExchangeNameForTheDm( ctx.getDomain());
		else if( ctx.getKind() == RecipientKind.INTER_APP )
			exchangeName = buildExchangeNameForInterApp( ctx.getDomain());
		else
			exchangeName = RabbitMqUtils.buildExchangeNameForAgent( ctx.getDomain(), ctx.getApplicationName());

		return exchangeName;
	}

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

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

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


Question:
@param CardCollection $cards

@return SevenCardResult

public static function createHighCard(CardCollection $cards, Hand $hand): self
    {
        $cardValues = $cards->sortByValue()->values();

        $highCard = $cardValues->get(4);

        $definition = sprintf('High Card - %s', $highCard->name());

        return new static(
            self::HIGH_CARD,
            $cardValues->map(function (Card $card) {
                return $card->value();
            })->toArray(),
            $cards,
            $definition,
            $hand
        );
    }

public function process(ContainerBuilder $container)
    {
        $checkers = array();
        foreach ($container->findTaggedServiceIds('avoo.resource_generator.template') as $id => $attributes) {
            $checkers[$attributes[0]['type']] = $id;
        }

        $container->setParameter('avoo.resource_generator.templates', $checkers);
    }

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


Question:
Bind the data into this object.

@param   mixed   $values       The data array or object.
@param   boolean $replaceNulls Replace null or not.

@return  static Return self to support chaining.

public function bind($values, $replaceNulls = false)
    {
        if ($values === null) {
            return $this;
        }

        // Check properties type.
        if (!is_array($values) && !is_object($values)) {
            throw new \InvalidArgumentException(sprintf('Please bind array or object, %s given.', gettype($values)));
        }

        // If is Traversable, get iterator.
        if ($values instanceof \Traversable) {
            $values = iterator_to_array($values);
        } elseif (is_object($values)) {
            // If is object, convert it to array
            $values = get_object_vars($values);
        }

        // Bind the properties.
        foreach ($values as $field => $value) {
            // Check if the value is null and should be bound.
            if ($value === null && !$replaceNulls) {
                continue;
            }

            // Set the property.
            $this->offsetSet($field, $value);
        }

        return $this;
    }

static Flowable<Notification<TupleN<Object>>> createWithNParameters( //
            Single<Connection> connection, //
            String sql, //
            Flowable<List<Object>> parameterGroups, //
            List<ParameterPlaceholder> parameterPlaceholders, //
            List<Class<?>> outClasses) {
        return connection //
                .toFlowable() //
                .flatMap( //
                        con -> createWithParameters( //
                                con, //
                                sql, //
                                parameterGroups, //
                                parameterPlaceholders, //
                                (stmt, parameters) -> createWithNParameters(stmt, parameters, parameterPlaceholders,
                                        outClasses)));
    }

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


Question: // SetNextToken sets the NextToken field's value.

func (s *GetJobRunsInput) SetNextToken(v string) *GetJobRunsInput {
	s.NextToken = &v
	return s
}

func yaml_parser_fetch_stream_end(parser *yaml_parser_t) bool {

	// Force new line.
	if parser.mark.column != 0 {
		parser.mark.column = 0
		parser.mark.line++
	}

	// Reset the indentation level.
	if !yaml_parser_unroll_indent(parser, -1) {
		return false
	}

	// Reset simple keys.
	if !yaml_parser_remove_simple_key(parser) {
		return false
	}

	parser.simple_key_allowed = false

	// Create the STREAM-END token and append it to the queue.
	token := yaml_token_t{
		typ:        yaml_STREAM_END_TOKEN,
		start_mark: parser.mark,
		end_mark:   parser.mark,
	}
	yaml_insert_token(parser, -1, &token)
	return true
}

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


Question:
@EXT\Route("/admin/parameters/oauth/{service}", name="claro_admin_oauth_form")
@EXT\Template("ClarolineAuthenticationBundle:oauth:admin_form.html.twig")

@param $service

@return \Symfony\Component\HttpFoundation\Response

public function formAction($service)
    {
        $config = $this->oauthManager->getConfiguration($service);
        $form = $this->formFactory->create(OauthConfigurationType::class, $config, ['resource_owner' => $service]);

        return ['form' => $form->createView(), 'service' => $service];
    }

public static function installCoreBundle(InputInterface $input, OutputInterface $output, QuestionHelper $helper)
    {
        $rootDir = getcwd();
        $question = new ConfirmationQuestion('Would you like to install default core bundle (Recommended)? [y/n] ', true);
        if (!$helper->ask($input, $output, $question)) {
            return;
        }

        $applicationName = self::getApplicationName($input, $output, $helper);

        if (is_dir($rootDir.'/src/' . $applicationName . '/CoreBundle')) {
            return;
        }

        $output->writeln('<info>Installing Core bundle.</info>');
        $output->writeln('');

        $bundleDir = $rootDir . '/src/' . $applicationName;

        $fileSystem = new Filesystem();
        $fileSystem->setTwigEnvironment(self::getTwigEnvironment());

        self::buildComponentFiles($bundleDir . '/Component/', $applicationName, $fileSystem);
        self::buildCoreFiles($bundleDir . '/Bundle/CoreBundle/', $applicationName, $fileSystem);
        self::buildAppFiles(getcwd(), $applicationName, $fileSystem);

        $configFile = $rootDir . '/app/config/config.yml';
        $ref = '- { resource: security.yml }';
        $configDeclaration = '- { resource: @' . $applicationName . 'CoreBundle/Resources/config/app/' . strtolower($applicationName) . '.yml }';
        $content = file_get_contents($configFile);

        if (false === strpos($content, $configDeclaration)) {
            $updatedContent = str_replace($ref, $ref . "\n    " . $configDeclaration, $content);
            if ($content === $updatedContent) {
                throw new \RuntimeException('Unable to patch %s.', $configFile);
            }

            $fileSystem->dumpFile($configFile, $updatedContent);
        }

        $kernelFile = $rootDir . '/app/AppKernel.php';

        $fileSystem = new Filesystem();
        $ref = '$bundles = array(';
        $bundleDeclaration = 'new ' . $applicationName . '\\Bundle\\CoreBundle\\' . $applicationName . 'CoreBundle(),';
        $content = file_get_contents($kernelFile);

        if (false === strpos($content, $bundleDeclaration)) {
            $updatedContent = str_replace($ref, $ref . "\n            " . $bundleDeclaration."\n        ", $content);
            if ($content === $updatedContent) {
                throw new \RuntimeException('Unable to patch %s.', $kernelFile);
            }

            $fileSystem->dumpFile($kernelFile, $updatedContent);
        }
    }

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


Question: Initialize class fields.

public void init(int iTypeField, String typeFieldName, int iTargetValue)
    {
        m_iTargetValue = 0;
        m_iTypeField = 0;
        m_iTypeField = iTypeField;
        this.typeFieldName = typeFieldName;
        m_iTargetValue = iTargetValue;

        super.init(null);

        this.setMasterSlaveFlag(FileListener.RUN_IN_SLAVE | FileListener.RUN_IN_MASTER);   // This runs on the slave (if there is a slave)
    }

public void init(final String name,
			final boolean[] value, final int dim_x, final int dim_y) {
		buildAttributeValueObject(name);
		insert(value, dim_x, dim_y);
    }

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


Question:
// GetIdentity retrieves identity information.
//  Parameters:
//  id is required identity id
//
//  Returns:
//  Returns identity information

func (c *CAClientImpl) GetIdentity(id, caname string) (*api.IdentityResponse, error) {

	if c.adapter == nil {
		return nil, fmt.Errorf("no CAs configured for organization: %s", c.orgName)
	}

	// Checke required parameters (ID and affiliation)
	if id == "" {
		return nil, errors.New("id is required")
	}

	registrar, err := c.getRegistrar(c.registrar.EnrollID, c.registrar.EnrollSecret)
	if err != nil {
		return nil, err
	}

	return c.adapter.GetIdentity(registrar.PrivateKey(), registrar.EnrollmentCertificate(), id, caname)
}

func (user *User) Add(message newMessage) error {
	switch message.(type) {
	case *UserPost:
		post := message.(*UserPost)
		if post.To == 0 {
			post.To = user.ID()
		}
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *ProjectPost:
		post := message.(*ProjectPost)
		if err := createMessage(post, user.ID(), post.To, post.Text(), post.Language()); err != nil {
			return err
		}

		return Db().Create(post)

	case *UserPostComment:
		comment := message.(*UserPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *ProjectPostComment:
		comment := message.(*ProjectPostComment)
		if err := createMessage(comment, user.ID(), comment.Hpid, comment.Text(), comment.Language()); err != nil {
			return err
		}

		return Db().Create(comment)

	case *Pm:
		pm := message.(*Pm)
		if err := createMessage(pm, user.ID(), pm.To, pm.Text(), pm.Language()); err != nil {
			return err
		}
		return Db().Create(pm)
	}

	return fmt.Errorf("Invalid parameter type: %s", reflect.TypeOf(message))
}

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


Question: Get a perf message for the given datetime.

def _get_daily_message(self, dt, algo, metrics_tracker):

        perf_message = metrics_tracker.handle_market_close(
            dt,
            self.data_portal,
        )
        perf_message['daily_perf']['recorded_vars'] = algo.recorded_vars
        return perf_message

func (service *VboxPortType) IPerformanceMetricgetPeriod(request *IPerformanceMetricgetPeriod) (*IPerformanceMetricgetPeriodResponse, error) {
	response := new(IPerformanceMetricgetPeriodResponse)
	err := service.client.Call("", request, response)
	if err != nil {
		return nil, err
	}

	return response, nil
}

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


Question:
getHelper

Creates the helper and set the router

@param string $helper
@param array  $params

@return mixed The view helper

public function getHelper($helper, $params=array())
    {
        parent::getHelper($helper, $params);

        $viewHelper = new $this->_helperClassName();

        $viewHelper->setParams($params);
        $viewHelper->setRouter($this->_router);

        return $viewHelper;
    }

public function render(array $data, ContextInterface $context)
    {
        $data = optionsParser($data, [
            'name' => '',
            'val' => null,
            'type' => 'text',
            'escape' => true,
            'templateVars' => [],
        ]);
        $data->add('value', $data->consume('val'));

        return $this->_templates->format('hidden', [
            'name' => $data->get('name'),
            'type' => $data->get('type'),
            'templateVars' => $data->get('templateVars'),
            'attrs' => $this->_templates->formatAttributes($data->toArray(), ['name', 'type']),
        ]);
    }

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


Question:
getCurrentUser the user from quickbooks

@throws ConnectionException

public User getcurrentUser(String consumerKey, String consumerSecret,
			String accessToken, String accessTokenSecret)
			throws ConnectionException {
		httpClient = new PlatformHttpClient(consumerKey, consumerSecret,
				accessToken, accessTokenSecret);
		User user = null;;
		try {
			user = this.httpClient.getCurrentUser();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return user;
	}

protected function process(array $config, ContainerBuilder $container)
    {
        $container->setParameter('qcm_core.website_name', $config['website_name']);
        $container->setParameter('qcm.model.user.class', $config['user_class']);
        $container->setParameter('qcm.configuration', $config['configuration']);
        $container->setParameter('qcm_core.statistics.class', $config['service']['statistics']['class']);
        $container->setParameter('qcm_core.template.class', $config['service']['statistics']['template']);

        $container->setAlias('qcm.configuration', $config['service']['configuration']);
        $container->setAlias('qcm.user_session_configuration', $config['service']['user_session_configuration']);

        return $config;
    }

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


Question:
// StatusCode method returns the HTTP status code for the executed request.
//	Example: 200

func (r *Response) StatusCode() int {
	if r.RawResponse == nil {
		return 0
	}

	return r.RawResponse.StatusCode
}

def handleStatus(self, version, code, message):
        ""
        proxy.ProxyClient.handleStatus(self, version, code, message)
        # client.Response is currently just a container for needed data
        self._response = client.Response(version, code, message, {}, None)

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


Question: Internal. Initialises the humidity sensor via RTIMU

def _init_humidity(self):

        if not self._humidity_init:
            self._humidity_init = self._humidity.humidityInit()
            if not self._humidity_init:
                raise OSError('Humidity Init Failed')

def imu_changed(self, val):
        """"""
        self.current_imuid = '{}_IMU{}'.format(self.sk8.get_device_name(), val)
        self.update_data_display(self.get_current_data())

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


Question:
@param  PhpParser\Node\Expr $first_arg_value

@return null|string

public static function getConstName($first_arg_value, Codebase $codebase, Aliases $aliases)
    {
        $const_name = null;

        if ($first_arg_value instanceof PhpParser\Node\Scalar\String_) {
            $const_name = $first_arg_value->value;
        } elseif (isset($first_arg_value->inferredType)) {
            if ($first_arg_value->inferredType->isSingleStringLiteral()) {
                $const_name = $first_arg_value->inferredType->getSingleStringLiteral()->value;
            }
        } else {
            $simple_type = self::getSimpleType($codebase, $first_arg_value, $aliases);
            if ($simple_type && $simple_type->isSingleStringLiteral()) {
                $const_name = $simple_type->getSingleStringLiteral()->value;
            }
        }

        return $const_name;
    }

public function InExpression()
    {
        $inExpression = new AST\InExpression($this->ArithmeticExpression());

        if ($this->lexer->isNextToken(Lexer::T_NOT)) {
            $this->match(Lexer::T_NOT);
            $inExpression->not = true;
        }

        $this->match(Lexer::T_IN);
        $this->match(Lexer::T_OPEN_PARENTHESIS);

        if ($this->lexer->isNextToken(Lexer::T_SELECT)) {
            $inExpression->subselect = $this->Subselect();
        } else {
            $literals   = [];
            $literals[] = $this->InParameter();

            while ($this->lexer->isNextToken(Lexer::T_COMMA)) {
                $this->match(Lexer::T_COMMA);
                $literals[] = $this->InParameter();
            }

            $inExpression->literals = $literals;
        }

        $this->match(Lexer::T_CLOSE_PARENTHESIS);

        return $inExpression;
    }

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


Question: // Union returns the union of the keyspaces. They must overlap otherwise nil is returned.

func (k *Keyspace) Union(a *Keyspace) *Keyspace {
	if a == nil && k == nil {
		return nil
	} else if a == nil {
		return k.Clone()
	} else if k == nil {
		return a.Clone()
	}
	aSI := k.Includes(a.Start) || k.End == a.Start
	aEI := k.Includes(a.End) || k.Start == a.End
	kSI := a.Includes(k.Start) || a.End == k.Start
	kEI := a.Includes(k.End) || a.Start == k.End

	switch {
	// Complete keyspace
	case aSI && aEI && kSI && kEI:
		return &Keyspace{Start: k.Start, End: k.Start - 1}

	// k encompasses a
	case aSI && aEI:
		return k.Clone()

	// a encompasses k
	case kSI && kEI:
		return a.Clone()

	// a.Start is in k
	case aSI:
		return &Keyspace{Start: k.Start, End: a.End}

	// a.End is in k
	case aEI:
		return &Keyspace{Start: a.Start, End: k.End}
	}
	return nil
}

def append_key_label key, label, mode=@mode
      #@key_labels << [key, label] if !@key_labels.include? [key, label]
      @key_hash[mode] << [key, label] if !@key_hash[mode].include? [key, label]
      @repaint_required = true
    end

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


Question:
Disables the channel and deactivates it's resources.

@throws IllegalStateException
When an attempt is done to deactivate the channel while
inactive.

public void close() throws IllegalStateException {
		if (this.open) {
			// Close channels
			this.rtpChannel.close();
			if (!this.rtcpMux) {
				this.rtcpChannel.close();
			}

			if(logger.isDebugEnabled()) {
				logger.debug(this.mediaType + " channel " + this.ssrc + " is closed");
			}

			// Reset state
			reset();
			this.open = false;
		} else {
			throw new IllegalStateException("Channel is already inactive");
		}
	}

def quit(self, exit_code=0, event=None):

        # --- Running on_close components methods. ---
        for component in reversed(self.__components_manager.list_components()):
            interface = self.__components_manager.get_interface(component)
            if not interface:
                continue

            if not interface.activated:
                continue

            if not hasattr(interface, "on_close"):
                continue

            if not interface.on_close():
                event and event.ignore()
                return

        # Storing current layout.
        self.__layouts_manager.store_startup_layout()
        self.__settings.settings.sync()

        # Stopping worker threads.
        for worker_thread in self.__worker_threads:
            LOGGER.debug("> Stopping worker thread: '{0}'.".format(worker_thread))
            if not worker_thread.isFinished():
                worker_thread.quit()
            worker_thread.wait()

        foundations.verbose.remove_logging_handler(self.__logging_file_handler)
        foundations.verbose.remove_logging_handler(self.__logging_session_handler)
        # foundations.verbose.remove_logging_handler(self.__logging_console_handler)

        # Stopping the Application timer.
        self.__timer.stop()
        self.__timer = None

        self.deleteLater()
        event and event.accept()

        exit(exit_code)

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


Question:
Shows a specific help topic

@param helpindex

public static void showHelp(String helpindex) {
		if (getHelpBroker() == null) {
			return;
		}

		try {
			getHelpBroker().showID(helpindex, "javax.help.SecondaryWindow", null);
		} catch (Exception e) {
			logger.error("error loading help with index: " + helpindex, e);
		}
	}

def list_search_indexes(self):

        if not self.yz_wm_index:
            raise NotImplementedError("Search 2.0 administration is not "
                                      "supported for this version")

        url = self.search_index_path()

        # Run the request...
        status, headers, body = self._request('GET', url)

        if status == 200:
            json_data = json.loads(bytes_to_str(body))
            # Return a list of dictionaries
            return json_data
        else:
            raise RiakError('Error getting Search 2.0 index.')

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


Question: NOTE (BC) - Options passed in here is not currently doing anything

function getTransport (name, options) {
	name = ('' + name).toLowerCase();
	if (!transports[name]) {
		try {
			transports[name] = require('../transports/' + name);
		} catch (e) {
			if (e.code === 'MODULE_NOT_FOUND') {
				throw new Error('Could not load transport (' + name + ')');
			} else {
				throw e;
			}
		}
	}
	return transports[name];
}

func (s *DescribeNotificationsForBudgetInput) SetBudgetName(v string) *DescribeNotificationsForBudgetInput {
	s.BudgetName = &v
	return s
}

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


Question: p is file ? return json content : false

function checkStatFile(p, cb) {
  var fullPath = path.resolve(p)
    , json;
  try {
    json = require(fullPath);
  } catch (e) {
    if (e.code == 'MODULE_NOT_FOUND') {
      return cb(null,false);
    } else {
      // eslint-disable-next-line no-console
      console.error('require("' + fullPath + '") failed', e);
      return cb(e);
    }
  }
  return cb(null, json);
}

def prepare_post_parameters(self, post_params=None, files=None):

        params = post_params or []
        for key, values in (files or {}).items():
            for maybe_file_or_path in values if isinstance(values, list) else [values]:
                try:
                    # use the parameter as if it was an open file object
                    data = maybe_file_or_path.read()
                    maybe_file_or_path = maybe_file_or_path.name
                except AttributeError:
                    # then it is presumably a file path
                    with open(maybe_file_or_path, 'rb') as fh:
                        data = fh.read()
                basepath = os.path.basename(maybe_file_or_path)
                mimetype = mimetypes.guess_type(basepath)[0] or 'application/octet-stream'
                params.append((key, (basepath, data, mimetype)))
        return params

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


Question:
Prepares the related table for select, calling limit and orderBy if required
@param \DBScribe\Table $relTable
@param array $callArgs
@return \DBScribe\Table

private function prepSelectRelTable(Table &$relTable, array $callArgs) {
        foreach ($callArgs[0] as $method => $args) {
            if ($method === 'where') continue;
            if (method_exists($relTable, $method)) {
                $args = is_array($args) ? $args : array($args);
                $relTable = call_user_func_array(array($relTable, $method),
                        $args);
            }
        }
        return $relTable;
    }

public function &PreviousRow($DatasetType = FALSE) {
      $Result = &$this->Result($DatasetType);
      --$this->_Cursor;
      if (isset($Result[$this->_Cursor])) {
         return $Result[$this->_Cursor];
      }
      return $this->_EOF;
   }

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


Question: // Identity returns a copy of the Identity

func (p *PUPolicy) Identity() *TagStore {
	p.Lock()
	defer p.Unlock()

	return p.identity.Copy()
}

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

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


Question:
Get exception description
@param encoded The encoded string
@return The string

public static String exceptionDescription(String encoded)
   {
      char[] data = encoded.toCharArray();
      StringBuilder sb = new StringBuilder();

      for (int i = 0; i < data.length; i++)
      {
         char c = data[i];
         if (c == '|')
         {
            sb = sb.append('\n');
         }
         else if (c == '/')
         {
            sb = sb.append('\r');
         }
         else if (c == '\\')
         {
            sb = sb.append('\t');
         }
         else if (c == '_')
         {
            sb = sb.append(' ');
         }
         else
         {
            sb = sb.append(c);
         }
      }

      return sb.toString();
   }

public function parseError(array $responseDecoded)
    {
        if (array_key_exists('results', $responseDecoded)) {
            $this->errors = $responseDecoded['results'][0]['errors'];
            foreach ($this->errors as $errorInfo) {
                $this->addStatusMessage($errorInfo['message'], 'error');
                if (array_key_exists('for', $errorInfo)) {
                    unset($errorInfo['message']);
                    $this->addStatusMessage(json_encode($errorInfo), 'debug');
                }
            }
        } else {
            if (array_key_exists('message', $responseDecoded)) {
                $this->errors = [['message' => $responseDecoded['message']]];
            }
        }
        return count($this->errors);
    }

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


Question:
Replies the preferred number of lanes for a road segment.

@return the preferred number of lanes for a road segment.
@see #DEFAULT_LANE_COUNT

@Pure
	public static int getPreferredLaneCount() {
		final Preferences prefs = Preferences.userNodeForPackage(RoadNetworkConstants.class);
		if (prefs != null) {
			return prefs.getInt("LANE_COUNT", DEFAULT_LANE_COUNT); //$NON-NLS-1$
		}
		return DEFAULT_LANE_COUNT;
	}

def list_migration_issues_courses(self, course_id, content_migration_id):

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

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

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

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

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


Question:
@param ConnectionContext $context
@param string $source

@return mixed

@throws InvalidCacheKeyException

public function fetch(ConnectionContext $context, $source)
    {
        if ($context->mustCache()) {
            $options = $this->connector instanceof ConnectorOptions ? $this->connector->getOptions()->copy() : [];
            ksort($options);

            $this->validateCacheKey($key = $this->cacheKeyGenerator->generateCacheKey($source, $options));

            if ($this->cache->hasItem($key)) {
                return $this->cache->getItem($key)->get();
            }
        }

        $data = $this->connector->fetch($context, $source);

        isset($key) && $this->cache->save($this->cache->getItem($key)->set($data));

        return $data;
    }

def _create_response_future(self, query, parameters, trace, custom_payload,
                                timeout, execution_profile=EXEC_PROFILE_DEFAULT,
                                paging_state=None, host=None):

        prepared_statement = None

        if isinstance(query, six.string_types):
            query = SimpleStatement(query)
        elif isinstance(query, PreparedStatement):
            query = query.bind(parameters)

        if self.cluster._config_mode == _ConfigMode.LEGACY:
            if execution_profile is not EXEC_PROFILE_DEFAULT:
                raise ValueError("Cannot specify execution_profile while using legacy parameters.")

            if timeout is _NOT_SET:
                timeout = self.default_timeout

            cl = query.consistency_level if query.consistency_level is not None else self.default_consistency_level
            serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else self.default_serial_consistency_level

            retry_policy = query.retry_policy or self.cluster.default_retry_policy
            row_factory = self.row_factory
            load_balancing_policy = self.cluster.load_balancing_policy
            spec_exec_policy = None
        else:
            execution_profile = self._maybe_get_execution_profile(execution_profile)

            if timeout is _NOT_SET:
                timeout = execution_profile.request_timeout

            cl = query.consistency_level if query.consistency_level is not None else execution_profile.consistency_level
            serial_cl = query.serial_consistency_level if query.serial_consistency_level is not None else execution_profile.serial_consistency_level

            retry_policy = query.retry_policy or execution_profile.retry_policy
            row_factory = execution_profile.row_factory
            load_balancing_policy = execution_profile.load_balancing_policy
            spec_exec_policy = execution_profile.speculative_execution_policy

        fetch_size = query.fetch_size
        if fetch_size is FETCH_SIZE_UNSET and self._protocol_version >= 2:
            fetch_size = self.default_fetch_size
        elif self._protocol_version == 1:
            fetch_size = None

        start_time = time.time()
        if self._protocol_version >= 3 and self.use_client_timestamp:
            timestamp = self.cluster.timestamp_generator()
        else:
            timestamp = None

        if isinstance(query, SimpleStatement):
            query_string = query.query_string
            statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None
            if parameters:
                query_string = bind_params(query_string, parameters, self.encoder)
            message = QueryMessage(
                query_string, cl, serial_cl,
                fetch_size, timestamp=timestamp,
                keyspace=statement_keyspace)
        elif isinstance(query, BoundStatement):
            prepared_statement = query.prepared_statement
            message = ExecuteMessage(
                prepared_statement.query_id, query.values, cl,
                serial_cl, fetch_size,
                timestamp=timestamp, skip_meta=bool(prepared_statement.result_metadata),
                result_metadata_id=prepared_statement.result_metadata_id)
        elif isinstance(query, BatchStatement):
            if self._protocol_version < 2:
                raise UnsupportedOperation(
                    "BatchStatement execution is only supported with protocol version "
                    "2 or higher (supported in Cassandra 2.0 and higher).  Consider "
                    "setting Cluster.protocol_version to 2 to support this operation.")
            statement_keyspace = query.keyspace if ProtocolVersion.uses_keyspace_flag(self._protocol_version) else None
            message = BatchMessage(
                query.batch_type, query._statements_and_parameters, cl,
                serial_cl, timestamp, statement_keyspace)

        message.tracing = trace

        message.update_custom_payload(query.custom_payload)
        message.update_custom_payload(custom_payload)
        message.allow_beta_protocol_version = self.cluster.allow_beta_protocol_version
        message.paging_state = paging_state

        spec_exec_plan = spec_exec_policy.new_plan(query.keyspace or self.keyspace, query) if query.is_idempotent and spec_exec_policy else None
        return ResponseFuture(
            self, message, query, timeout, metrics=self._metrics,
            prepared_statement=prepared_statement, retry_policy=retry_policy, row_factory=row_factory,
            load_balancer=load_balancing_policy, start_time=start_time, speculative_execution_plan=spec_exec_plan,
            host=host)

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


Question:
(non-PHPdoc)
@see \Thrace\DataGridBundle\DataGrid\DataGridInterface::setDriver()

public function setDriver($driver)
    {
        $availableDrivers = array(DataGridInterface::ARRAY_DRIVER, DataGridInterface::ORM_DRIVER);

        if (!in_array($driver, $availableDrivers)){
            throw new \InvalidArgumentException(sprintf('Driver %s is not available.', $driver));
        }

        $this->driver = $driver;

        return $this;
    }

public function set($name, $value, $secure=false)
    {
        $params = ['cookie' =>
            [
                'name' => $name,
                'value' => "{$value}",
                'secure' => $secure,
            ]
        ];
        $command = $this->driver->factoryCommand('cookie', WebDriver_Command::METHOD_POST, $params);
        $this->driver->curl($command);
    }

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


Question: // DeleteFunction stub.

func (l *Lambda) DeleteFunction(in *lambda.DeleteFunctionInput) (*lambda.DeleteFunctionOutput, error) {
	if in.Qualifier == nil {
		l.remove("function", *in.FunctionName, nil)
	} else {
		l.remove("function version", fmt.Sprintf("%s (version: %s)", *in.FunctionName, *in.Qualifier), nil)
	}

	return nil, nil
}

function(toDelete, evtStck) {
    let len = toDelete.length
    for (let i = 0; len > i; len--) {
      evtStck.splice(toDelete[len - 1], 1)
    }
  }

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


Question:
Get lock state transaction status

        Args:
            transaction_id: Transaction ID received from set_lock_state

def get_lock_state_transaction(self, transaction_id):

        response = None
        try:
            response = requests.get(
                urls.get_lockstate_transaction(self._giid, transaction_id),
                headers={
                    'Accept': 'application/json, text/javascript, */*; q=0.01',
                    'Cookie': 'vid={}'.format(self._vid)})
        except requests.exceptions.RequestException as ex:
            raise RequestError(ex)
        _validate_response(response)
        return json.loads(response.text)

func (c *ConversationLockTab) Acquire(ctx context.Context, uid gregor1.UID, convID chat1.ConversationID) (blocked bool, err error) {
	sleep := 200 * time.Millisecond
	for i := 0; i < c.maxAcquireRetries; i++ {
		blocked, err = c.doAcquire(ctx, uid, convID)
		if err != nil {
			if err != ErrConvLockTabDeadlock {
				return true, err
			}
			c.Debug(ctx, "Acquire: deadlock condition detected, sleeping and trying again: attempt: %d", i)
			time.Sleep(sleep)
			continue
		}
		return blocked, nil
	}
	c.Debug(ctx, "Acquire: giving up, max attempts reached")
	return true, ErrConvLockTabDeadlock
}

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


Question:
We will register user defined events, it will trigger event when matches.

@param $events
@throws \RuntimeException

public function registerEvents($events)
    {
        if (empty($events)) {
            throw new \RuntimeException(sprintf('Empty argument passed %s', __FUNCTION__));
        }

        foreach ($events as $event => $namespace) {
            $parts = explode('@', $namespace);
            // attach all before and after event to handler
            $this->register("$event.before", $parts[0].'@before'.ucfirst(Inflector::pathAction(end($parts))))
                 ->register("$event", $parts[0].'@'.Inflector::pathAction(end($parts)))
                 ->register("$event.after", $parts[0].'@after'.ucfirst(Inflector::pathAction(end($parts))));
        }
    }

public function setupRules()
    {
        $this->rules->addMany([
            'comment'     => new Rule(new CommentMatcher([], [['{#', '#}']]), ['priority' => 0]),
            'delimiter'   => new Rule(new RegexMatcher('/((\{[{%]|[%}]\}))/')),
            'variable'    => new Rule(new RegexMatcher('/\{\{\s*([a-z]\w*)/')),
            'call'        => new Rule(new RegexMatcher('/\{\{.*?\|([a-z]\w*)/')),
            'call.template-tag' => new Rule(new RegexMatcher('/{%\s*([a-z]\w*)/')),
            'string' => CommonFeatures::strings(['single' => '\'', 'double' => '"'], [
                'context' => ['!string', '!comment']
            ]),
        ]);
    }

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


Question:
// === Utility
// ===

func stripComments(l string) string {
	// Comments are preceded by space or TAB
	for _, c := range []string{" ;", "\t;", " #", "\t#"} {
		if i := strings.Index(l, c); i != -1 {
			l = l[0:i]
		}
	}
	return l
}

func (*StrictQuad_Ref) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _StrictQuad_Ref_OneofMarshaler, _StrictQuad_Ref_OneofUnmarshaler, _StrictQuad_Ref_OneofSizer, []interface{}{
		(*StrictQuad_Ref_BnodeLabel)(nil),
		(*StrictQuad_Ref_Iri)(nil),
	}
}

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


Question:
Show the form for editing the specified resource.
GET /subscriber/{id}/edit

@param  int  $id
@return Response

public function show($id)
    {
        $subscriber = $this->subscriber->find($id);
        $newsletter = $this->newsletter->getAll();

        return view('newsletter::Backend.subscribers.show')->with(['subscriber' => $subscriber , 'newsletter' => $newsletter]);
    }

public function updateRules(RuleSet $ruleSet)
    {
        $this->client->updateRules($this->uri->withPath('.settings/rules'), $ruleSet);
    }

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


Question:
Return a cache key for the content item output.

    .. seealso::

        The :func:`ContentItem.clear_cache() <fluent_contents.models.ContentItem.clear_cache>` function
        can be used to remove the cache keys of a retrieved object.

def get_rendering_cache_key(placeholder_name, contentitem):

    if not contentitem.pk:
        return None
    return "contentitem.@{0}.{1}.{2}".format(
        placeholder_name,
        contentitem.plugin.type_name,  # always returns the upcasted name.
        contentitem.pk,                # already unique per language_code
    )

def populate_client_cache(self, low):
        '''

        '''
        reaction_type = low['state']
        if reaction_type not in self.client_cache:
            log.debug('Reactor is populating %s client cache', reaction_type)
            if reaction_type in ('runner', 'wheel'):
                # Reaction types that run locally on the master want the full
                # opts passed.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts)
                # The len() function will cause the module functions to load if
                # they aren't already loaded. We want to load them so that the
                # spawned threads don't need to load them. Loading in the
                # spawned threads creates race conditions such as sometimes not
                # finding the required function because another thread is in
                # the middle of loading the functions.
                len(self.client_cache[reaction_type].functions)
            else:
                # Reactions which use remote pubs only need the conf file when
                # instantiating a client instance.
                self.client_cache[reaction_type] = \
                    self.reaction_class[reaction_type](self.opts['conf_file'])

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


Question: // IdleLen returns number of idle connections.

func (p *ConnPool) IdleLen() int {
	p.connsMu.Lock()
	n := p.idleConnsLen
	p.connsMu.Unlock()
	return n
}

public function onConnect(Server $server, int $fd, int $fromId): void
    {
        $this->log("onConnect: Has a new client [fd:$fd] connection to the main server.(fromId: $fromId,workerId: {$server->worker_id})");

        if ($this->handler) {
            $this->handler->onConnect($server, $fd, $fromId);
        }
    }

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


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

func (s *RDSDataSpec) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "RDSDataSpec"}
	if s.DatabaseCredentials == nil {
		invalidParams.Add(request.NewErrParamRequired("DatabaseCredentials"))
	}
	if s.DatabaseInformation == nil {
		invalidParams.Add(request.NewErrParamRequired("DatabaseInformation"))
	}
	if s.ResourceRole == nil {
		invalidParams.Add(request.NewErrParamRequired("ResourceRole"))
	}
	if s.ResourceRole != nil && len(*s.ResourceRole) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ResourceRole", 1))
	}
	if s.S3StagingLocation == nil {
		invalidParams.Add(request.NewErrParamRequired("S3StagingLocation"))
	}
	if s.SecurityGroupIds == nil {
		invalidParams.Add(request.NewErrParamRequired("SecurityGroupIds"))
	}
	if s.SelectSqlQuery == nil {
		invalidParams.Add(request.NewErrParamRequired("SelectSqlQuery"))
	}
	if s.SelectSqlQuery != nil && len(*s.SelectSqlQuery) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("SelectSqlQuery", 1))
	}
	if s.ServiceRole == nil {
		invalidParams.Add(request.NewErrParamRequired("ServiceRole"))
	}
	if s.ServiceRole != nil && len(*s.ServiceRole) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("ServiceRole", 1))
	}
	if s.SubnetId == nil {
		invalidParams.Add(request.NewErrParamRequired("SubnetId"))
	}
	if s.SubnetId != nil && len(*s.SubnetId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("SubnetId", 1))
	}
	if s.DatabaseCredentials != nil {
		if err := s.DatabaseCredentials.Validate(); err != nil {
			invalidParams.AddNested("DatabaseCredentials", err.(request.ErrInvalidParams))
		}
	}
	if s.DatabaseInformation != nil {
		if err := s.DatabaseInformation.Validate(); err != nil {
			invalidParams.AddNested("DatabaseInformation", err.(request.ErrInvalidParams))
		}
	}

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

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

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

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


Question: Creates an enum for contest type

def challenge():
  """"""
  enums = dict(
    ACTIVE="active",
    UPCOMING="upcoming",
    HIRING="hiring",
    ALL="all",
    SHORT="short",
  )

  return type('Enum', (), enums)

func DetermineTxTypeString(msgTx *wire.MsgTx) string {
	switch stake.DetermineTxType(msgTx) {
	case stake.TxTypeSSGen:
		return "Vote"
	case stake.TxTypeSStx:
		return "Ticket"
	case stake.TxTypeSSRtx:
		return "Revocation"
	default:
		return "Regular"
	}
}

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


Question:
Setup the ui

        :returns: None
        :rtype: None
        :raises: None

def setup_ui(self, ):

        labels = self.reftrack.get_option_labels()
        self.browser = ComboBoxBrowser(len(labels), headers=labels)
        self.browser_vbox.addWidget(self.browser)

public function draw($im) {
        $this->calculateChecksum();

        // Starting Code
        $this->drawChar($im, '000', true);
        $c = strlen($this->upce);
        for ($i = 0; $i < $c; $i++) {
            $this->drawChar($im, self::inverse($this->findCode($this->upce[$i]), $this->codeParity[intval($this->text[0])][$this->checksumValue][$i]), false);
        }

        // Draw Center Guard Bar
        $this->drawChar($im, '00000', false);

        // Draw Right Bar
        $this->drawChar($im, '0', true);
        $this->text = $this->text[0] . $this->upce;
        $this->drawText($im, 0, 0, $this->positionX, $this->thickness);

        if ($this->isDefaultEanLabelEnabled()) {
            $dimension = $this->labelCenter->getDimension();
            $this->drawExtendedBars($im, $dimension[1] - 2);
        }
    }

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


Question:
Constructor.
@param record My owner (usually passed as null, and set on addListener in setOwner()).

public void init(Record record, BaseField fldDeleteFlag)
    {
        m_fldDeleteFlag = fldDeleteFlag;
        m_bFilterThisRecord = true;
        super.init(record);
    }

def _create_event_listeners(self):
        """"""
        LOG.debug("Create the event listeners.")
        for event_type, callback in self._event_callback_pairs:
            LOG.debug("Create listener for %r event", event_type)
            listener = self._utils.get_vnic_event_listener(event_type)
            eventlet.spawn_n(listener, callback)

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


Question:
Parses directives that are potentially common to all entries and returns the LdifEntry object. Common directives
include: changetype, control

@param $dn
@return LdifEntryInterface
@throws LdifParserException

protected function parseCommonDirectives($dn)
    {
        $changeType = null;
        $controls = [];

        $this->nextLine();
        while ($this->isCommonDirective()) {
            if ($this->isComment()) {
                $this->nextLine();
                continue;
            // We need to exit the loop completely in this case...
            } elseif ($this->isEndOfLdif() || $this->isStartOfEntry()) {
                break;
            } elseif ($this->isCommonDirective()) {
                list($key, $value) = $this->getKeyAndValue($this->currentLine());

                if ($key == Ldif::DIRECTIVE_CHANGETYPE && is_null($changeType)) {
                    $changeType = $value;
                } elseif ($key == Ldif::DIRECTIVE_CHANGETYPE && !is_null($changeType)) {
                    $this->throwException('The changetype directive has already been defined');
                } else {
                    $controls[] = $this->getLdapControl($value);
                }
            }
            $this->nextLine();
        }
        $changeType = $changeType ?: LdifEntryInterface::TYPE_ADD;
        $entry = $this->getLdifEntryObject($dn, $changeType);

        foreach ($controls as $control) {
            $entry->addControl($control);
        }

        return $entry;
    }

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);
    }

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


Question:
// StringMap converts a string map of string values into a string
// map of string pointers

func StringMap(src map[string]string) map[string]*string {
	dst := make(map[string]*string)
	for k, val := range src {
		v := val
		dst[k] = &v
	}
	return dst
}

List<Message> getMutableList() {
        if (mode != StorageMode.LIST) {
            if (mode == StorageMode.MAP) {
                listData = convertMapToList(mapData);
            }
            mapData = null;
            mode = StorageMode.LIST;
        }
        return listData;
    }

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


Question:
Ask wich metadata you want to use
@param  MetaDataSource                              $metadataSource
@param  string|null                                 $choice
@throws ResponseExpectedException
@return \CrudGenerator\Metadata\DataObject\MetaData

public function ask(MetaDataSource $metadataSource, $choice = null)
    {
        $metaDataCollection = $this->getMetadataDao($metadataSource)->getAllMetadata();
        $responseCollection = new PredefinedResponseCollection();

        foreach ($metaDataCollection as $metaData) {
            $response = new PredefinedResponse($metaData->getOriginalName(), $metaData->getOriginalName(), $metaData);
            $response->setAdditionalData(array('source' => $metadataSource->getUniqueName()));

            $responseCollection->append($response);
        }

        $question = new QuestionWithPredefinedResponse(
            "Select Metadata",
            self::QUESTION_KEY,
            $responseCollection
        );
        $question->setPreselectedResponse($choice);
        $question->setShutdownWithoutResponse(true);

        return $this->context->askCollection($question);
    }

function namedParameterList()
    {
        $def = array( $this->Name => array( 'context' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => false ),
                                            'comment' => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => '' ),
                                            'arguments' => array( 'type' => 'hash',
                                                                  'required' => false,
                                                                  'default' => false ) ),
                      $this->ExtensionName => array( 'extension' => array( 'type' => 'string',
                                                                           'required' => true,
                                                                           'default' => false ),
                                                     'context' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => false ),
                                                     'comment' => array( 'type' => 'string',
                                                                         'required' => false,
                                                                         'default' => '' ),
                                                     'arguments' => array( 'type' => 'hash',
                                                                           'required' => false,
                                                                           'default' => false ) ) );
        $def[ $this->DynamicName ] = $def[ $this->Name ];
        return $def;
    }

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


Question:
Compares the scopes read from request with previously issued scopes.

        :param previous_scopes: A list of scopes.
        :return: ``True``

def compare(self, previous_scopes):

        for scope in self.scopes:
            if scope not in previous_scopes:
                raise OAuthInvalidError(
                    error="invalid_scope",
                    explanation="Invalid scope parameter in request")

        return True

def check_url(url_data, logger):
    """"""
    if url_data.has_result:
        logger.log_url(url_data.to_wire())
    else:
        cache = url_data.aggregate.result_cache
        key = url_data.cache_url
        result = cache.get_result(key)
        if result is None:
            # check
            check_start = time.time()
            try:
                url_data.check()
                do_parse = url_data.check_content()
                url_data.checktime = time.time() - check_start
                # Add result to cache
                result = url_data.to_wire()
                cache.add_result(key, result)
                for alias in url_data.aliases:
                    # redirect aliases
                    cache.add_result(alias, result)
                # parse content recursively
                # XXX this could add new warnings which should be cached.
                if do_parse:
                    parser.parse_url(url_data)
            finally:
                # close/release possible open connection
                url_data.close_connection()
        else:
            # copy data from cache and adjust it
            result = copy.copy(result)
            result.parent_url = url_data.parent_url
            result.base_ref = url_data.base_ref or u""
            result.base_url = url_data.base_url or u""
            result.line = url_data.line
            result.column = url_data.column
            result.level = url_data.recursion_level
            result.name = url_data.name
        logger.log_url(result)

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


Question: // Message returns just the error message without the backtrace or exits.

func (e *Error) Message() string {
	message := strings.TrimRight(GetMessage(e.err), "\n ")
	if strings.Contains(message, "\n") {
		return fmt.Sprintf("%s:\n  %s", e.class.String(),
			strings.Replace(message, "\n", "\n  ", -1))
	}
	return fmt.Sprintf("%s: %s", e.class.String(), message)
}

def exception(self, exception):
        """"""
        if self.writelog:
            self.logger.exception(exception)
        if self.verbose:
            for line in  traceback.format_exception(
                    None, exception, exception.__traceback__):
                print(line, end='', file=sys.stderr, flush=True)

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


Question: // DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (in *TokenRequestSpec) DeepCopyInto(out *TokenRequestSpec) {
	*out = *in
	if in.Audiences != nil {
		in, out := &in.Audiences, &out.Audiences
		*out = make([]string, len(*in))
		copy(*out, *in)
	}
	if in.BoundObjectRef != nil {
		in, out := &in.BoundObjectRef, &out.BoundObjectRef
		*out = new(BoundObjectReference)
		**out = **in
	}
	return
}

def to_gufunc_string(self):

        all_dims = self.all_core_dims
        dims_map = dict(zip(sorted(all_dims), range(len(all_dims))))
        input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                           for core_dims in self.input_core_dims]
        output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims]
                            for core_dims in self.output_core_dims]
        alt_signature = type(self)(input_core_dims, output_core_dims)
        return str(alt_signature)

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


Question: Add rename function to copy task config

function(dest, src) {
      if(src.indexOf('.js') > -1) {
        return dest + src.replace('.js','.' + tsPrefix + newTS + '.js');
      }
      else {
        return dest + src.replace('.css','.' + tsPrefix + newTS + '.css');
      }
    }

func (s *SnapshotCopyGrant) SetSnapshotCopyGrantName(v string) *SnapshotCopyGrant {
	s.SnapshotCopyGrantName = &v
	return s
}

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


Question:
@param $interval

@return \DateInterval
@throws DateTimeObjectException

private function parseDateInterval($interval)
    {
        try {
            if (!$this->isInstanceOf($interval, 'DateInterval')) {
                $interval = new StringObject($interval);
                if ($interval->startsWith('P')) {
                    $interval = new \DateInterval($interval);
                } else {
                    $interval = \DateInterval::createFromDateString($interval);
                }
            }
        } catch (\Exception $e) {
            throw new DateTimeObjectException(DateTimeObjectException::MSG_INVALID_DATE_INTERVAL, [$interval]);
        }

        return $interval;
    }

protected static function fail(
        int $errorCode = ErrorCodes::INVALID_VALUE,
        string $messageTemplate = Messages::INVALID_VALUE,
        array $messageParams = []
    ): RuleInterface {
        return new Fail($errorCode, $messageTemplate, $messageParams);
    }

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


Question:
Process a RDS enhenced monitoring DATA_MESSAGE,
        coming from CLOUDWATCH LOGS

def lambda_handler(event, context):
    '''
    '''
    # event is a dict containing a base64 string gzipped
    event = json.loads(gzip.GzipFile(fileobj=StringIO(event['awslogs']['data'].decode('base64'))).read())

    account = event['owner']
    region = context.invoked_function_arn.split(':', 4)[3]

    log_events = event['logEvents']

    for log_event in log_events:
        message = json.loads(log_event['message'])
        ts = log_event['timestamp'] / 1000
        _process_rds_enhanced_monitoring_message(ts, message, account, region)

    stats.flush()
    return {'Status': 'OK'}

func CreateObjects(
	ctx context.Context,
	bucket gcs.Bucket,
	input map[string][]byte) (err error) {
	bundle := syncutil.NewBundle(ctx)

	// Feed ObjectInfo records into a channel.
	type record struct {
		name     string
		contents []byte
	}

	recordChan := make(chan record, len(input))
	for name, contents := range input {
		recordChan <- record{name, contents}
	}

	close(recordChan)

	// Create the objects in parallel.
	const parallelism = 64
	for i := 0; i < 10; i++ {
		bundle.Add(func(ctx context.Context) (err error) {
			for r := range recordChan {
				_, err = CreateObject(
					ctx, bucket,
					r.name,
					r.contents)

				if err != nil {
					return
				}
			}

			return
		})
	}

	err = bundle.Join()
	return
}

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


Question: //run: sendSMS <from-number> <to-number> <text>

func main5() {
	api, _ := bandwidth.New(os.Getenv("CATAPULT_USER_ID"), os.Getenv("CATAPULT_API_TOKEN"), os.Getenv("CATAPULT_API_SECRET"))
	fromNumber := os.Args[1]
	toNumber := os.Args[2]
	text := os.Args[3]
	id, err := api.CreateMessage(&bandwidth.CreateMessageData{From: fromNumber, To: toNumber, Text: text})
	if err != nil {
		fmt.Printf("Error: %s", err.Error())
		return
	}
	fmt.Printf("Message ID is %s", id)
}

public BaseMessageSender createMessageSender()
    {
        RemoteTask server = (RemoteTask)((App)this.getMessageManager().getApplication()).getRemoteTask(null);
        try   {
            return new RemoteMessageSender(server, this);
        } catch (RemoteException ex)    {
            ex.printStackTrace();
        }
        return null;
    }

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


Question: <editor-fold defaultstate="collapsed" desc="Greatest lower bound">

public Type glb(List<Type> ts) {
        Type t1 = ts.head;
        for (Type t2 : ts.tail) {
            if (t1.isErroneous())
                return t1;
            t1 = glb(t1, t2);
        }
        return t1;
    }

function() {

      // This element wraps the input node in a float: none div
      this.wrapEl = inputEx.cn('div', {className: 'inputEx-StringField-wrapper'});

      // Attributes of the input field
      var attributes = {};
      attributes.id = this.divEl.id?this.divEl.id+'-field':YAHOO.util.Dom.generateId();
      attributes.rows = this.options.rows;
      attributes.cols = this.options.cols;
      if(this.options.name) attributes.name = this.options.name;
      if(this.options.readonly) attributes.readonly = 'readonly';

      //if(this.options.maxLength) attributes.maxLength = this.options.maxLength;

      // Create the node
      this.el = inputEx.cn('textarea', attributes, null, this.options.value);

      // Append it to the main element
      this.wrapEl.appendChild(this.el);
      this.fieldContainer.appendChild(this.wrapEl);
   }

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


Question:
Interpret the provided option when a list is expected.
 Used to provide functionality like:
     jido.conjugate 'be', :form => 'prs'
     jido.conjugate 'be', :form => %w{prs pst prf}

def check_for_list_option option_name
      return nil if @options[option_name].nil?

      return [@options[option_name]] if @options[option_name].is_a?(String) or @options[option_name].is_a(Hash)
      return @options[option_name] if @options[option_name].is_a?(Array)

      raise "Invalid data type provided for option #{option_name}: a list was expected. Please provide a single string element or an array of strings."
    end

public function transform(Did $did)
    {
        return [
            'id'    => $did->id,
            'text'  => $did->text,
            'created_at' => $did->created_at->toIso8601String()
        ];
    }

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


Question: Respond to an RPC previously sent to a service.

async def respond_rpc(self, msg, _context):
        """"""

        rpc_id = msg.get('response_uuid')
        result = msg.get('result')
        payload = msg.get('response')

        self.service_manager.send_rpc_response(rpc_id, result, payload)

function to($alias) {
		if (isset($this->aliases[$alias])) {
			return $this->aliases[$alias];
		}
		else {
			throw new Exception("That Redisent alias does not exist");
		}
	}

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


Question: Merges this node with the other, returning a new node that spans the both.

def merge(self, other):

        new_node = self.copy()
        new_node.size += other.size
        new_node.instruction_addrs += other.instruction_addrs
        # FIXME: byte_string should never be none, but it is sometimes
        # like, for example, patcherex test_cfg.py:test_fullcfg_properties
        if new_node.byte_string is None or other.byte_string is None:
            new_node.byte_string = None
        else:
            new_node.byte_string += other.byte_string
        return new_node

private static function removeProceedingNodes($domNode, $topNode)
    {
        $nextNode = $domNode->nextSibling;

        if ($nextNode !== null) {
            self::removeProceedingNodes($nextNode, $topNode);
            $domNode->parentNode->removeChild($nextNode);
        } else {
            //scan upwards till we find a sibling
            $curNode = $domNode->parentNode;
            while ($curNode !== $topNode) {
                if ($curNode->nextSibling !== null) {
                    $curNode = $curNode->nextSibling;
                    self::removeProceedingNodes($curNode, $topNode);
                    $curNode->parentNode->removeChild($curNode);
                    break;
                }
                $curNode = $curNode->parentNode;
            }
        }
    }

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


Question:
/*!
See eZTemplateOperator::namedParameterList()

function namedParameterList()
    {
        return array( $this->AttributeName => array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 2 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ),
                      $this->DumpName =>      array( "show_values" => array( "type" => "string",
                                                                             "required" => false,
                                                                             "default" => "show" ),
                                                     "max_val"     => array( "type" => "numerical",
                                                                             "required" => false,
                                                                             "default" => 1 ),
                                                     "format"      => array( "type" => "boolean",
                                                                             "required" => false,
                                                                             "default" => eZINI::instance( 'template.ini' )->variable( 'AttributeOperator', 'DefaultFormatter' ) ) ) );
    }

public function maybeMatch(string $variable = null, array $labels = []): self
    {
        $query = new self;
        $query->clauses = $this->clauses->add(
            new Clause\OptionalMatchClause(
                Clause\Expression\Path::startWithNode($variable, $labels)
            )
        );

        return $query;
    }

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


Question:
@param string $whenYouWereFourteenNumberOfEmployeesByFather

@throws \InvalidArgumentException

@return Employer

public function setWhenYouWereFourteenNumberOfEmployeesByFather($whenYouWereFourteenNumberOfEmployeesByFather)
    {
        if (
            !is_string($whenYouWereFourteenNumberOfEmployeesByFather)
            &&
            !is_null($whenYouWereFourteenNumberOfEmployeesByFather)
        ) {
            throw new \InvalidArgumentException(__CLASS__ . ' ' . __METHOD__ . ': Not a string');
        }

        $this->whenYouWereFourteenNumberOfEmployeesByFather = $whenYouWereFourteenNumberOfEmployeesByFather;

        return $this;
    }

function (arg) {
    var self = this;

    var argType = arg[0];
    var argValue = arg[1];

    var argCode;
    switch (argType) {
    case 'STRING':
    case 'NUMBER':
    case 'BOOLEAN':
    case 'NULL':
      argCode = BlazeTools.toJSLiteral(argValue);
      break;
    case 'PATH':
      argCode = self.codeGenPath(argValue);
      break;
    case 'EXPR':
      // The format of EXPR is ['EXPR', { type: 'EXPR', path: [...], args: { ... } }]
      argCode = self.codeGenMustache(argValue.path, argValue.args, 'dataMustache');
      break;
    default:
      // can't get here
      throw new Error("Unexpected arg type: " + argType);
    }

    return argCode;
  }

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


Question:
Create a new tenant with the given definition and return the updated definition.
Throw a {@link DuplicateException} if the tenant has already been defined.

@param tenantDef {@link TenantDefinition} of new tenant.
@return          Updated definition.

public TenantDefinition defineTenant(TenantDefinition tenantDef) {
        checkServiceState();
        String tenantName = tenantDef.getName();
        if (getTenantDef(tenantName) != null) {
            throw new DuplicateException("Tenant already exists: " + tenantName);
        }
        defineNewTenant(tenantDef);
        TenantDefinition updatedTenantDef = getTenantDef(tenantName);
        if (updatedTenantDef == null) {
            throw new RuntimeException("Tenant definition could not be retrieved after creation: " + tenantName);
        }
        removeUserHashes(updatedTenantDef);
        return updatedTenantDef;
    }

@Override
	public PrincipalUser getUser(String username, String password) {
		requireNotDisposed();

		PrincipalUser result = _userService.findUserByUsername(username);
		String isPrivileged= _config.getValue(Property.IS_PRIVILEGED.getName(), Property.IS_PRIVILEGED.getDefaultValue());

		if(result == null){
			result = new PrincipalUser(_userService.findAdminUser(), username, username+"@gmail.com");
		}
                DAILY_USERS.put(username, System.currentTimeMillis());
                MONTHLY_USERS.put(username, System.currentTimeMillis());
                _monitorService.updateCounter(MonitorService.Counter.DAILY_USERS, DAILY_USERS.size(), new HashMap<>(0));
                _monitorService.updateCounter(MonitorService.Counter.MONTHLY_USERS, MONTHLY_USERS.size(), new HashMap<>(0));
		_monitorService.updateCounter(MonitorService.Counter.UNIQUE_USERS, _userService.getUniqueUserCount(), new HashMap<String, String>(0));

		try{
			Method method = PrincipalUser.class.getDeclaredMethod("setPrivileged", boolean.class);
			method.setAccessible(true);
			method.invoke(result, Boolean.parseBoolean(isPrivileged));

		} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
			throw new SystemException("Failed to change privileged status.", e);
		}

		result = _userService.updateUser(result);
		return result;
	}

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


Question: mutates `reachable`, btw

function widthTraverse (graph, reachable, start, depth, hops, iter) {
  if(!start)
    throw new Error('Graphmitter#traverse: start must be provided')

  //var nodes = 1

  reachable[start] = reachable[start] == null ? 0 : reachable[start]

  var queue = [start] //{key: start, hops: depth}]
  iter = iter || function () {}
  while(queue.length) {
    var o = queue.shift()
    var h = reachable[o]
    var node = graph[o]
    if(node && (!hops || (h + 1 <= hops)))
      for(var k in node) {
        // If we have already been to this node by a shorter path,
        // then skip this node (this only happens when processing
        // a realtime edge)
        if(!(reachable[k] != null && reachable[k] < h + 1)) {
          if(false === iter(o, k, h + 1, reachable[k]))
            return reachable

          reachable[k] = h + 1
//          nodes ++
          queue.push(k)
        }
    }
  }

  return reachable
}

def next(self):

        self.params['offset'] = str(int(self.params['offset']) + int(self.params['limit']))
        return self.marvel.get_characters(self.marvel, (), **self.params)

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


Question:
Register function prototypes with a libclang library instance.

    This must be called as part of library instantiation so Python knows how
    to call out to the shared library.

def register_functions(lib, ignore_errors):

    def register(item):
        return register_function(lib, item, ignore_errors)

    for f in functionList:
        register(f)

def start_notebook_on_demand(self, name, context):

        if self.is_running(name):

            last_context = self.get_context(name)
            logger.info("Notebook context change detected for %s", name)
            if not self.is_same_context(context, last_context):
                self.stop_notebook(name)
                # Make sure we don't get race condition over context.json file
                time.sleep(2.0)
            else:
                return last_context, False

        err_log = os.path.join(self.get_work_folder(name), "notebook.stderr.log")
        logger.info("Launching new Notebook named %s, context is %s", name, context)
        logger.info("Notebook log is %s", err_log)

        self.start_notebook(name, context)
        time.sleep(1)
        context = self.get_context(name)
        if "notebook_name" not in context:
            # Failed to launch within timeout
            raise RuntimeError("Failed to launch IPython Notebook, see {}".format(err_log))

        return context, True

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


Question:
Display the available data frame names in a given data frame collection

    :param dict d: Dataframe collection
    :return none:

def showDfs(d):

    if "metadata" in d:
        print("metadata")
    if "paleoData" in d:
        try:
            for k, v in d["paleoData"].items():
                print(k)
        except KeyError:
            pass
        except AttributeError:
            pass
    if "chronData" in d:
        try:
            for k, v in d["chronData"].items():
                print(k)
        except KeyError:
            pass
        except AttributeError:
            pass
    # print("Process Complete")
    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:
// Where adds an expression to the WHERE clause of the query. Expressions are
// ANDed together in the generated CQL.

func (b *UpdateBuilder) Where(w ...Cmp) *UpdateBuilder {
	b.where = append(b.where, w...)
	return b
}

public function contextHasMessages($context_data)
    {
        $qb2 = $this->_em->createQueryBuilder();
        $qb2->select('mc')
              ->from($this->_entityName, 'mc')
              ->where('mc.system = :system')
              ->andWhere('mc.object_name = :object_name')
              ->andWhere('mc.external_id = :external_id')
              ->setParameter("system", $context_data['system'])
              ->setParameter("object_name", $context_data['object_name'])
              ->setParameter("external_id", $context_data['external_id'])
              ->setMaxResults(1);

        $message_context = $qb2->getQuery()->getResult();
        return !empty($message_context);
    }

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