Question:
// WithTransactionContext returns a new context holding the provided
// bolt transaction. Functions which require a bolt transaction will
// first check to see if a transaction is already created on the
// context before creating their own.

func WithTransactionContext(ctx context.Context, tx *bolt.Tx) context.Context {
	return context.WithValue(ctx, transactionKey{}, tx)
}

def add_route(app_or_blueprint, fn, context=default_context):

    transmute_func = TransmuteFunction(
        fn,
        args_not_from_request=["request"]
    )
    handler = create_handler(transmute_func, context=context)
    get_swagger_spec(app_or_blueprint).add_func(transmute_func, context)
    for p in transmute_func.paths:
        sanic_path = _convert_to_sanic_path(p)
        app_or_blueprint.add_route(handler, sanic_path, methods=list(transmute_func.methods))

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


Question:
////////////////////////////////////////////////////////////
// This function pretty much attempts to mimic the parsing rules
// listed above at the start of this file

func getPatternFromLine(line string) (*regexp.Regexp, bool) {
	// Trim OS-specific carriage returns.
	line = strings.TrimRight(line, "\r")

	// Strip comments [Rule 2]
	if strings.HasPrefix(line, `#`) {
		return nil, false
	}

	// Trim string [Rule 3]
	// TODO: Handle [Rule 3], when the " " is escaped with a \
	line = strings.Trim(line, " ")

	// Exit for no-ops and return nil which will prevent us from
	// appending a pattern against this line
	if line == "" {
		return nil, false
	}

	// TODO: Handle [Rule 4] which negates the match for patterns leading with "!"
	negatePattern := false
	if line[0] == '!' {
		negatePattern = true
		line = line[1:]
	}

	// Handle [Rule 2, 4], when # or ! is escaped with a \
	// Handle [Rule 4] once we tag negatePattern, strip the leading ! char
	if regexp.MustCompile(`^(\#|\!)`).MatchString(line) {
		line = line[1:]
	}

	// If we encounter a foo/*.blah in a folder, prepend the / char
	if regexp.MustCompile(`([^\/+])/.*\*\.`).MatchString(line) && line[0] != '/' {
		line = "/" + line
	}

	// Handle escaping the "." char
	line = regexp.MustCompile(`\.`).ReplaceAllString(line, `\.`)

	magicStar := "#$~"

	// Handle "/**/" usage
	if strings.HasPrefix(line, "/**/") {
		line = line[1:]
	}
	line = regexp.MustCompile(`/\*\*/`).ReplaceAllString(line, `(/|/.+/)`)
	line = regexp.MustCompile(`\*\*/`).ReplaceAllString(line, `(|.`+magicStar+`/)`)
	line = regexp.MustCompile(`/\*\*`).ReplaceAllString(line, `(|/.`+magicStar+`)`)

	// Handle escaping the "*" char
	line = regexp.MustCompile(`\\\*`).ReplaceAllString(line, `\`+magicStar)
	line = regexp.MustCompile(`\*`).ReplaceAllString(line, `([^/]*)`)

	// Handle escaping the "?" char
	line = strings.Replace(line, "?", `\?`, -1)

	line = strings.Replace(line, magicStar, "*", -1)

	// Temporary regex
	var expr = ""
	if strings.HasSuffix(line, "/") {
		expr = line + "(|.*)$"
	} else {
		expr = line + "(|/.*)$"
	}
	if strings.HasPrefix(expr, "/") {
		expr = "^(|/)" + expr[1:]
	} else {
		expr = "^(|.*/)" + expr
	}
	pattern, _ := regexp.Compile(expr)

	return pattern, negatePattern
}

def clean_line_profile_text(text):

    #
    profile_block_list = parse_rawprofile_blocks(text)
    #profile_block_list = fix_rawprofile_blocks(profile_block_list)
    #---
    # FIXME can be written much nicer
    prefix_list, timemap = parse_timemap_from_blocks(profile_block_list)
    # Sort the blocks by time
    sorted_lists = sorted(six.iteritems(timemap), key=operator.itemgetter(0))
    newlist = prefix_list[:]
    for key, val in sorted_lists:
        newlist.extend(val)
    # Rejoin output text
    output_text = '\n'.join(newlist)
    #---
    # Hack in a profile summary
    summary_text = get_summary(profile_block_list)
    output_text = output_text
    return output_text, summary_text

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


Question:
https://github.com/thom311/libnl/blob/libnl3_2_25/lib/utils.c#L968.

    Positional arguments:
    type_ -- integer, key to lookup in `tbl`.
    buf -- bytearray().
    _ -- unused.
    tbl -- dict.

    Returns:
    Reference to `buf`.

def __type2str(type_, buf, _, tbl):

    del buf[:]
    if type_ in tbl:
        buf.extend(tbl[type_].encode('ascii'))
    else:
        buf.extend('0x{0:x}'.format(type_).encode('ascii'))
    return buf

def get_data(self):
        '''
        '''
        fifo_size = self._intf._get_tcp_data_size()
        fifo_int_size = int((fifo_size - (fifo_size % 4)) / 4)
        data = self._intf._get_tcp_data(fifo_int_size * 4)
        return np.frombuffer(data, dtype=np.dtype('<u4'))

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


Question:
Valida si en los headers existe el application/json
@return bool

private function isJsonRequest(): bool
    {

        if((request()->hasHeader('Content-Type') && 'application/json' == request()->header('Content-Type')) || (request()->hasHeader('accept') && request()->header('accept') == 'application/json') ){
            return true;
        }
        return false;
    }

public function finishNativeClientAuthorization($is_authorized, $params = [])
    {
        $result = [];
        $params += ['scope' => null, 'state' => null,];

        if ($params['state'] !== null) {
            $result["query"]["state"] = $params['state'] ;
        }

        if ($is_authorized === false) {
            $result["error"] = OAUTH2_ERROR_USER_DENIED;
        } else {
            if ($params['response_type'] === OAUTH2_AUTH_RESPONSE_TYPE_AUTH_CODE) {
                $result["code"] = $this->createAuthCode($params['account_id'], $params['redirect_uri'], $params['scope']);
            }

            if ($params['response_type'] === OAUTH2_AUTH_RESPONSE_TYPE_ACCESS_TOKEN) {
                $result["error"] = OAUTH2_ERROR_UNSUPPORTED_RESPONSE_TYPE;
            }
        }

        return $result;
    }

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


Question: // ListFunctions lists all functions in the process matching filter.

func (s *RPCServer) ListFunctions(arg ListFunctionsIn, out *ListFunctionsOut) error {
	fns, err := s.debugger.Functions(arg.Filter)
	if err != nil {
		return err
	}
	out.Funcs = fns
	return nil
}

func (c *Connect) LookupNWFilterByName(name string) (*NWFilter, error) {
	cName := C.CString(name)
	defer C.free(unsafe.Pointer(cName))
	var err C.virError
	ptr := C.virNWFilterLookupByNameWrapper(c.ptr, cName, &err)
	if ptr == nil {
		return nil, makeError(&err)
	}
	return &NWFilter{ptr: ptr}, nil
}

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


Question: // If current position matches input string, consumes it and returns true (else false)

func (l *lex) match(m string) bool {
	if !l.matchNoConsume(m) {
		return false
	}

	l.p += len(m)
	return true
}

private function getRealLinesAfterLastUse(int $lastUseEndPos): array
    {
        $file = $this->getFile();
        $tokens = $file->getTokens();
        $whitespaceEnd = TokenHelper::findNextExcluding($file, T_WHITESPACE, $lastUseEndPos + 1) - 1;

        if ($lastUseEndPos !== $whitespaceEnd && $tokens[$whitespaceEnd]['content'] !== $file->eolChar) {
            $lastEolPos = TokenHelper::findPreviousContent(
                $file,
                T_WHITESPACE,
                $file->eolChar,
                $whitespaceEnd - 1,
                $lastUseEndPos
            );
            $whitespaceEnd = $lastEolPos ?? $lastUseEndPos;
        }

        $whitespaceAfterLastUse = TokenHelper::getContent($file, $lastUseEndPos + 1, $whitespaceEnd);

        $realLinesAfterUse = substr_count($whitespaceAfterLastUse, $file->eolChar) - 1;

        return [$realLinesAfterUse, $whitespaceEnd];
    }

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


Question: // Check validate the password, and get the level.

func (s *Safety) Check(raw string) Level {
	l := len([]rune(raw))
	if l < s.ml {
		return Terrible
	}

	if s.isAsdf(raw) || s.isByStep(raw) {
		return Simple
	}

	if s.isCommonPassword(raw, s.mf) {
		return Simple
	}

	typ := 0

	if lower.MatchString(raw) {
		typ++
	}
	if upper.MatchString(raw) {
		typ++
	}
	if number.MatchString(raw) {
		typ++
	}
	if marks.MatchString(raw) {
		typ++
	}

	if l < 8 && typ == 2 {
		return Simple
	}

	if typ < s.mt {
		return Medium
	}

	return Strong
}

public static function makeAndValidate(array $data, array $rules = [], array $translates = [], string $scene = '')
    {
        return new static($data, $rules, $translates, $scene, true);
    }

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


Question:
/*
String[] validTypes = new String[]
{ "application/xhtml+xml",
"application/x-dtbncx+xml", "text/css" };

void buildCSSTypesDictionary()
  {
    String description;
    String value;
    TextSearchDictionaryEntry de;

    //search eval() expression
    description = "text/css";
    value = "text/css";
    de = new TextSearchDictionaryEntry(description, value, MessageId.CSS_009);
    v.add(de);

  }

public static void assertAccessibility(HtmlPage htmlPage, Testable testable) {
        assertThat(htmlPage, is(compliantTo(testable)));
    }

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


Question: Отправка вопросов заполненых клиентом

public function sendQuestions($data)
	{
		$mail = new MailHelper;

		$this->ips 			= $this->getIPs();
		$this->ip				= $this->getIP();
		$this->host 		= $this->getHOST();

		// Заголовок письма с датой
		$subject = date("d.m.y_G:i", strtotime($data['date']));
		// Подготовка тела письма
		$message = '';
		$message .= "Имя: $this->name\n\n";
		foreach ($data as $key => $value) {
			if (is_array($value)){
				$message .=	"Вопрос $key: ";
				$message .=  $value['question']."\n";
				$message .=  $value['answer']."\n";
			}
		}
		$message .= "\n";
		$message .= "ID клиента: ".$data['id'];
		$message .="\n\n\nВопросы были заполнены на сайте - $this->q_url";
		$message.= "\n\n\nВсе варианты ip: $this->q_ip\n";
		$message.= "\n http://sypexgeo.net/ru/demo/";
		$mail->mailSend($subject, $message);
	}

function (req, res) {
  return rp({
    method: 'POST',
    uri: config.LYFT_API_URI + '/oauth/token',
    auth: {
      username: config.LYFT_CLIENT_ID,
      password: (config.USE_SANDBOX ? 'SANDBOX-' : '') + config.LYFT_CLIENT_SECRET
    },
    json: {
      grant_type: 'client_credentials',
      scope: 'public'
    }
  })
}

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


Question:
Create collection

@param string $name
@param array  $options
@return array

public function createCollection($name, array $options = [])
    {
        if (isset($this->collections[$name])) {
            throw new RuntimeException('collection already exists');
        }

        $this->collections[$name] = [
            'collection' => new MockCollection($name, $this),
            'options' => $options
        ];

        return [
            'ok' => 1.0
        ];
    }

def getAlbumsForArtistInCollection(artist,user=nil,extras=nil)
      method = 'getAlbumsForArtistInCollection'
      type = Album
      args = {:artist=>artist}
      args[:user] = user if user
      args[:extras] = extras if extras
      auth = !!user
      return_object type,method,args,auth
    end

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


Question: // Handle handles the given binary payload.

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

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

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

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

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

	return buff.Bytes(), nil
}

func (eui *EUI64) UnmarshalBinary(data []byte) error {
	if len(data) != 8 {
		return errors.New("ttn/core: Invalid length for EUI64")
	}
	copy(eui[:], data)
	return nil
}

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


Question: // SetDPI sets the screen resolution in dots per inch.

func (rgc *RasterGraphicContext) SetDPI(dpi float64) {
	rgc.DPI = dpi
	rgc.recalc()
}

def resizeEvent(self, event):

        value = self.config.value
        self.idx_fig.fitInView(value['x_min'],
                               value['y_min'],
                               value['x_max'] - value['x_min'],
                               value['y_max'] - value['y_min'])

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


Question:
Resize an image to an exact width and height.

@param ImageInterface $image
@param string         $width
@param string         $height
@param bool           $enlarge

@return ImageInterface

protected function resizeExact(ImageInterface $image, $width, $height, $enlarge = true)
    {
        return $image->resize(new Box($width, $height));
    }

public function process(\Jb\Bundle\TagCloudBundle\Model\TagCloud $cloud)
    {
        foreach ($cloud as $tag) {
            $this->setPercentSize($tag, $cloud->getMax());
        }
    }

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


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

@Override
	public EClass getIfcPlate() {
		if (ifcPlateEClass == null) {
			ifcPlateEClass = (EClass) EPackage.Registry.INSTANCE.getEPackage(Ifc4Package.eNS_URI).getEClassifiers()
					.get(428);
		}
		return ifcPlateEClass;
	}

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

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

            config.script = wrapped_script

        return Container(config)

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


Question: Creates relations between words in a noun phrase

private void processWordsInNP(ArrayList<Pair<String>> wordsInPhrase) {
	if( wordsInPhrase.size() > 1 ) {
	    // this is from Grefenstette's pseudo code
	    for (int i = 0; i < wordsInPhrase.size()-1; i++) {

		if (inStartSet(wordsInPhrase.get(i).x) ) {

		    for (int j = i+1; j < wordsInPhrase.size(); j++ ) {

			if (inReceiveSet( wordsInPhrase.get(j).x ) ) {

			    wordRelationsWriter.
				println(wordsInPhrase.get(j).y + " "
					+ wordsInPhrase.get(i).y);

// 			    System.out.println(wordsInPhrase.get(j).y + " "
// 					       + wordsInPhrase.get(i).y);

			    addRelation(wordsInPhrase.get(j).y,
					wordsInPhrase.get(i).y);
			}
		    }
		}
	    }
	}
    }

def research_organism(soup):
    ""
    if not raw_parser.research_organism_keywords(soup):
        return []
    return list(map(node_text, raw_parser.research_organism_keywords(soup)))

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


Question:
find ANSI escape sequences in text and remove them

    :param text: str
    :return: list, should be passed to ListBox

def strip_from_ansi_esc_sequences(text):

    # esc[ + values + control character
    # h, l, p commands are complicated, let's ignore them
    seq_regex = r"\x1b\[[0-9;]*[mKJusDCBAfH]"
    regex = re.compile(seq_regex)
    start = 0
    response = ""
    for match in regex.finditer(text):
        end = match.start()
        response += text[start:end]

        start = match.end()
    response += text[start:len(text)]
    return response

def _rt_parse_execs(self, statement, element, mode, lineparser):
        """"""
        #This is the same deal as with _rt_parse_types() below.
        if mode == "insert":
            enew, start, end = self.xparser.parse_signature(statement, element, element)
            if enew is not None:
                enew.start, enew.end = lineparser.absolute_charindex(statement, start, end)
                enew.incomplete = True
                element.executables[enew.name.lower()] = enew
                lineparser.additions.append((enew, element))

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


Question: // GetLocalClusterName upserts local domain

func (s *PresenceService) GetLocalClusterName() (string, error) {
	item, err := s.Get(context.TODO(), backend.Key(localClusterPrefix, valPrefix))
	if err != nil {
		return "", trace.Wrap(err)
	}
	return string(item.Value), nil
}

def get_network_folder(dc_ref):
    '''

    '''
    dc_name = get_managed_object_name(dc_ref)
    log.trace('Retrieving network folder in datacenter \'%s\'', dc_name)
    service_instance = get_service_instance_from_managed_object(dc_ref)
    traversal_spec = vmodl.query.PropertyCollector.TraversalSpec(
        path='networkFolder',
        skip=False,
        type=vim.Datacenter)
    entries = get_mors_with_properties(service_instance,
                                       vim.Folder,
                                       container_ref=dc_ref,
                                       property_list=['name'],
                                       traversal_spec=traversal_spec)
    if not entries:
        raise salt.exceptions.VMwareObjectRetrievalError(
            'Network folder in datacenter \'{0}\' wasn\'t retrieved'
            ''.format(dc_name))
    return entries[0]['object']

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


Question:
Handle an incoming request.

@param Request  $request
@param \Closure $next

@return mixed

public function handle($request, Closure $next)
    {
        if (!$request->secure()) {
            $errorMessage = trans('LaravelHttps::laravel-https.messages.httpsRequredError').trans('LaravelHttps::laravel-https.messages.httpsRequred');
            $errorCode = config('LaravelHttps.httpsAccessDeniedErrorCode');

            if ($request->ajax() || $request->wantsJson()) {
                return Response::json([
                    'code'      => $errorCode,
                    'message'   => $errorMessage,
                ], $errorCode);
            }

            try {
                return response()->view('LaravelHttps::errors.'.$errorCode);
            } catch (Exception $e) {
                \App::abort($errorCode, $errorMessage);
            }
        }

        return $next($request);
    }

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

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

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

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

      sendRequest( :addReplaceDBPage, xmlRequestData )

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

      return self if @chainAPIcalls
      @pageid
    end

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


Question:
Send a curl request

@param  string $url   The url API
@param  array $params The query params
@return \Octopush\Client

public function request($url, array $params = [])
    {
        $curl = new Curl();
        $query = $this->buildQuery($params);
        $curl->setOptions($this->url . $url, $query, $this->port);
        $response = $curl->exec();
        $this->setResponse($response);
        $this->setErrors($response);
        return $this;
    }

protected function make($ctx)
    {
      // ENV or raw args
      if (!is_object($ctx)) {
        $this->user_id = $ctx['BANDWIDTH_USER_ID'];
        $this->token = $ctx['BANDWIDTH_API_TOKEN'];
        $this->secret = $ctx['BANDWIDTH_API_SECRET'];
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      } else {
        $this->user_id = $ctx->get('BANDWIDTH_USER_ID');
        $this->token = $ctx->get('BANDWIDTH_API_TOKEN');
        $this->secret = $ctx->get('BANDWIDTH_API_SECRET');
        $this->application_id = $ctx->get('BANDWIDTH_APPLICATION_ID');
      }

      if (!isset($this->user_id)
         ||!isset($this->token)
         ||!isset($this->secret))
              throw new \CatapultApiException("Credentials were improperly configured");

      $this->started = TRUE;

      return (self::$CLIENT = new RESTClient($this->user_id, array($this->token, $this->secret), $this->application_id));
    }

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


Question: // StartAutoLoadPolicy starts a go routine that will every specified duration call LoadPolicy

func (e *SyncedEnforcer) StartAutoLoadPolicy(d time.Duration) {
	e.autoLoad = true
	go func() {
		n := 1
		log.Print("Start automatically load policy")
		for {
			if !e.autoLoad {
				log.Print("Stop automatically load policy")
				break
			}

			// error intentionally ignored
			e.LoadPolicy()
			// Uncomment this line to see when the policy is loaded.
			// log.Print("Load policy for time: ", n)
			n++
			time.Sleep(d)
		}
	}()
}

func (wp *WorkerPool) JobWithOptions(name string, jobOpts JobOptions, fn interface{}) *WorkerPool {
	jobOpts = applyDefaultsAndValidate(jobOpts)

	vfn := reflect.ValueOf(fn)
	validateHandlerType(wp.contextType, vfn)
	jt := &jobType{
		Name:           name,
		DynamicHandler: vfn,
		JobOptions:     jobOpts,
	}
	if gh, ok := fn.(func(*Job) error); ok {
		jt.IsGeneric = true
		jt.GenericHandler = gh
	}

	wp.jobTypes[name] = jt

	for _, w := range wp.workers {
		w.updateMiddlewareAndJobTypes(wp.middleware, wp.jobTypes)
	}

	return wp
}

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


Question:
Extract XML element attributes form XML input stream
@param reader XML reader
@return {@code List} of {@code Attribute} items

private List<Attribute> getAttributes(XMLStreamReader reader) {
        List<Attribute> list = new ArrayList<Attribute>();
        for(int i=0; i<reader.getAttributeCount(); i++) {
            list.add(new Attribute(reader.getAttributeLocalName(i), reader.getAttributeValue(i)));
        }
        return list;
    }

public ArrayList<String> parseColumnNames()
  {
    ArrayList<String> columns = new ArrayList<String>();

    Token token = scanToken();
    if (token == Token.LPAREN) {
      do {
        columns.add(parseIdentifier());

        token = scanToken();
      } while (token == Token.COMMA);

      if (token != Token.RPAREN) {
        throw error("expected ')' at '{0}'", token);
      }
    }
    else if (token == Token.IDENTIFIER) {
      columns.add(_lexeme);

      _token = token;
    }
    else {
      throw error("expected '(' at '{0}'", token);
    }

    return columns;
  }

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


Question:
レスポンスを送信する

@param   ResponseInterface   $response

@return  void

private function emit(ResponseInterface $response){
        $params = [
            "start"     => null,
            "finish"    => null,
            "error"     => null,
        ];

        try{
            $params["start"]    = microtime(true);

            $this->emitter->emit($response);
        }catch(\Throwable $e){
            $params["error"]    = $e;
            $this->error        = $e;
        }finally{
            $params["finish"]   = microtime(true);
        }

        $this->event(new Event("response.emit.after", $params));
    }

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

        return;
    }

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


Question:
Generates the output.<p>

@throws IOException if something goes wrong

public void generateOutput() throws IOException {

        HttpServletResponse res = CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
        res.setContentType("application/octet-stream");
        res.setHeader(
            "Content-Disposition",
            new StringBuffer("attachment; filename=\"").append(getDownloadFile().getName()).append("\"").toString());
        res.setContentLength((int)getDownloadFile().length());

        // getOutputStream() throws IllegalStateException if the jsp directive buffer="none" is set.
        ServletOutputStream outStream = res.getOutputStream();
        InputStream in = new BufferedInputStream(new FileInputStream(getDownloadFile()));

        try {
            // don't write the last '-1'
            int bit = in.read();
            while ((bit) >= 0) {
                outStream.write(bit);
                bit = in.read();
            }
        } catch (SocketException soe) {
            // this is the case for ie if cancel in download window is chosen:
            // "Connection reset by peer: socket write error". But not for firefox -> don't care
        } finally {
            if (outStream != null) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (SocketException soe) {
                    // ignore
                }
            }
            in.close();
        }
    }

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


Question:
Index all forwards.

@param  int  $page
@return \Illuminate\Support\Collection

public function index($page = null)
    {
        $url = sprintf('buckets/%d/inboxes/%d/forwards.json', $this->bucket, $this->parent);

        $forwards = $this->client->get($url, [
            'query' => [
                'page' => $page,
            ]
        ]);

        return $this->indexResponse($forwards, Forward::class);
    }

function PageResultInfinite(items, totalCount, requestIndex, nextIndex, baseUrl) {
      this.items = items != null ? items : [];
      this.totalCount = totalCount != null ? totalCount : 0;
      this.requestIndex = requestIndex;
      this.nextIndex = nextIndex != null ? nextIndex : null;
      this.baseUrl = baseUrl != null ? baseUrl : null;
      this.toRest = __bind(this.toRest, this);

    }

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


Question:
/* (non-Javadoc)
@see cyclops2.async.wait.WaitStrategy#offer(cyclops2.async.wait.WaitStrategy.Offerable)

@Override
    public boolean offer(final com.oath.cyclops.async.wait.WaitStrategy.Offerable o) throws InterruptedException {
        return o.offer();
    }

Scope enterScope() {
    final Map<VarKey, Variable> currentFrame = new LinkedHashMap<>();
    final Label scopeExit = new Label();
    frames.push(currentFrame);
    return new Scope() {
      boolean exited;

      @Override
      Variable createSynthetic(
          SyntheticVarName varName, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.SYNTHETIC, varName.name());
        // synthetics are prefixed by $ by convention
        String name = fieldNames.generateName("$" + varName.name());
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Variable createTemporary(String name, Expression initExpr) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.TEMPORARY, name);
        name = fieldNames.generateName("$$" + name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, SaveStrategy.NEVER);
      }

      @Override
      Variable create(String name, Expression initExpr, SaveStrategy strategy) {
        checkState(!exited, "Scope already exited");
        VarKey key = VarKey.create(Kind.USER_DEFINED, name);
        name = fieldNames.generateName(name);
        return doCreate(name, new Label(), scopeExit, initExpr, key, strategy);
      }

      @Override
      Statement exitScope() {
        checkState(!exited, "Scope already exited");
        exited = true;
        frames.pop();
        // Use identity semantics to make sure we visit each label at most once.  visiting a label
        // more than once tends to corrupt internal asm state.
        final Set<Label> endLabels = Sets.newIdentityHashSet();
        for (Variable var : currentFrame.values()) {
          endLabels.add(var.local.end());
          availableSlots.clear(
              var.local.index(), var.local.index() + var.local.resultType().getSize());
        }
        return new Statement() {
          // TODO(lukes): we could generate null writes for when object typed fields go out of
          // scope.  This would potentially allow intermediate results to be collected sooner.
          @Override
          protected void doGen(CodeBuilder adapter) {
            for (Label label : endLabels) {
              adapter.visitLabel(label);
            }
          }
        };
      }

      private Variable doCreate(
          String name,
          Label start,
          Label end,
          Expression initExpr,
          VarKey key,
          SaveStrategy strategy) {
        int index = reserveSlotFor(initExpr.resultType());
        LocalVariable local =
            LocalVariable.createLocal(name, index, initExpr.resultType(), start, end);
        Variable var;
        switch (strategy) {
          case DERIVED:
            var = new DerivedVariable(initExpr, local);
            break;
          case NEVER:
            var = new TemporaryVariable(initExpr, local);
            break;
          case STORE:
            var = new FieldSavedVariable(initExpr, local);
            break;
          default:
            throw new AssertionError();
        }
        currentFrame.put(key, var);
        allVariables.add(var);
        return var;
      }
    };
  }

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


Question:
Check if current position is valid.

@return boolean

public function valid()
    {
        return isset($this->base['value'][$this->position]) && is_array($this->base['value'][$this->position]);
    }

def bound(val)
    case val
    when Rectangle then
      r = val.clone
      r.size = r.size.min(size)
      r.loc = r.loc.bound(loc, loc + size - val.size)
      r
    when Point then (val-loc).bound(point, size) + loc
    else raise ArgumentError.new("wrong type: (#{val.class}) - Rectangle or Point expected")
    end
  end

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


Question:
Returns database server info array
@return array Array containing 'description' and 'version' info

public function get_server_info() {
        static $info = null; // TODO: move to real object property

        if (is_null($info)) {
            $this->query_start("--oci_server_version()", null, SQL_QUERY_AUX);
            $description = oci_server_version($this->oci);
            $this->query_end(true);
            preg_match('/(\d+\.)+\d+/', $description, $matches);
            $info = array('description'=>$description, 'version'=>$matches[0]);
        }

        return $info;
    }

func (_m *DBClient) GetDeviceProfilesWithLabel(l string) ([]models.DeviceProfile, error) {
	ret := _m.Called(l)

	var r0 []models.DeviceProfile
	if rf, ok := ret.Get(0).(func(string) []models.DeviceProfile); ok {
		r0 = rf(l)
	} else {
		if ret.Get(0) != nil {
			r0 = ret.Get(0).([]models.DeviceProfile)
		}
	}

	var r1 error
	if rf, ok := ret.Get(1).(func(string) error); ok {
		r1 = rf(l)
	} else {
		r1 = ret.Error(1)
	}

	return r0, r1
}

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


Question:
Create a dated event.

@param family the family the event is for
@param type the type of event
@param dateString the date of the event
@return the created event

public Attribute createFamilyEvent(final Family family, final String type,
            final String dateString) {
        if (family == null || type == null || dateString == null) {
            return gedObjectBuilder.createAttribute();
        }
        final Attribute event = gedObjectBuilder.createAttribute(family, type);
        event.insert(new Date(event, dateString));
        return event;
    }

public void marshall(ChildWorkflowExecutionCompletedEventAttributes childWorkflowExecutionCompletedEventAttributes, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(childWorkflowExecutionCompletedEventAttributes.getWorkflowExecution(), WORKFLOWEXECUTION_BINDING);
            protocolMarshaller.marshall(childWorkflowExecutionCompletedEventAttributes.getWorkflowType(), WORKFLOWTYPE_BINDING);
            protocolMarshaller.marshall(childWorkflowExecutionCompletedEventAttributes.getResult(), RESULT_BINDING);
            protocolMarshaller.marshall(childWorkflowExecutionCompletedEventAttributes.getInitiatedEventId(), INITIATEDEVENTID_BINDING);
            protocolMarshaller.marshall(childWorkflowExecutionCompletedEventAttributes.getStartedEventId(), STARTEDEVENTID_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

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


Question: Return the default bundle config file as an AttrDict.

def default_bundle_config():
    """"""

    import os
    from ambry.util import AttrDict

    config = AttrDict()
    f = os.path.join(
        os.path.dirname(
            os.path.realpath(__file__)),
        'bundle.yaml')

    config.update_yaml(f)

    return config

def scan_django_settings(values, imports):
    '''
    '''
    if isinstance(values, (str, bytes)):
        if utils.is_import_str(values):
            imports.add(values)
    elif isinstance(values, dict):
        for k, v in values.items():
            scan_django_settings(k, imports)
            scan_django_settings(v, imports)
    elif hasattr(values, '__file__') and getattr(values, '__file__'):
        imp, _ = utils.import_path_from_file(getattr(values, '__file__'))
        imports.add(imp)
    elif hasattr(values, '__iter__'):
        for item in values:
            scan_django_settings(item, imports)

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


Question: // SetVpcId sets the VpcId field's value.

func (s *Stack) SetVpcId(v string) *Stack {
	s.VpcId = &v
	return s
}

func (u *FakeAPIUtil) GetAndResetCreatedPVs() map[string]*v1.PersistentVolume {
	createdPVs := u.createdPVs
	u.createdPVs = map[string]*v1.PersistentVolume{}
	return createdPVs
}

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


Question:
Creates an array of elements, sorted in specified order by the results
of running each element in a collection thru each iteratee.

function orderBy(collection, keys, directions) {
    var index = -1;
    var result = collection.map(function (value) {
        var criteria = keys.map(function (key) { return value[key]; });
        return { criteria: criteria, index: ++index, value: value };
    });
    return baseSortBy(result, function (object, other) {
        return compareMultiple(object, other, directions);
    });
}

private void setUpIteration(DeltaIteration<?, ?> iteration) {

		// set up the iteration operator
		if (this.configuration != null) {

			iteration.name(this.configuration.getName("Vertex-centric iteration (" + computeFunction + ")"));
			iteration.parallelism(this.configuration.getParallelism());
			iteration.setSolutionSetUnManaged(this.configuration.isSolutionSetUnmanagedMemory());

			// register all aggregators
			for (Map.Entry<String, Aggregator<?>> entry : this.configuration.getAggregators().entrySet()) {
				iteration.registerAggregator(entry.getKey(), entry.getValue());
			}
		}
		else {
			// no configuration provided; set default name
			iteration.name("Vertex-centric iteration (" + computeFunction + ")");
		}
	}

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


Question:
Carga cada una de las dependencias indicadas en su correspondiente propiedad del objeto
Esta funcion supone que las Clases de las dependencias ya se encuentran importadas.
@param type $object
@param array $dependencies

public function injectDependencies($object, array $dependencies){
        $dependenciesDefinition= $this->dependencies;
        //Recorre las dependencias indicadas y las que existe las carga
        foreach ($dependencies as $property => $dependencyName) {
            if(isset($dependenciesDefinition[$dependencyName])){
                $dependency= $dependenciesDefinition[$dependencyName];
                $this->loadDependencyInObject($object, $property, $dependencyName, $dependency);
            }
        }
    }

private function initFieldsTypes()
    {
        $this->fieldTypes = [];

        $fieldTypes = $this->loadFieldTypes();

        foreach ($fieldTypes as $fieldType) {
            if (!$fieldType instanceof FieldTypeInterface) {
                throw new DataSourceException(sprintf('Expected instance of FieldTypeInterface, "%s" given.', get_class($fieldType)));
            }

            if (isset($this->fieldTypes[$fieldType->getType()])) {
                throw new DataSourceException(sprintf('Error during field types loading. Name "%s" already in use.', $fieldType->getType()));
            }

            $this->fieldTypes[$fieldType->getType()] = $fieldType;
        }
    }

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


Question:
Zwraca drzewo kategorii
@param integer $parentCategoryId identyfikator kategorii rodzica (opcjonalny)
@return array

public function getCategoryTree($parentCategoryId = null)
    {
        //brak zdefiniowanej kategorii
        if ($parentCategoryId === null) {
            return $this->_categoryTree;
        }
        //wyszukiwanie kategorii
        return $this->_searchChildren($this->_categoryTree, $parentCategoryId);
    }

public function store(Request $request)
    {
        $category = $this->api('category.fetch', $request->route('category'))->get();

        if (!$category->threadsEnabled) {
            Forum::alert('warning', 'categories.threads_disabled');

            return redirect(Forum::route('category.show', $category));
        }

        $thread = [
            'author_id'     => auth()->user()->getKey(),
            'category_id'   => $category->id,
            'title'         => $request->input('title'),
            'content'       => $request->input('content')
        ];

        $thread = $this->api('thread.store')->parameters($thread)->post();

        Forum::alert('success', 'threads.created');

        return redirect(Forum::route('thread.show', $thread));
    }

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


Question:
Assert that the Vue component's attribute at the given key
is an array that contains the given value.

@param  string  $key
@param  string  $value
@param  string|null  $componentSelector
@return $this

public function assertVueContains($key, $value, $componentSelector = null)
    {
        $attribute = $this->vueAttribute($componentSelector, $key);

        PHPUnit::assertIsArray($attribute, "The attribute for key [$key] is not an array.");
        PHPUnit::assertContains($value, $attribute);

        return $this;
    }

function getVariables(spec_c, parent) {
  var spec_js = {};
  var vars = _.find(getChildren(spec_c, 'sectiondef'), function(section) {
    var kind = getAttr(section, 'kind');
    return (kind == 'public-attrib');
  });
  if (vars) {
    _.each(_.filter(vars.children, function(variable) {
      return (getAttr(variable, 'kind') == 'variable');
    }), function(variable) {
      var varName = getText(getChild(variable, 'name'), 'name');
      var varType = getType(getText(getChild(variable, 'type')), parent);
      var varDescription = getText(getChild(variable, 'detaileddescription'));
      spec_js[varName] = {
        type: varType,
        description: varDescription
      }
    });
  }
  return spec_js;
}

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


Question: ---------------------------------------------------------- Getters and Setters end

@Override
	public void render() {
		if (false == HuluSetting.isDevMode) {
			Response.sendError(this.errorCode, this.errorContent);
			return;
		}

		if (null != e) {
			StaticLog.error(e);
			if (null == this.errorContent) {
				this.errorContent = StrUtil.EMPTY;
			}
			String stacktraceContent = ExceptionUtil.stacktraceToString(e)
					.replace("\tat", "    \tat")
					.replace("\n", "<br/>\n");
			this.errorContent = StrUtil.format(TEMPLATE_ERROR, this.getErrorCode(), Request.getServletRequest().getRequestURI(), this.errorContent, stacktraceContent);
		}

		Response.setStatus(errorCode);
		Response.write(errorContent, Response.CONTENT_TYPE_HTML);
	}

def _get_action_endpoint(action):

    _endpoint = None
    if is_method(action):
        if hasattr(action, "_rule_cache"):
            rc = action._rule_cache
            if rc:
                k = list(rc.keys())[0]
                rules = rc[k]
                len_rules = len(rules)
                if len_rules == 1:
                    rc_kw = rules[0][1]
                    _endpoint = rc_kw.get("endpoint", None)
                    if not _endpoint:
                        _endpoint = _build_endpoint_route_name(action)
                elif len_rules > 1:
                    _prefix = _build_endpoint_route_name(action)
                    for r in Mocha._app.url_map.iter_rules():
                        if ('GET' in r.methods or 'POST' in r.methods) \
                                and _prefix in r.endpoint:
                            _endpoint = r.endpoint
                            break
    return _endpoint

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


Question: // Replay replays the batch contents.

func (b *batch) Replay(w ethdb.Writer) error {
	return b.b.Replay(&replayer{writer: w})
}

def _reset(self):

        self.commands = []
        self.watching = False
        self._watched_keys = {}
        self.explicit_transaction = False

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


Question:
Call the pg_dump command to create a db backup

        Parameters
        ----------
        pg_dump_exe: str
            the pg_dump command path
        exclude_schema: str[]
            list of schemas to be skipped

def pg_backup(self, pg_dump_exe='pg_dump', exclude_schema=None):

        command = [
            pg_dump_exe, '-Fc', '-f', self.file,
            'service={}'.format(self.pg_service)
            ]
        if exclude_schema:
            command.append(' '.join("--exclude-schema={}".format(schema) for schema in exclude_schema))

        subprocess.check_output(command, stderr=subprocess.STDOUT)

def retrieve_all_quiz_reports(self, quiz_id, course_id, includes_all_versions=None):

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

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

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

        # OPTIONAL - includes_all_versions
        """Whether to retrieve reports that consider all the submissions or only
        the most recent. Defaults to false, ignored for item_analysis reports."""
        if includes_all_versions is not None:
            params["includes_all_versions"] = includes_all_versions

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

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


Question:
returns the named queries stored in the database.
        :rtype: dict (str -> str) mapping alias to full query string

def get_named_queries(self):

        db = Database(path=self.path)
        return {k[6:]: v for k, v in db.get_configs('query.')}

def _generate_reversed_sql(self, keys, changed_keys):

        for key in keys:
            if key not in changed_keys:
                continue
            app_label, sql_name = key
            old_item = self.from_sql_graph.nodes[key]
            new_item = self.to_sql_graph.nodes[key]
            if not old_item.reverse_sql or old_item.reverse_sql == RunSQL.noop or new_item.replace:
                continue

            # migrate backwards
            operation = ReverseAlterSQL(sql_name, old_item.reverse_sql, reverse_sql=old_item.sql)
            sql_deps = [n.key for n in self.from_sql_graph.node_map[key].children]
            sql_deps.append(key)
            self.add_sql_operation(app_label, sql_name, operation, sql_deps)

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


Question:
Loads PHPExcel from file into PHPExcel instance

@param 	string 		$pFilename
@param	PHPExcel	$objPHPExcel
@return 	PHPExcel
@throws 	PHPExcel_Reader_Exception

public function loadIntoExisting($pFilename, PHPExcel $objPHPExcel)
	{
		// Check if file exists
		if (!file_exists($pFilename)) {
			throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! File does not exist.");
		}

		$timezoneObj = new DateTimeZone('Europe/London');
		$GMT = new DateTimeZone('UTC');

		$zip = new ZipArchive;
		if (!$zip->open($pFilename)) {
			throw new PHPExcel_Reader_Exception("Could not open " . $pFilename . " for reading! Error opening file.");
		}

//		echo '
Meta Information
';
		$xml = simplexml_load_string($zip->getFromName("meta.xml"));
		$namespacesMeta = $xml->getNamespaces(true);
//		echo '
';
//		print_r($namespacesMeta);
//		echo '

';

		$docProps = $objPHPExcel->getProperties();
		$officeProperty = $xml->children($namespacesMeta['office']);
		foreach($officeProperty as $officePropertyData) {
			$officePropertyDC = array();
			if (isset($namespacesMeta['dc'])) {
				$officePropertyDC = $officePropertyData->children($namespacesMeta['dc']);
			}
			foreach($officePropertyDC as $propertyName => $propertyValue) {
				switch ($propertyName) {
					case 'title' :
							$docProps->setTitle($propertyValue);
							break;
					case 'subject' :
							$docProps->setSubject($propertyValue);
							break;
					case 'creator' :
							$docProps->setCreator($propertyValue);
							$docProps->setLastModifiedBy($propertyValue);
							break;
					case 'date' :
							$creationDate = strtotime($propertyValue);
							$docProps->setCreated($creationDate);
							$docProps->setModified($creationDate);
							break;
					case 'description' :
							$docProps->setDescription($propertyValue);
							break;
				}
			}
			$officePropertyMeta = array();
			if (isset($namespacesMeta['dc'])) {
				$officePropertyMeta = $officePropertyData->children($namespacesMeta['meta']);
			}
			foreach($officePropertyMeta as $propertyName => $propertyValue) {
				$propertyValueAttributes = $propertyValue->attributes($namespacesMeta['meta']);
				switch ($propertyName) {
					case 'initial-creator' :
							$docProps->setCreator($propertyValue);
							break;
					case 'keyword' :
							$docProps->setKeywords($propertyValue);
							break;
					case 'creation-date' :
							$creationDate = strtotime($propertyValue);
							$docProps->setCreated($creationDate);
							break;
					case 'user-defined' :
							$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
							foreach ($propertyValueAttributes as $key => $value) {
								if ($key == 'name') {
									$propertyValueName = (string) $value;
								} elseif($key == 'value-type') {
									switch ($value) {
										case 'date'	:
											$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'date');
											$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_DATE;
											break;
										case 'boolean'	:
											$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'bool');
											$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_BOOLEAN;
											break;
										case 'float'	:
											$propertyValue = PHPExcel_DocumentProperties::convertProperty($propertyValue,'r4');
											$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_FLOAT;
											break;
										default :
											$propertyValueType = PHPExcel_DocumentProperties::PROPERTY_TYPE_STRING;
									}
								}
							}
							$docProps->setCustomProperty($propertyValueName,$propertyValue,$propertyValueType);
							break;
				}
			}
		}

//		echo '
Workbook Content
';
		$xml = simplexml_load_string($zip->getFromName("content.xml"));
		$namespacesContent = $xml->getNamespaces(true);
//		echo '
';
//		print_r($namespacesContent);
//		echo '

';

		$workbook = $xml->children($namespacesContent['office']);
		foreach($workbook->body->spreadsheet as $workbookData) {
			$workbookData = $workbookData->children($namespacesContent['table']);
			$worksheetID = 0;
			foreach($workbookData->table as $worksheetDataSet) {
				$worksheetData = $worksheetDataSet->children($namespacesContent['table']);
//				print_r($worksheetData);
//				echo '
';
				$worksheetDataAttributes = $worksheetDataSet->attributes($namespacesContent['table']);
//				print_r($worksheetDataAttributes);
//				echo '
';
				if ((isset($this->_loadSheetsOnly)) && (isset($worksheetDataAttributes['name'])) &&
					(!in_array($worksheetDataAttributes['name'], $this->_loadSheetsOnly))) {
					continue;
				}

//				echo '
Worksheet '.$worksheetDataAttributes['name'].'
';
				// Create new Worksheet
				$objPHPExcel->createSheet();
				$objPHPExcel->setActiveSheetIndex($worksheetID);
				if (isset($worksheetDataAttributes['name'])) {
					$worksheetName = (string) $worksheetDataAttributes['name'];
					//	Use false for $updateFormulaCellReferences to prevent adjustment of worksheet references in
					//		formula cells... during the load, all formulae should be correct, and we're simply
					//		bringing the worksheet name in line with the formula, not the reverse
					$objPHPExcel->getActiveSheet()->setTitle($worksheetName,false);
				}

				$rowID = 1;
				foreach($worksheetData as $key => $rowData) {
//					echo ''.$key.'
';
					switch ($key) {
						case 'table-header-rows':
							foreach ($rowData as $key=>$cellData) {
								$rowData = $cellData;
								break;
							}
						case 'table-row' :
							$rowDataTableAttributes = $rowData->attributes($namespacesContent['table']);
							$rowRepeats = (isset($rowDataTableAttributes['number-rows-repeated'])) ?
									$rowDataTableAttributes['number-rows-repeated'] : 1;
							$columnID = 'A';
							foreach($rowData as $key => $cellData) {
								if ($this->getReadFilter() !== NULL) {
									if (!$this->getReadFilter()->readCell($columnID, $rowID, $worksheetName)) {
										continue;
									}
								}

//								echo ''.$columnID.$rowID.'
';
								$cellDataText = (isset($namespacesContent['text'])) ?
									$cellData->children($namespacesContent['text']) :
									'';
								$cellDataOffice = $cellData->children($namespacesContent['office']);
								$cellDataOfficeAttributes = $cellData->attributes($namespacesContent['office']);
								$cellDataTableAttributes = $cellData->attributes($namespacesContent['table']);

//								echo 'Office Attributes: ';
//								print_r($cellDataOfficeAttributes);
//								echo '
Table Attributes: ';
//								print_r($cellDataTableAttributes);
//								echo '
Cell Data Text';
//								print_r($cellDataText);
//								echo '
';
//
								$type = $formatting = $hyperlink = null;
								$hasCalculatedValue = false;
								$cellDataFormula = '';
								if (isset($cellDataTableAttributes['formula'])) {
									$cellDataFormula = $cellDataTableAttributes['formula'];
									$hasCalculatedValue = true;
								}

								if (isset($cellDataOffice->annotation)) {
//									echo 'Cell has comment
';
									$annotationText = $cellDataOffice->annotation->children($namespacesContent['text']);
									$textArray = array();
									foreach($annotationText as $t) {
										foreach($t->span as $text) {
											$textArray[] = (string)$text;
										}
									}
									$text = implode("\n",$textArray);
//									echo $text,'
';
									$objPHPExcel->getActiveSheet()->getComment( $columnID.$rowID )
//																	->setAuthor( $author )
																	->setText($this->_parseRichText($text) );
								}

									if (isset($cellDataText->p)) {
									// Consolidate if there are multiple p records (maybe with spans as well)
									$dataArray = array();
									// Text can have multiple text:p and within those, multiple text:span.
									// text:p newlines, but text:span does not.
									// Also, here we assume there is no text data is span fields are specified, since
									// we have no way of knowing proper positioning anyway.
									foreach ($cellDataText->p as $pData) {
										if (isset($pData->span)) {
											// span sections do not newline, so we just create one large string here
											$spanSection = "";
											foreach ($pData->span as $spanData) {
												$spanSection .= $spanData;
											}
											array_push($dataArray, $spanSection);
										} else {
											array_push($dataArray, $pData);
										}
									}
									$allCellDataText = implode($dataArray, "\n");

//									echo 'Value Type is '.$cellDataOfficeAttributes['value-type'].'
';
									switch ($cellDataOfficeAttributes['value-type']) {
 										case 'string' :
												$type = PHPExcel_Cell_DataType::TYPE_STRING;
												$dataValue = $allCellDataText;
												if (isset($dataValue->a)) {
													$dataValue = $dataValue->a;
													$cellXLinkAttributes = $dataValue->attributes($namespacesContent['xlink']);
													$hyperlink = $cellXLinkAttributes['href'];
												}
												break;
										case 'boolean' :
												$type = PHPExcel_Cell_DataType::TYPE_BOOL;
												$dataValue = ($allCellDataText == 'TRUE') ? True : False;
												break;
										case 'percentage' :
												$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
												$dataValue = (float) $cellDataOfficeAttributes['value'];
												if (floor($dataValue) == $dataValue) {
													$dataValue = (integer) $dataValue;
												}
												$formatting = PHPExcel_Style_NumberFormat::FORMAT_PERCENTAGE_00;
												break;
										case 'currency' :
												$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
												$dataValue = (float) $cellDataOfficeAttributes['value'];
												if (floor($dataValue) == $dataValue) {
													$dataValue = (integer) $dataValue;
												}
												$formatting = PHPExcel_Style_NumberFormat::FORMAT_CURRENCY_USD_SIMPLE;
												break;
										case 'float' :
												$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
												$dataValue = (float) $cellDataOfficeAttributes['value'];
												if (floor($dataValue) == $dataValue) {
													if ($dataValue = (integer) $dataValue)
														$dataValue = (integer) $dataValue;
													else
														$dataValue = (float) $dataValue;
												}
												break;
										case 'date' :
												$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
											    $dateObj = new DateTime($cellDataOfficeAttributes['date-value'], $GMT);
												$dateObj->setTimeZone($timezoneObj);
												list($year,$month,$day,$hour,$minute,$second) = explode(' ',$dateObj->format('Y m d H i s'));
												$dataValue = PHPExcel_Shared_Date::FormattedPHPToExcel($year,$month,$day,$hour,$minute,$second);
												if ($dataValue != floor($dataValue)) {
													$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15.' '.PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
												} else {
													$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX15;
												}
												break;
										case 'time' :
												$type = PHPExcel_Cell_DataType::TYPE_NUMERIC;
												$dataValue = PHPExcel_Shared_Date::PHPToExcel(strtotime('01-01-1970 '.implode(':',sscanf($cellDataOfficeAttributes['time-value'],'PT%dH%dM%dS'))));
												$formatting = PHPExcel_Style_NumberFormat::FORMAT_DATE_TIME4;
												break;
									}
//									echo 'Data value is '.$dataValue.'
';
//									if ($hyperlink !== NULL) {
//										echo 'Hyperlink is '.$hyperlink.'
';
//									}
								} else {
									$type = PHPExcel_Cell_DataType::TYPE_NULL;
									$dataValue = NULL;
								}

								if ($hasCalculatedValue) {
									$type = PHPExcel_Cell_DataType::TYPE_FORMULA;
//									echo 'Formula: '.$cellDataFormula.'
';
									$cellDataFormula = substr($cellDataFormula,strpos($cellDataFormula,':=')+1);
									$temp = explode('"',$cellDataFormula);
									$tKey = false;
									foreach($temp as &$value) {
										//	Only replace in alternate array entries (i.e. non-quoted blocks)
										if ($tKey = !$tKey) {
											$value = preg_replace('/\[\.(.*):\.(.*)\]/Ui','$1:$2',$value);
											$value = preg_replace('/\[\.(.*)\]/Ui','$1',$value);
											$value = PHPExcel_Calculation::_translateSeparator(';',',',$value,$inBraces);
										}
									}
									unset($value);
									//	Then rebuild the formula string
									$cellDataFormula = implode('"',$temp);
//									echo 'Adjusted Formula: '.$cellDataFormula.'
';
								}

								$colRepeats = (isset($cellDataTableAttributes['number-columns-repeated'])) ?
									$cellDataTableAttributes['number-columns-repeated'] : 1;
								if ($type !== NULL) {
									for ($i = 0; $i < $colRepeats; ++$i) {
										if ($i > 0) {
											++$columnID;
										}
										if ($type !== PHPExcel_Cell_DataType::TYPE_NULL) {
											for ($rowAdjust = 0; $rowAdjust < $rowRepeats; ++$rowAdjust) {
												$rID = $rowID + $rowAdjust;
												$objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setValueExplicit((($hasCalculatedValue) ? $cellDataFormula : $dataValue),$type);
												if ($hasCalculatedValue) {
//													echo 'Forumla result is '.$dataValue.'
';
													$objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->setCalculatedValue($dataValue);
												}
												if ($formatting !== NULL) {
													$objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode($formatting);
												} else {
													$objPHPExcel->getActiveSheet()->getStyle($columnID.$rID)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_GENERAL);
												}
												if ($hyperlink !== NULL) {
													$objPHPExcel->getActiveSheet()->getCell($columnID.$rID)->getHyperlink()->setUrl($hyperlink);
												}
											}
										}
									}
								}

								//	Merged cells
								if ((isset($cellDataTableAttributes['number-columns-spanned'])) || (isset($cellDataTableAttributes['number-rows-spanned']))) {
									if (($type !== PHPExcel_Cell_DataType::TYPE_NULL) || (!$this->_readDataOnly)) {
										$columnTo = $columnID;
										if (isset($cellDataTableAttributes['number-columns-spanned'])) {
											$columnTo = PHPExcel_Cell::stringFromColumnIndex(PHPExcel_Cell::columnIndexFromString($columnID) + $cellDataTableAttributes['number-columns-spanned'] -2);
										}
										$rowTo = $rowID;
										if (isset($cellDataTableAttributes['number-rows-spanned'])) {
											$rowTo = $rowTo + $cellDataTableAttributes['number-rows-spanned'] - 1;
										}
										$cellRange = $columnID.$rowID.':'.$columnTo.$rowTo;
										$objPHPExcel->getActiveSheet()->mergeCells($cellRange);
									}
								}

								++$columnID;
							}
							$rowID += $rowRepeats;
							break;
					}
				}
				++$worksheetID;
			}
		}

		// Return
		return $objPHPExcel;
	}

private function _mysqli()
    {
        if (!isset($this->_link)) {
            mysqli_report(MYSQLI_REPORT_OFF);

            if(!$this->_link = mysqli_init())
                throw new Exception("Mysql initialization failed");

            $sqlMode = $this->_strict ? 'TRADITIONAL' : '';
            $this->_link->options(MYSQLI_INIT_COMMAND, "SET SESSION sql_mode = '{$sqlMode}'");
            $this->_link->options(MYSQLI_OPT_CONNECT_TIMEOUT, 5);

            @$this->_link->real_connect(
                $this->_dsn->host, $this->_dsn->user, $this->_dsn->pass,
                $this->_dsn->database, $this->_dsn->port
            );

            if ($this->_link->connect_error)
                throw new Exception("Failed to connect to mysql: {$this->_link->connect_error}", $this->_link->connect_errno);

            if (!$this->_link->set_charset($this->_charset))
                throw new Exception(sprintf("Error setting character to %s: %s", $this->_charset, $this->_link->error));
        }

        return $this->_link;
    }

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


Question:
@param string $title

@return TabInterface|null

public function getTabByTitle($title)
    {
        foreach ($this->tabs as $key => $tab) {
            if ($tab->getTitle() === $title) {
                return $this->tabs[$key];
            }
        }

        return null;
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question: // Like findRegionalDiskByName, but returns an error if the disk is not found

func (g *Cloud) getRegionalDiskByName(diskName string) (*Disk, error) {
	disk, err := g.findRegionalDiskByName(diskName)
	if disk == nil && err == nil {
		return nil, fmt.Errorf("GCE regional persistent disk not found: diskName=%q", diskName)
	}
	return disk, err
}

function(cb) {
            fs.exists(potterHome, function(exists) {
                if(exists) {
                    cb(null);
                } else {
                    mkdirp(potterHome, cb);
                }
            });
        }

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


Question: Disable automatic corrections and completions.

def build_attrs(self, *args, **kwargs):
        """"""
        attrs = super(CaptchaAnswerInput, self).build_attrs(*args, **kwargs)
        attrs['autocapitalize'] = 'off'
        attrs['autocomplete'] = 'off'
        attrs['autocorrect'] = 'off'
        attrs['spellcheck'] = 'false'
        return attrs

def check(self, text):

        for word, pos in self.tokenizer(text):
            correct = self.dictionary.check(word)
            if correct:
                continue
            yield word, self.dictionary.suggest(word) if self.suggest else []
        return

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


Question:
Compute the bubble representation of given power graph,
    and push it into given file.

def tree_to_file(tree:'BubbleTree', outfile:str):
    """"""
    with open(outfile, 'w') as fd:
        fd.write(tree_to_bubble(tree))

def report(bump_info)
      bump_info.update_rules.each do |rule|
        log rule.file.to_s
        log '  Performed pattern replacement:'
        log_green "    '#{rule.before_pattern}' => '#{rule.after_pattern}'"
        log
      end
    end

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


Question:
// Alive returns whether the key is currently considered alive by w,
// or an error in case the watcher is dying.

func (w *Watcher) Alive(key string) (bool, error) {
	result := make(chan bool, 1)
	w.sendReq(reqAlive{key, result})
	var alive bool
	select {
	case alive = <-result:
	case <-w.tomb.Dying():
		return false, errors.Errorf("cannot check liveness: watcher is dying")
	}
	logger.Tracef("[%s] Alive(%q) -> %v", w.modelUUID[:6], key, alive)
	return alive, nil
}

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

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

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

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

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

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


Question:
synchronize state with the blockchain.
    Return True on success
    Return False if we're supposed to stop indexing
    Abort on error

def sync_blockchain( working_dir, bt_opts, last_block, server_state, expected_snapshots={}, **virtualchain_args ):

    subdomain_index = server_state['subdomains']
    atlas_state = server_state['atlas']

    # make this usable even if we haven't explicitly configured virtualchain
    impl = sys.modules[__name__]
    log.info("Synchronizing database {} up to block {}".format(working_dir, last_block))

    # NOTE: this is the only place where a read-write handle should be created,
    # since this is the only place where the db should be modified.
    new_db = BlockstackDB.borrow_readwrite_instance(working_dir, last_block, expected_snapshots=expected_snapshots)

    # propagate runtime state to virtualchain callbacks
    new_db.subdomain_index = subdomain_index
    new_db.atlas_state = atlas_state

    rc = virtualchain.sync_virtualchain(bt_opts, last_block, new_db, expected_snapshots=expected_snapshots, **virtualchain_args)

    BlockstackDB.release_readwrite_instance(new_db, last_block)

    return rc

func DependencySort(txs map[chainhash.Hash]*wire.MsgTx) []*wire.MsgTx {
	graph := makeGraph(txs)
	s := graphRoots(graph)

	// If there are no edges (no transactions from the map reference each
	// other), then Kahn's algorithm is unnecessary.
	if len(s) == len(txs) {
		return s
	}

	sorted := make([]*wire.MsgTx, 0, len(txs))
	for len(s) != 0 {
		tx := s[0]
		s = s[1:]
		sorted = append(sorted, tx)

		n := graph[tx.TxHash()]
		for _, mHash := range n.outEdges {
			m := graph[*mHash]
			if m.inDegree != 0 {
				m.inDegree--
				graph[*mHash] = m
				if m.inDegree == 0 {
					s = append(s, m.value)
				}
			}
		}
	}
	return sorted
}

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


Question:
Hash given input value.

@param string $input
@param string $alphabet

@return string

protected function hash($input, $alphabet)
    {
        $hash = '';
        $alphabetLength = strlen($alphabet);

        do {
            $hash = $alphabet[Math::intval(Math::mod($input, $alphabetLength))] . $hash;

            $input = Math::divide($input, $alphabetLength);
        } while (Math::greaterThan($input, 0));

        return $hash;
    }

def type_string text, options={}
      shift_key_down = nil

      text.each_char do |char|
        key_to_press = KEY_PRESS_CHARS[char]
        unless key_to_press.nil?
          key_press key_to_press
        else
          key_needs_shift = SHIFTED_CHARS.include? char

          if shift_key_down.nil? || shift_key_down != key_needs_shift
            if key_needs_shift
              key_down :shift
            else
              key_up :shift
            end
          end

          type char
          shift_key_down = key_needs_shift
        end
      end
      wait options
    end

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


Question:
appends input string to log file and sends it to log function (self.log_function)
        Returns:

def log(self, string):

        self.log_data.append(string)
        if self.log_function is None:
            print(string)
        else:
            self.log_function(string)

func (l *Logger) Panic(msg interface{}, data ...interface{}) {
	if l.shouldAppend(PANIC) {
		l.makeLog(msg, PANIC, data)
		panic(msg)
	}
}

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


Question:
Render a view template.

@param (string) $file Name of files.
@param (array)  $args Attributes.

@since 1.0.0

@return void

public static function renderTemplate($file, $args = [])
    {
        if (!empty($file)) {
            self::setFile($file);
            extract($args, EXTR_SKIP);
            if (file_exists(self::$file)) {
                ob_start();
                require_once self::$file;
            } else {
                throw new \Exception("Sorry, view file {$file} not exists", 404);
            }
        } else {
            throw new \Exception('Sorry, file much be provided', 404);
        }
    }

public function visit(Visitor $visitor, Generator $generator, $data)
    {
        $generator->startObjectElement('TagList');
        $visitor->setHeader('Content-Type', $generator->getMediaType('TagList'));

        $generator->startAttribute('href', $data->path);
        $generator->endAttribute('href');

        $generator->startList('Tag');

        foreach ($data->tags as $restTag) {
            $generator->startObjectElement('Tag');
            $generator->startAttribute(
                'href',
                $this->router->generate(
                    'ezpublish_rest_eztags_loadTag',
                    ['tagPath' => trim($restTag->tag->pathString, '/')]
                )
            );
            $generator->endAttribute('href');
            $generator->endObjectElement('Tag');
        }

        $generator->endList('Tag');

        $generator->endObjectElement('TagList');
    }

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


Question: Process everything all over again.

def reset(self):

        self.indexCount = 0
        indexDir = self.store.newDirectory(self.indexDirectory)
        if indexDir.exists():
            indexDir.remove()
        for src in self.getSources():
            src.removeReliableListener(self)
            src.addReliableListener(self, style=iaxiom.REMOTE)

function DisplayOTron(model) {
    if (!(this instanceof DisplayOTron)) {
        return new DisplayOTron(model);
    }

    this.model = model;

    this.pythonProcess = null;

    this.reset();

    events.EventEmitter.call(this);
}

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


Question: child process - this holds all the GUI elements

def child_task(self):
        ''''''
        mp_util.child_close_fds()

        import matplotlib
        import wx_processguard
        from wx_loader import wx
        from live_graph_ui import GraphFrame

        matplotlib.use('WXAgg')
        app = wx.App(False)
        app.frame = GraphFrame(state=self)
        app.frame.Show()
        app.MainLoop()

function DisplayOTron(model) {
    if (!(this instanceof DisplayOTron)) {
        return new DisplayOTron(model);
    }

    this.model = model;

    this.pythonProcess = null;

    this.reset();

    events.EventEmitter.call(this);
}

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


Question:
The friendly name is mapped to Facebook's first name. If the first
        name is missing, use the last name.

async def get_friendly_name(self) -> Text:

        u = await self._get_user()
        f = u.get('first_name', '').strip()
        l = u.get('last_name', '').strip()

        return f or l

def normalize(email_address, resolve=True):

    address = utils.parseaddr(email_address)
    local_part, domain_part = address[1].lower().split('@')

    # Plus addressing is supported by Microsoft domains and FastMail
    if domain_part in MICROSOFT_DOMAINS:
        if '+' in local_part:
            local_part = local_part.split('+')[0]

    # GMail supports plus addressing and throw-away period delimiters
    elif _is_gmail(domain_part, resolve):
        local_part = local_part.replace('.', '').split('+')[0]

    # Yahoo domain handling of - is like plus addressing
    elif _is_yahoo(domain_part, resolve):
        if '-' in local_part:
            local_part = local_part.split('-')[0]

    # FastMail has domain part username aliasing and plus addressing
    elif _is_fastmail(domain_part, resolve):
        domain_segments = domain_part.split('.')
        if len(domain_segments) > 2:
            local_part = domain_segments[0]
            domain_part = '.'.join(domain_segments[1:])
        elif '+' in local_part:
            local_part = local_part.split('+')[0]

    return '@'.join([local_part, domain_part])

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


Question:
For a given group (ie: a list containing [marker, position])
    order the list according to their position.

def _order_linkage_group(group):

    tmp = {}
    for row in group:
        if float(row[1]) in tmp:  # pragma: no cover
            tmp[float(row[1])].append(row[0])
        else:
            tmp[float(row[1])] = [row[0]]

    keys = list(tmp.keys())
    keys.sort()
    output = []
    for key in keys:
        for entry in tmp[key]:
            if not entry:
                continue
            output.append([entry, str(key)])
    return output

def dfs_postorder(self, reverse=False):
        """"""
        stack = deque()
        stack.append(self)
        visited = set()
        while stack:
            node = stack.pop()
            if node in visited:
                yield node
            else:
                visited.add(node)
                stack.append(node)
                if hasattr(node, "childs"):
                    if reverse:
                        stack.extend(node.childs)
                    else:
                        stack.extend(node.childs[::-1])

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


Question:
// AcquireGzipWriter prepares a gzip writer and returns it
//
// see ReleaseGzipWriter

func (p *GzipPool) AcquireGzipWriter(w io.Writer) *gzip.Writer {
	v := p.Get()
	if v == nil {
		gzipWriter, err := gzip.NewWriterLevel(w, p.Level)
		if err != nil {
			return nil
		}
		return gzipWriter
	}
	gzipWriter := v.(*gzip.Writer)
	gzipWriter.Reset(w)
	return gzipWriter
}

def __save_output(self):

        out = zipfile.ZipFile(self.outputfilename, 'w')

        for info_zip in self.infile.infolist():

            if info_zip.filename in self.templated_files:
                # Template file - we have edited these.

                # get a temp file
                streamout = open(get_secure_filename(), "w+b")
                fname, output_stream = self.output_streams[
                    self.templated_files.index(info_zip.filename)
                ]

                transformer = get_list_transformer(self.namespaces)
                remapped_stream = output_stream | transformer

                # write the whole stream to it
                for chunk in remapped_stream.serialize():
                    streamout.write(chunk.encode('utf-8'))
                    yield True

                # close the temp file to flush all data and make sure we get
                # it back when writing to the zip archive.
                streamout.close()

                # write the full file to archive
                out.write(streamout.name, fname)

                # remove temp file
                os.unlink(streamout.name)

            else:
                # Copy other files straight from the source archive.
                out.writestr(info_zip, self.infile.read(info_zip.filename))

        # Save images in the "Pictures" sub-directory of the archive.
        for identifier, data in self.images.items():
            out.writestr(PY3O_IMAGE_PREFIX + identifier, data)

        # close the zipfile before leaving
        out.close()
        yield True

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


Question:
"Add" the task, not possible for QueueEmailTask

@return void

public function add() {
		$this->err('Queue Email Task cannot be added via Console.');
		$this->out('Please use createJob() on the QueuedTask Model to create a Proper Email Task.');
		$this->out('The Data Array should look something like this:');
		$this->out(var_export([
			'settings' => [
				'to' => 'email@example.com',
				'subject' => 'Email Subject',
				'from' => 'system@example.com',
				'template' => 'sometemplate',
			],
			'content' => 'hello world',
		], true));
		$this->out('Alternativly, you can pass the whole EmailLib to directly use it.');
	}

def _build_tree_by_level(self, time_qualifier, collection_name, since):

        invalid_tree_records = dict()
        invalid_tq_records = dict()

        try:
            job_records = self.job_dao.get_all(collection_name, since)
            for job_record in job_records:
                tree = self.get_tree(job_record.process_name)
                if tree is None:
                    utils.increment_family_property(job_record.process_name, invalid_tree_records)
                    continue

                job_time_qualifier = context.process_context[job_record.process_name].time_qualifier
                if time_qualifier != job_time_qualifier:
                    utils.increment_family_property(job_record.process_name, invalid_tq_records)
                    continue

                tree.update_node(job_record)

        except LookupError:
            self.logger.warning('No job records in {0}.'.format(collection_name))

        for name, counter in invalid_tree_records.items():
            self.logger.warning('Skipping {0} job records for {1} since no tree is handling it.'
                                .format(counter, name))

        for name, counter in invalid_tq_records.items():
            self.logger.warning('Skipping {0} job records for {1} since the process has different time qualifier.'
                                .format(counter, name))

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 *AppProjectList) DeepCopyInto(out *AppProjectList) {
	*out = *in
	out.TypeMeta = in.TypeMeta
	out.ListMeta = in.ListMeta
	if in.Items != nil {
		in, out := &in.Items, &out.Items
		*out = make([]AppProject, len(*in))
		for i := range *in {
			(*in)[i].DeepCopyInto(&(*out)[i])
		}
	}
	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:
// reloadInsecureRegistries updates configuration with insecure registry option
// and updates the passed attributes

func (daemon *Daemon) reloadInsecureRegistries(conf *config.Config, attributes map[string]string) error {
	// update corresponding configuration
	if conf.IsValueSet("insecure-registries") {
		daemon.configStore.InsecureRegistries = conf.InsecureRegistries
		if err := daemon.RegistryService.LoadInsecureRegistries(conf.InsecureRegistries); err != nil {
			return err
		}
	}

	// prepare reload event attributes with updatable configurations
	if daemon.configStore.InsecureRegistries != nil {
		insecureRegistries, err := json.Marshal(daemon.configStore.InsecureRegistries)
		if err != nil {
			return err
		}
		attributes["insecure-registries"] = string(insecureRegistries)
	} else {
		attributes["insecure-registries"] = "[]"
	}

	return nil
}

public function store(Request $request)
    {
        $this->validate(
            $request,
            [
                'key' => 'required|string|unique:settings',
                'value' => 'required'
            ]
        );

        $requestData = $request->all();

        Setting::create($requestData);

        return redirect('admin/settings')->with('flash_message', 'Setting added!');
    }

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


Question:
Unbinds the data to the already existing ViewHolder and removes the listeners from the holder.itemView

@param holder the viewHolder we unbind the data from

@Override
    public void onViewRecycled(RecyclerView.ViewHolder holder) {
        if (mVerbose) Log.v(TAG, "onViewRecycled: " + holder.getItemViewType());
        super.onViewRecycled(holder);
        mOnBindViewHolderListener.unBindViewHolder(holder, holder.getAdapterPosition());
    }

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

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

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

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


Question:
Returns a generally symmetrized tensor, calculated by taking
        the sum of the tensor and its transpose with respect to all
        possible permutations of indices

def symmetrized(self):

        perms = list(itertools.permutations(range(self.rank)))
        return sum([np.transpose(self, ind) for ind in perms]) / len(perms)

private void setUpIteration(DeltaIteration<?, ?> iteration) {

		// set up the iteration operator
		if (this.configuration != null) {

			iteration.name(this.configuration.getName("Vertex-centric iteration (" + computeFunction + ")"));
			iteration.parallelism(this.configuration.getParallelism());
			iteration.setSolutionSetUnManaged(this.configuration.isSolutionSetUnmanagedMemory());

			// register all aggregators
			for (Map.Entry<String, Aggregator<?>> entry : this.configuration.getAggregators().entrySet()) {
				iteration.registerAggregator(entry.getKey(), entry.getValue());
			}
		}
		else {
			// no configuration provided; set default name
			iteration.name("Vertex-centric iteration (" + computeFunction + ")");
		}
	}

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 *ListDeviceEventsInput) Validate() error {
	invalidParams := request.ErrInvalidParams{Context: "ListDeviceEventsInput"}
	if s.DeviceId == nil {
		invalidParams.Add(request.NewErrParamRequired("DeviceId"))
	}
	if s.DeviceId != nil && len(*s.DeviceId) < 1 {
		invalidParams.Add(request.NewErrParamMinLen("DeviceId", 1))
	}
	if s.FromTimeStamp == nil {
		invalidParams.Add(request.NewErrParamRequired("FromTimeStamp"))
	}
	if s.MaxResults != nil && *s.MaxResults < 1 {
		invalidParams.Add(request.NewErrParamMinValue("MaxResults", 1))
	}
	if s.ToTimeStamp == nil {
		invalidParams.Add(request.NewErrParamRequired("ToTimeStamp"))
	}

	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: InternalSimpleAntlr.g:648:1: ruleAtom returns [EObject current=null] : ( (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? ) | this_RuleOptions_3= ruleRuleOptions ) ;

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

        Token lv_cardinality_2_1=null;
        Token lv_cardinality_2_2=null;
        Token lv_cardinality_2_3=null;
        EObject this_OtherElement_0 = null;

        EObject this_RuleOptions_3 = null;

         enterRule();

        try {
            // InternalSimpleAntlr.g:651:28: ( ( (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? ) | this_RuleOptions_3= ruleRuleOptions ) )
            // InternalSimpleAntlr.g:652:1: ( (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? ) | this_RuleOptions_3= ruleRuleOptions )
            {
            // InternalSimpleAntlr.g:652:1: ( (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? ) | this_RuleOptions_3= ruleRuleOptions )
            int alt15=2;
            int LA15_0 = input.LA(1);

            if ( (LA15_0==RULE_ID||(LA15_0>=RULE_OPEN && LA15_0<=RULE_STRING)||LA15_0==28||LA15_0==36) ) {
                alt15=1;
            }
            else if ( ((LA15_0>=15 && LA15_0<=16)) ) {
                alt15=2;
            }
            else {
                if (state.backtracking>0) {state.failed=true; return current;}
                NoViableAltException nvae =
                    new NoViableAltException("", 15, 0, input);

                throw nvae;
            }
            switch (alt15) {
                case 1 :
                    // InternalSimpleAntlr.g:652:2: (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? )
                    {
                    // InternalSimpleAntlr.g:652:2: (this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )? )
                    // InternalSimpleAntlr.g:653:2: this_OtherElement_0= ruleOtherElement ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )?
                    {
                    if ( state.backtracking==0 ) {

                      	  /* */

                    }
                    if ( state.backtracking==0 ) {

                              newCompositeNode(grammarAccess.getAtomAccess().getOtherElementParserRuleCall_0_0());

                    }
                    pushFollow(FOLLOW_17);
                    this_OtherElement_0=ruleOtherElement();

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

                              current = this_OtherElement_0;
                              afterParserOrEnumRuleCall();

                    }
                    // InternalSimpleAntlr.g:664:1: ( () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) ) )?
                    int alt14=2;
                    int LA14_0 = input.LA(1);

                    if ( ((LA14_0>=25 && LA14_0<=27)) ) {
                        alt14=1;
                    }
                    switch (alt14) {
                        case 1 :
                            // InternalSimpleAntlr.g:664:2: () ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) )
                            {
                            // InternalSimpleAntlr.g:664:2: ()
                            // InternalSimpleAntlr.g:665:2:
                            {
                            if ( state.backtracking==0 ) {

                              	  /* */

                            }
                            if ( state.backtracking==0 ) {

                                      current = forceCreateModelElementAndSet(
                                          grammarAccess.getAtomAccess().getElementWithCardinalityElementAction_0_1_0(),
                                          current);

                            }

                            }

                            // InternalSimpleAntlr.g:673:2: ( ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) ) )
                            // InternalSimpleAntlr.g:674:1: ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) )
                            {
                            // InternalSimpleAntlr.g:674:1: ( (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' ) )
                            // InternalSimpleAntlr.g:675:1: (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' )
                            {
                            // InternalSimpleAntlr.g:675:1: (lv_cardinality_2_1= '+' | lv_cardinality_2_2= '*' | lv_cardinality_2_3= '?' )
                            int alt13=3;
                            switch ( input.LA(1) ) {
                            case 25:
                                {
                                alt13=1;
                                }
                                break;
                            case 26:
                                {
                                alt13=2;
                                }
                                break;
                            case 27:
                                {
                                alt13=3;
                                }
                                break;
                            default:
                                if (state.backtracking>0) {state.failed=true; return current;}
                                NoViableAltException nvae =
                                    new NoViableAltException("", 13, 0, input);

                                throw nvae;
                            }

                            switch (alt13) {
                                case 1 :
                                    // InternalSimpleAntlr.g:676:3: lv_cardinality_2_1= '+'
                                    {
                                    lv_cardinality_2_1=(Token)match(input,25,FOLLOW_2); if (state.failed) return current;
                                    if ( state.backtracking==0 ) {

                                              newLeafNode(lv_cardinality_2_1, grammarAccess.getAtomAccess().getCardinalityPlusSignKeyword_0_1_1_0_0());

                                    }
                                    if ( state.backtracking==0 ) {

                                      	        if (current==null) {
                                      	            current = createModelElement(grammarAccess.getAtomRule());
                                      	        }
                                             		setWithLastConsumed(current, "cardinality", lv_cardinality_2_1, null);

                                    }

                                    }
                                    break;
                                case 2 :
                                    // InternalSimpleAntlr.g:688:8: lv_cardinality_2_2= '*'
                                    {
                                    lv_cardinality_2_2=(Token)match(input,26,FOLLOW_2); if (state.failed) return current;
                                    if ( state.backtracking==0 ) {

                                              newLeafNode(lv_cardinality_2_2, grammarAccess.getAtomAccess().getCardinalityAsteriskKeyword_0_1_1_0_1());

                                    }
                                    if ( state.backtracking==0 ) {

                                      	        if (current==null) {
                                      	            current = createModelElement(grammarAccess.getAtomRule());
                                      	        }
                                             		setWithLastConsumed(current, "cardinality", lv_cardinality_2_2, null);

                                    }

                                    }
                                    break;
                                case 3 :
                                    // InternalSimpleAntlr.g:700:8: lv_cardinality_2_3= '?'
                                    {
                                    lv_cardinality_2_3=(Token)match(input,27,FOLLOW_2); if (state.failed) return current;
                                    if ( state.backtracking==0 ) {

                                              newLeafNode(lv_cardinality_2_3, grammarAccess.getAtomAccess().getCardinalityQuestionMarkKeyword_0_1_1_0_2());

                                    }
                                    if ( state.backtracking==0 ) {

                                      	        if (current==null) {
                                      	            current = createModelElement(grammarAccess.getAtomRule());
                                      	        }
                                             		setWithLastConsumed(current, "cardinality", lv_cardinality_2_3, null);

                                    }

                                    }
                                    break;

                            }

                            }

                            }

                            }
                            break;

                    }

                    }

                    }
                    break;
                case 2 :
                    // InternalSimpleAntlr.g:717:2: this_RuleOptions_3= ruleRuleOptions
                    {
                    if ( state.backtracking==0 ) {

                      	  /* */

                    }
                    if ( state.backtracking==0 ) {

                              newCompositeNode(grammarAccess.getAtomAccess().getRuleOptionsParserRuleCall_1());

                    }
                    pushFollow(FOLLOW_2);
                    this_RuleOptions_3=ruleRuleOptions();

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

                              current = this_RuleOptions_3;
                              afterParserOrEnumRuleCall();

                    }

                    }
                    break;

            }

            }

            if ( state.backtracking==0 ) {
               leaveRule();
            }
        }

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

<V> ElementRule<T, V> getRule(ChronoElement<V> element) {

        return this.getChronology().getRule(element);

    }

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


Question: // Errorf is a convenience function for constructing a NestedError.

func Errorf(err error, msg string, format ...interface{}) error {
	return NestedError{
		NestedErr: err,
		Err:       fmt.Errorf(msg, format...),
	}
}

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.