Question:
Defined by Zend_Validate_Interface

Returns true if and only if the $value is a valid hostname with respect to the current allow option

@param  string $value
@throws Zend_Validate_Exception if a fatal error occurs for validation process
@return boolean

public function isValid($value)
    {
        $valueString = (string) $value;

        $this->_setValue($valueString);

        // Check input against IP address schema
        if ($this->_ipValidator->setTranslator($this->getTranslator())->isValid($valueString)) {
            if (!($this->_allow & self::ALLOW_IP)) {
                $this->_error(self::IP_ADDRESS_NOT_ALLOWED);
                return false;
            } else{
                return true;
            }
        }

        // Check input against DNS hostname schema
        $domainParts = explode('.', $valueString);
        if ((count($domainParts) > 1) && (strlen($valueString) >= 4) && (strlen($valueString) <= 254)) {
            $status = false;

            do {
                // First check TLD
                if (preg_match('/([^.]{2,10})$/i', end($domainParts), $matches) ||
                    (end($domainParts) == 'ایران') || (end($domainParts) == '中国') ||
                    (end($domainParts) == '公司') || (end($domainParts) == '网络')) {

                    reset($domainParts);

                    // Hostname characters are: *(label dot)(label dot label); max 254 chars
                    // label: id-prefix [*ldh{61} id-prefix]; max 63 chars
                    // id-prefix: alpha / digit
                    // ldh: alpha / digit / dash

                    // Match TLD against known list
                    $this->_tld = strtolower($matches[1]);
                    if ($this->_validateTld) {
                        if (!in_array($this->_tld, $this->_validTlds)) {
                            $this->_error(self::UNKNOWN_TLD);
                            $status = false;
                            break;
                        }
                    }

                    /**
                     * Match against IDN hostnames
                     * Note: Keep label regex short to avoid issues with long patterns when matching IDN hostnames
                     * @see Zend_Validate_Hostname_Interface
                     */
                    $regexChars = array(0 => '/^[a-z0-9\x2d]{1,63}$/i');
                    if ($this->_validateIdn &&  isset($this->_validIdns[strtoupper($this->_tld)])) {
                        if (is_string($this->_validIdns[strtoupper($this->_tld)])) {
                            $regexChars += include($this->_validIdns[strtoupper($this->_tld)]);
                        } else {
                            $regexChars += $this->_validIdns[strtoupper($this->_tld)];
                        }
                    }

                    // Check each hostname part
                    $valid = true;
                    foreach ($domainParts as $domainPart) {

                        // Decode Punycode domainnames to IDN
                        if (strpos($domainPart, 'xn--') === 0) {
                            $domainPart = $this->decodePunycode(substr($domainPart, 4));
                            if ($domainPart === false) {
                                return false;
                            }
                        }

                        // Check dash (-) does not start, end or appear in 3rd and 4th positions
                        if ((strpos($domainPart, '-') === 0)
                            || ((strlen($domainPart) > 2) && (strpos($domainPart, '-', 2) == 2) && (strpos($domainPart, '-', 3) == 3))
                            || (strpos($domainPart, '-') === (strlen($domainPart) - 1))) {
                            $this->_error(self::INVALID_DASH);
                            $status = false;
                            break 2;
                        }

                        // Check each domain part
                        $check = false;
                        foreach($regexChars as $regexKey => $regexChar) {
                            $status = @preg_match($regexChar, $domainPart);
                            if ($status === false) {
                                require_once 'Zend/Validate/Exception.php';
                                throw new Zend_Validate_Exception('Internal error: DNS validation failed');
                            } elseif ($status !== 0) {
                                $length = 63;
                                if (array_key_exists(strtoupper($this->_tld), $this->_idnLength)
                                    && (array_key_exists($regexKey, $this->_idnLength[strtoupper($this->_tld)]))) {
                                    $length = $this->_idnLength[strtoupper($this->_tld)];
                                }

                                if (iconv_strlen($domainPart) > $length) {
                                    $this->_error(self::INVALID_HOSTNAME);
                                } else {
                                    $check = true;
                                    break 2;
                                }
                            }
                        }

                        if (!$check) {
                            $valid = false;
                        }
                    }

                    // If all labels didn't match, the hostname is invalid
                    if (!$valid) {
                        $this->_error(self::INVALID_HOSTNAME_SCHEMA);
                        $status = false;
                    }

                } else {
                    // Hostname not long enough
                    $this->_error(self::UNDECIPHERABLE_TLD);
                    $status = false;
                }
            } while (false);

            // If the input passes as an Internet domain name, and domain names are allowed, then the hostname
            // passes validation
            if ($status && ($this->_allow & self::ALLOW_DNS)) {
                return true;
            }
        } else {
            $this->_error(self::INVALID_HOSTNAME);
        }

        // Check input against local network name schema; last chance to pass validation
        $regexLocal = '/^(([a-zA-Z0-9\x2d]{1,63}\x2e)*[a-zA-Z0-9\x2d]{1,63}){1,254}$/';
        $status = @preg_match($regexLocal, $valueString);
        if (false === $status) {
            /**
             * Regex error
             * @see Zend_Validate_Exception
             */
            require_once 'Zend/Validate/Exception.php';
            throw new Zend_Validate_Exception('Internal error: local network name validation failed');
        }

        // If the input passes as a local network name, and local network names are allowed, then the
        // hostname passes validation
        $allowLocal = $this->_allow & self::ALLOW_LOCAL;
        if ($status && $allowLocal) {
            return true;
        }

        // If the input does not pass as a local network name, add a message
        if (!$status) {
            $this->_error(self::INVALID_LOCAL_NAME);
        }

        // If local network names are not allowed, add a message
        if ($status && !$allowLocal) {
            $this->_error(self::LOCAL_NAME_NOT_ALLOWED);
        }

        return false;
    }

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

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


Question: switchToWindow switch to an other Window.

private void switchToWindow(String key, String handleToKeep) {
        Context.addWindow(key, handleToKeep);
        Context.setMainWindow(key);
        Context.getDriver().switchTo().window(handleToKeep);
    }

public static void main(String args[]) {
		try {
			Display display = Display.getDefault();
			WebcamPanelShell shell = new WebcamPanelShell(display);
			shell.open();
			shell.layout();
			while (!shell.isDisposed()) {
				if (!display.readAndDispatch()) {
					display.sleep();
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

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


Question: // SetLastModified sets the LastModified field's value.

func (s *DashboardEntry) SetLastModified(v time.Time) *DashboardEntry {
	s.LastModified = &v
	return s
}

def _init_metadata(self):
        """"""

        # pylint: disable=attribute-defined-outside-init
        # this method is called from descendent __init__
        self._mdata.update(default_mdata.get_osid_form_mdata())
        update_display_text_defaults(self._mdata['journal_comment'], self._locale_map)
        for element_name in self._mdata:
            self._mdata[element_name].update(
                {'element_id': Id(self._authority,
                                  self._namespace,
                                  element_name)})
        self._journal_comment_default = self._mdata['journal_comment']['default_string_values'][0]
        self._validation_messages = {}

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


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

public EClass getIfcStructuralActivityAssignmentSelect() {
		if (ifcStructuralActivityAssignmentSelectEClass == null) {
			ifcStructuralActivityAssignmentSelectEClass = (EClass) EPackage.Registry.INSTANCE
					.getEPackage(Ifc2x3tc1Package.eNS_URI).getEClassifiers().get(972);
		}
		return ifcStructuralActivityAssignmentSelectEClass;
	}

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: // XXX_OneofFuncs is for the internal use of the proto package.

func (*Annotation) XXX_OneofFuncs() (func(msg proto.Message, b *proto.Buffer) error, func(msg proto.Message, tag, wire int, b *proto.Buffer) (bool, error), func(msg proto.Message) (n int), []interface{}) {
	return _Annotation_OneofMarshaler, _Annotation_OneofUnmarshaler, _Annotation_OneofSizer, []interface{}{
		(*Annotation_Variant)(nil),
		(*Annotation_Transcript)(nil),
	}
}

private void createFunction(String name, GeometryFunction function) {
		try {
			Function.create(getGeoPackage().getConnection().getConnection(),
					name, function);
		} catch (SQLException e) {
			log.log(Level.SEVERE, "Failed to create function: " + name, e);
		}
	}

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


Question:
take a list of words and return a dict of sets sorted by word length
    e.g.
    ret[3]=set(['ant', 'cat', 'dog', 'pig'])
    ret[4]=set(['frog', 'goat'])
    ret[5]=set(['horse'])
    ret[8]=set(['elephant'])

def bysize(words):

    ret = {}
    for w in words:
        if len(w) not in ret:
            ret[len(w)] = set()
        ret[len(w)].add(w)
    return ret

def allocate_buffers(self):
        ""
        if self.ite_len is None: len(self)
        self.idx   = LanguageModelPreLoader.CircularIndex(len(self.dataset.x.items), not self.backwards)
        self.batch = np.zeros((self.bs, self.bptt+1), dtype=np.int64)
        self.batch_x, self.batch_y = self.batch[:,0:self.bptt], self.batch[:,1:self.bptt+1]
        #ro: index of the text we're at inside our datasets for the various batches
        self.ro    = np.zeros(self.bs, dtype=np.int64)
        #ri: index of the token we're at inside our current text for the various batches
        self.ri    = np.zeros(self.bs, dtype=np.int)

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


Question:
// SubscribeRemovedLogsEvent implements the interface of filters.Backend
// LightChain does not send core.RemovedLogsEvent, so return an empty subscription.

func (lc *LightChain) SubscribeRemovedLogsEvent(ch chan<- core.RemovedLogsEvent) event.Subscription {
	return lc.scope.Track(new(event.Feed).Subscribe(ch))
}

public function del($fd, $flag)
    {
        switch ($flag) {
            case static::EV_READ:
            case static::EV_WRITE:
                $fd_key    = (int)$fd;
                if(isset($this->fdEvents[$fd_key][$flag])){
                    $this->fdEvents[$fd_key][$flag]->del();
                    $this->fdEvents[$fd_key][$flag]->free();
                    unset($this->fdEvents[$fd_key][$flag]);
                }
            case static::EV_SIGNAL:
                if(isset($this->signalEvents[$fd])) {
                    $this->signalEvents[$fd]->del();
                    $this->signalEvents[$fd]->free();
                    unset($this->signalEvents[$fd]);
                }
                break;
            case static::EV_INTERVAL:
            case static::EV_TIMEOUT:
                if(isset($this->timerEvents[$fd])) {
                    static::unsetId($fd);
                    $this->timerEvents[$fd]->del();
                    $this->timerEvents[$fd]->free();
                    unset($this->timerEvents[$fd]);
                }

                break;

        }
    }

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


Question:
Checks whether the token is in the source.

@param \Gems_Tracker_Token $token Gems token object
@param int $surveyId Gems Survey Id
@param string $sourceSurveyId Optional Survey Id used by source
@return boolean

public function inSource(\Gems_Tracker_Token $token, $surveyId, $sourceSurveyId = null)
    {
        $tokenInfo = $this->getTokenInfo($token, $surveyId, $sourceSurveyId);
        return (boolean) $tokenInfo;
    }

def options
      {id: self.survey_id, surveyID: self.survey_id, responseID: self.response_id,
       resultMode: self.result_mode, startDate: self.start_date, userID: self.user_id,
       endDate: self.end_date, startingResponseCounter: self.starting_response_counter,
       emailGroupID: self.email_group_id, templateID: self.template_id}.compact.to_json
    end

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


Question: // This is a courtesy helper function, which in some cases may not work as expected!

func (s *FirewallService) GetPortForwardingRuleByID(id string, opts ...OptionFunc) (*PortForwardingRule, int, error) {
	p := &ListPortForwardingRulesParams{}
	p.p = make(map[string]interface{})

	p.p["id"] = id

	for _, fn := range append(s.cs.options, opts...) {
		if err := fn(s.cs, p); err != nil {
			return nil, -1, err
		}
	}

	l, err := s.ListPortForwardingRules(p)
	if err != nil {
		if strings.Contains(err.Error(), fmt.Sprintf(
			"Invalid parameter id value=%s due to incorrect long value format, "+
				"or entity does not exist", id)) {
			return nil, 0, fmt.Errorf("No match found for %s: %+v", id, l)
		}
		return nil, -1, err
	}

	if l.Count == 0 {
		return nil, l.Count, fmt.Errorf("No match found for %s: %+v", id, l)
	}

	if l.Count == 1 {
		return l.PortForwardingRules[0], l.Count, nil
	}
	return nil, l.Count, fmt.Errorf("There is more then one result for PortForwardingRule UUID: %s!", id)
}

public List<SuggestedFix> drive(Scanner scanner, Pattern includeFilePattern) {
    JsFlumeCallback callback = new JsFlumeCallback(scanner, includeFilePattern);
    NodeTraversal.traverse(compiler, rootNode, callback);
    List<SuggestedFix> fixes = callback.getFixes();
    fixes.addAll(scanner.processAllMatches(callback.getMatches()));
    return fixes;
  }

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


Question:
// generateUserTypes iterates through the user types and generates the data structures and
// marshaling code.

func (g *Generator) generateUserTypes(outdir string, api *design.APIDefinition) error {
	var modelname, filename string
	err := GormaDesign.IterateStores(func(store *RelationalStoreDefinition) error {
		err := store.IterateModels(func(model *RelationalModelDefinition) error {
			modelname = strings.ToLower(codegen.Goify(model.ModelName, false))

			filename = fmt.Sprintf("%s.go", modelname)
			utFile := filepath.Join(outdir, filename)
			err := os.RemoveAll(utFile)
			if err != nil {
				fmt.Println(err)
			}
			utWr, err := NewUserTypesWriter(utFile)
			if err != nil {
				panic(err) // bug
			}
			title := fmt.Sprintf("%s: Models", api.Context())
			imports := []*codegen.ImportSpec{
				codegen.SimpleImport(g.appPkgPath),
				codegen.SimpleImport("context"),
				codegen.SimpleImport("time"),
				codegen.SimpleImport("github.com/goadesign/goa"),
				codegen.SimpleImport("github.com/jinzhu/gorm"),
				codegen.SimpleImport("github.com/gofrs/uuid"),
			}

			if model.Cached {
				imp := codegen.NewImport("cache", "github.com/patrickmn/go-cache")
				imports = append(imports, imp)
				imp = codegen.SimpleImport("strconv")
				imports = append(imports, imp)
			}
			utWr.WriteHeader(title, g.target, imports)
			data := &UserTypeTemplateData{
				APIDefinition: api,
				UserType:      model,
				DefaultPkg:    g.target,
				AppPkg:        g.appPkgPath,
			}
			err = utWr.Execute(data)
			g.genfiles = append(g.genfiles, utFile)
			if err != nil {
				fmt.Println(err)
				return err
			}
			err = utWr.FormatCode()
			if err != nil {
				fmt.Println(err)
			}
			return err
		})
		return err
	})
	return err
}

protected function buildUsageLine($usage_data, $options_data) {
    if ($usage_data['use_argv_self']) {
      $self_name = $_SERVER['argv'][0];
    } else {
      $self_name = $usage_data['self'];
    }

    $has_options = (count($options_data['lines']) > 0 ? true : false);
    $has_named_args = (count($usage_data['named_args_spec']) > 0 ? true : false);

    $out =
      ConsoleFormat::applyformatToText('bold','cyan',"Usage:")."\n".
      "  {$self_name}".
      ($has_options ? ' [options]' : '').
      ($has_named_args ? ' '.$this->generateValueNamesHelp($usage_data['named_args_spec']) : '').
      "\n";

    return $out;
  }

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


Question: // removeApplication removes the application from the model.

func (m *Model) removeApplication(ch RemoveApplication) error {
	defer m.doLocked()()

	app, ok := m.applications[ch.Name]
	if ok {
		if err := app.evict(); err != nil {
			return errors.Trace(err)
		}
		delete(m.applications, ch.Name)
	}
	return nil
}

public final boolean isRemoved(final String key) {
        final Property prop = find(key);
        if (prop == null) {
            return true;
        }
        return prop.isDeleted();
    }

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


Question:
Check if the combination of format/subtype/endian is valid.

    Examples
    --------
    >>> import soundfile as sf
    >>> sf.check_format('WAV', 'PCM_24')
    True
    >>> sf.check_format('FLAC', 'VORBIS')
    False

def check_format(format, subtype=None, endian=None):

    try:
        return bool(_format_int(format, subtype, endian))
    except (ValueError, TypeError):
        return False

def file_info_long(self):

        self.file_info()
        for ii in np.arange(self.signals_in_file):
            print("label:", self.getSignalLabels()[ii], "fs:",
                  self.getSampleFrequencies()[ii], "nsamples",
                  self.getNSamples()[ii])

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


Question:
Log a message at the 'finest' debugging level.

You should check isDebugging() before building the message.

@param message Informational log message.
@param e Exception

public void finest(CharSequence message, Throwable e) {
    log(Level.FINEST, message, e);
  }

public void encode(AsnOutputStream aos) throws EncodeException {
        if (this.userType == null && this.providerType == null)
            throw new EncodeException("Error encoding ResultSourceDiagnostic: Value not set");

        try {
            aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG);
            int pos = aos.StartContentDefiniteLength();

            if (this.userType != null) {
                aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_U);
                int pos2 = aos.StartContentDefiniteLength();
                aos.writeInteger(this.userType.getType());
                aos.FinalizeContent(pos2);
            } else {
                aos.writeTag(Tag.CLASS_CONTEXT_SPECIFIC, false, _TAG_P);
                int pos2 = aos.StartContentDefiniteLength();
                aos.writeInteger(this.providerType.getType());
                aos.FinalizeContent(pos2);
            }

            aos.FinalizeContent(pos);

        } catch (IOException e) {
            throw new EncodeException("IOException while encoding ResultSourceDiagnostic: " + e.getMessage(), e);
        } catch (AsnException e) {
            throw new EncodeException("AsnException while encoding ResultSourceDiagnostic: " + e.getMessage(), e);
        }

    }

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


Question: // ValidateUpdate is the default update validation for an end user.

func (daemonSetStrategy) ValidateUpdate(ctx context.Context, obj, old runtime.Object) field.ErrorList {
	newDaemonSet := obj.(*apps.DaemonSet)
	oldDaemonSet := old.(*apps.DaemonSet)
	allErrs := validation.ValidateDaemonSet(obj.(*apps.DaemonSet))
	allErrs = append(allErrs, validation.ValidateDaemonSetUpdate(newDaemonSet, oldDaemonSet)...)
	allErrs = append(allErrs, corevalidation.ValidateConditionalPodTemplate(&newDaemonSet.Spec.Template, &oldDaemonSet.Spec.Template, field.NewPath("spec.template"))...)

	// Update is not allowed to set Spec.Selector for apps/v1 and apps/v1beta2 (allowed for extensions/v1beta1).
	// If RequestInfo is nil, it is better to revert to old behavior (i.e. allow update to set Spec.Selector)
	// to prevent unintentionally breaking users who may rely on the old behavior.
	// TODO(#50791): after extensions/v1beta1 is removed, move selector immutability check inside ValidateDaemonSetUpdate().
	if requestInfo, found := genericapirequest.RequestInfoFrom(ctx); found {
		groupVersion := schema.GroupVersion{Group: requestInfo.APIGroup, Version: requestInfo.APIVersion}
		switch groupVersion {
		case extensionsv1beta1.SchemeGroupVersion:
			// no-op for compatibility
		default:
			// disallow mutation of selector
			allErrs = append(allErrs, apivalidation.ValidateImmutableField(newDaemonSet.Spec.Selector, oldDaemonSet.Spec.Selector, field.NewPath("spec").Child("selector"))...)
		}
	}

	return allErrs
}

def SchemaValidateCtxt(self, reader, options):

        if reader is None: reader__o = None
        else: reader__o = reader._o
        ret = libxml2mod.xmlTextReaderSchemaValidateCtxt(reader__o, self._o, options)
        return ret

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


Question:
Returns the cache of alert channels for the given policy, creating one if it doesn't exist .
@param policyId The id of the policy for the cache of alert channels
@return The cache of alert channels for the given policy

public AlertChannelCache alertChannels(long policyId)
    {
        AlertChannelCache cache = channels.get(policyId);
        if(cache == null)
            channels.put(policyId, cache = new AlertChannelCache(policyId));
        return cache;
    }

public void marshall(MatchmakingTicket matchmakingTicket, ProtocolMarshaller protocolMarshaller) {

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

        try {
            protocolMarshaller.marshall(matchmakingTicket.getTicketId(), TICKETID_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getConfigurationName(), CONFIGURATIONNAME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatus(), STATUS_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatusReason(), STATUSREASON_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStatusMessage(), STATUSMESSAGE_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getStartTime(), STARTTIME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getEndTime(), ENDTIME_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getPlayers(), PLAYERS_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getGameSessionConnectionInfo(), GAMESESSIONCONNECTIONINFO_BINDING);
            protocolMarshaller.marshall(matchmakingTicket.getEstimatedWaitTime(), ESTIMATEDWAITTIME_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:
Make this object represent the same set as other.
@param other a UnicodeSet whose value will be
copied to this object

public UnicodeSet set(UnicodeSet other) {
        checkFrozen();
        list = other.list.clone();
        len = other.len;
        pat = other.pat;
        strings = new TreeSet<String>(other.strings);
        return this;
    }

public BaseFontParameters getBaseFontParameters(String name) {
        String alias = (String)aliases.get(name);
        if (alias == null)
            return (BaseFontParameters)mapper.get(name);
        BaseFontParameters p = (BaseFontParameters)mapper.get(alias);
        if (p == null)
            return (BaseFontParameters)mapper.get(name);
        else
            return p;
    }

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


Question:
Build the array for conditional fields using a configuration array
@param array $config The ocnfiguration array
@param string $action Optional the action (create, edit, etc) where the conditionals are needed

public static function buildConditionalArray(array $config, string $action = "-") {
        if ($action == "") {
            $action = substr(request()->route()->getName(), stripos(request()->route()->getName(), "::") + 2);
        }
        $condiciones = [];
        $validadores = [];
        $tabla = $config['tabla'];
        foreach ($config['campos'] as $campo => $datos) {
            if (\Sirgrimorum\CrudGenerator\CrudGenerator::inside_array($datos, "hide", $action) === false) {
                if (isset($datos['conditional'])) {
                    if (is_array($datos['conditional'])) {
                        $validadores["{$tabla}_{$campo}"] = [];
                        foreach ($datos['conditional'] as $conCampo => $conValor) {
                            if (!isset($condiciones["{$tabla}_{$conCampo}"])) {
                                $condiciones["{$tabla}_{$conCampo}"] = [];
                            }
                            $condiciones["{$tabla}_{$conCampo}"][] = "{$tabla}_{$campo}";
                            $validadores["{$tabla}_{$campo}"]["{$tabla}_{$conCampo}"] = $conValor;
                        }
                    }
                }
            }
        }
        return [$condiciones, $validadores];
    }

public function getConditionToUpdateInputAjaxAction($couponId, $conditionIndex)
    {
        if (null !== $response = $this->checkAuth(AdminResources::COUPON, [], AccessManager::VIEW)) {
            return $response;
        }

        $this->checkXmlHttpRequest();

        $search = CouponQuery::create();
        /** @var Coupon $coupon */
        $coupon = $search->findOneById($couponId);
        if (!$coupon) {
            return $this->pageNotFound();
        }

        /** @var CouponFactory $couponFactory */
        $couponFactory = $this->container->get('thelia.coupon.factory');
        $couponManager = $couponFactory->buildCouponFromModel($coupon);

        if (!$couponManager instanceof CouponInterface) {
            return $this->pageNotFound();
        }

        $conditions = $couponManager->getConditions();
        if (!isset($conditions[$conditionIndex])) {
            return $this->pageNotFound();
        }
        /** @var ConditionInterface $condition */
        $condition = $conditions[$conditionIndex];

        /** @var ConditionFactory $conditionFactory */
        $conditionFactory = $this->container->get('thelia.condition.factory');
        $inputs = $conditionFactory->getInputsFromConditionInterface($condition);

        if ($inputs === null) {
            return $this->pageNotFound();
        }

        return $this->render(
            'coupon/condition-input-ajax',
            [
                'inputsDrawn' => $condition->drawBackOfficeInputs(),
                'conditionServiceId' => $condition->getServiceId(),
                'conditionIndex' => $conditionIndex,
            ]
        );
    }

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


Question:
Extracts the token a qualifier from the text given the line/colum
    (see test_extract_token_and_qualifier for examples).

    :param unicode text:
    :param int line: 0-based
    :param int column: 0-based

def extract_token_and_qualifier(text, line=0, column=0):
    '''

    '''
    # Note: not using the tokenize module because text should be unicode and
    # line/column refer to the unicode text (otherwise we'd have to know
    # those ranges after converted to bytes).
    if line < 0:
        line = 0
    if column < 0:
        column = 0

    if isinstance(text, bytes):
        text = text.decode('utf-8')

    lines = text.splitlines()
    try:
        text = lines[line]
    except IndexError:
        return TokenAndQualifier(u'', u'')

    if column >= len(text):
        column = len(text)

    text = text[:column]
    token = u''
    qualifier = u''

    temp_token = []
    for i in range(column - 1, -1, -1):
        c = text[i]
        if c in identifier_part or isidentifier(c) or c == u'.':
            temp_token.append(c)
        else:
            break
    temp_token = u''.join(reversed(temp_token))
    if u'.' in temp_token:
        temp_token = temp_token.split(u'.')
        token = u'.'.join(temp_token[:-1])
        qualifier = temp_token[-1]
    else:
        qualifier = temp_token

    return TokenAndQualifier(token, qualifier)

protected function _keySql($prefix, $data)
    {
        $columns = array_map(
            [$this->_driver, 'quoteIdentifier'],
            $data['columns']
        );
        foreach ($data['columns'] as $i => $column) {
            if (isset($data['length'][$column])) {
                $columns[$i] .= sprintf('(%d)', $data['length'][$column]);
            }
        }
        if ($data['type'] === TableSchema::CONSTRAINT_FOREIGN) {
            return $prefix . sprintf(
                ' FOREIGN KEY (%s) REFERENCES %s (%s) ON UPDATE %s ON DELETE %s',
                implode(', ', $columns),
                $this->_driver->quoteIdentifier($data['references'][0]),
                $this->_convertConstraintColumns($data['references'][1]),
                $this->_foreignOnClause($data['update']),
                $this->_foreignOnClause($data['delete'])
            );
        }

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

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


Question:
获取临时素材.

@see   https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1444738727

@param  $media_id

@return mixed

public function download($media_id)
    {
        $url = 'https://api.weixin.qq.com/cgi-bin/media/get?'.$this->access_token.'&media_id='.$media_id;

        return $this->curl->get($url);
    }

public function favorite($accountId, $mediaId, $isFavorite = true, $mediaType = 'movie')
    {
        return $this->postJson('account/' . $accountId . '/favorite', [
            'media_id'   => $mediaId,
            'media_type' => $mediaType,
            'favorite'   => $isFavorite
        ]);
    }

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


Question: Returns a JSON response containing 'context' as payload

def render_to_response(self, context, indent=None):
        ""
        return self.get_json_response(self.convert_context_to_json(context, indent=indent))

func (c *securityContextConstraints) Get(name string, options v1.GetOptions) (result *security.SecurityContextConstraints, err error) {
	result = &security.SecurityContextConstraints{}
	err = c.client.Get().
		Resource("securitycontextconstraints").
		Name(name).
		VersionedParams(&options, scheme.ParameterCodec).
		Do().
		Into(result)
	return
}

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


Question:
Serializes a Group entity.

@param Group $group
@param array $options

@return array

public function serialize(Group $group, array $options = [])
    {
        return [
            'id' => $group->getUuid(),
            'name' => $group->getName(),
            'roles' => array_map(function (Role $role) use ($options) {
                return $this->roleSerializer->serialize($role, $options);
            }, $group->getEntityRoles()->toArray()),
            'organizations' => array_map(function (Organization $organization) use ($options) {
                return $this->organizationSerializer->serialize($organization, $options);
            }, $group->getOrganizations()->toArray()),
        ];
    }

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:
Set Password

@param string     $pValue
@param boolean     $pAlreadyHashed If the password has already been hashed, set this to true
@return PHPExcel_Worksheet_Protection

public function setPassword($pValue = '', $pAlreadyHashed = false)
    {
        if (!$pAlreadyHashed) {
            $pValue = PHPExcel_Shared_PasswordHasher::hashPassword($pValue);
        }
        $this->password = $pValue;
        return $this;
    }

protected function buildInsertQuery(SQLInsert $query, array &$parameters)
    {
        $nl = $this->getSeparator();
        $into = $query->getInto();

        // Column identifiers
        $columns = $query->getColumns();
        $sql = "INSERT INTO {$into}{$nl}(" . implode(', ', $columns) . ")";

        // Values
        $sql .= "{$nl}VALUES";

        // Build all rows
        $rowParts = array();
        foreach ($query->getRows() as $row) {
            // Build all columns in this row
            $assignments = $row->getAssignments();
            // Join SET components together, considering parameters
            $parts = array();
            foreach ($columns as $column) {
                // Check if this column has a value for this row
                if (isset($assignments[$column])) {
                    // Assigment is a single item array, expand with a loop here
                    foreach ($assignments[$column] as $assignmentSQL => $assignmentParameters) {
                        $parts[] = $assignmentSQL;
                        $parameters = array_merge($parameters, $assignmentParameters);
                        break;
                    }
                } else {
                    // This row is missing a value for a column used by another row
                    $parts[] = '?';
                    $parameters[] = null;
                }
            }
            $rowParts[] = '(' . implode(', ', $parts) . ')';
        }
        $sql .= $nl . implode(",$nl", $rowParts);

        return $sql;
    }

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


Question: Read opens_flags.

Set<OpensFlag> readOpensFlags(int flags) {
        Set<OpensFlag> set = EnumSet.noneOf(OpensFlag.class);
        for (OpensFlag f: OpensFlag.values()) {
            if ((flags & f.value) != 0)
                set.add(f);
        }
        return set;
    }

def setOverlayFlag(self, ulOverlayHandle, eOverlayFlag, bEnabled):
        """"""

        fn = self.function_table.setOverlayFlag
        result = fn(ulOverlayHandle, eOverlayFlag, bEnabled)
        return result

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


Question:
// Call shells out to a provider and return its output
// If call succeeds, stdout is returned with no error
// If call fails, "" is return with error containing stderr

func Call(provider, specPath string) (string, error) {
	var (
		stdOut bytes.Buffer
		stdErr bytes.Buffer
	)
	cmd := exec.Command(provider, specPath)
	cmd.Stdout = &stdOut
	cmd.Stderr = &stdErr
	err := cmd.Run()

	if err != nil {
		errstr := err.Error()
		if stdErr.Len() > 0 {
			errstr += ": " + strings.TrimSpace(stdErr.String())
		}
		return "", fmt.Errorf(errstr)
	}

	return strings.TrimSpace(stdOut.String()), nil
}

def _interactive_loop(self, sin: IO[str], sout: IO[str]) -> None:
        """"""
        self._sin = sin
        self._sout = sout
        tasknum = len(all_tasks(loop=self._loop))
        s = '' if tasknum == 1 else 's'
        self._sout.write(self.intro.format(tasknum=tasknum, s=s))
        try:
            while not self._closing.is_set():
                self._sout.write(self.prompt)
                self._sout.flush()
                try:
                    user_input = sin.readline().strip()
                except Exception as e:
                    msg = 'Could not read from user input due to:\n{}\n'
                    log.exception(msg)
                    self._sout.write(msg.format(repr(e)))
                    self._sout.flush()
                else:
                    try:
                        self._command_dispatch(user_input)
                    except Exception as e:
                        msg = 'Unexpected Exception during command execution:\n{}\n'  # noqa
                        log.exception(msg)
                        self._sout.write(msg.format(repr(e)))
                        self._sout.flush()
        finally:
            self._sin = None  # type: ignore
            self._sout = None

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


Question: Installs the hook without checking if it already exists

function actuallyInstallHook(
			hookToCopy,
			whereToPutIt,
			sourceCanonicalName
		) {
			mkpath.sync( path.join( './', path.dirname( whereToPutIt ) ) );
			exec( 'cp ' + hookToCopy + ' ' + whereToPutIt );
			grunt.log.writeln( [
				'Installed ', sourceCanonicalName, ' hook in ', whereToPutIt
			].join( '' ).green );
		}

public function getLogger($name = 'main')
    {
        if (!$this->hasLogger($name)) {
            throw new LoggerNotFoundException(sprintf("Logger instance '%s' not found", $name));
        }

        return $this->channels[$name];
    }

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


Question:
Gets build variable associated with a project and key.

@param project The project associated with the variable.
@return A variable.
@throws IOException on gitlab api call error

public GitlabBuildVariable getBuildVariable(GitlabProject project, String key)
            throws IOException {
        return getBuildVariable(project.getId(), key);
    }

def validate_account_credentials(deployment, context):
    """"""
    boto_args = {'region_name': context.env_vars['AWS_DEFAULT_REGION']}
    for i in ['aws_access_key_id', 'aws_secret_access_key',
              'aws_session_token']:
        if context.env_vars.get(i.upper()):
            boto_args[i] = context.env_vars[i.upper()]
    if isinstance(deployment.get('account-id'), (int, six.string_types)):
        account_id = str(deployment['account-id'])
    elif deployment.get('account-id', {}).get(context.env_name):
        account_id = str(deployment['account-id'][context.env_name])
    else:
        account_id = None
    if account_id:
        validate_account_id(boto3.client('sts', **boto_args), account_id)
    if isinstance(deployment.get('account-alias'), six.string_types):
        account_alias = deployment['account-alias']
    elif deployment.get('account-alias', {}).get(context.env_name):
        account_alias = deployment['account-alias'][context.env_name]
    else:
        account_alias = None
    if account_alias:
        validate_account_alias(boto3.client('iam', **boto_args),
                               account_alias)

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


Question:
Sends a non-expiring {@link TextMessage} with average priority.

@param queueName name of queue
@param text body of message

public void sendTextMessage(String queueName, String text){
        sendTextMessage(queueName, text, DeliveryMode.NON_PERSISTENT, 4, 0);
    }

public function setBodyText($txt, $charset = null, $encoding = Zend_Mime::ENCODING_QUOTEDPRINTABLE)
    {
        if ($charset === null) {
            $charset = $this->_charset;
        }

        $mp = new Zend_Mime_Part($txt);
        $mp->encoding = $encoding;
        $mp->type = Zend_Mime::TYPE_TEXT;
        $mp->disposition = Zend_Mime::DISPOSITION_INLINE;
        $mp->charset = $charset;

        $this->_bodyText = $mp;

        return $this;
    }

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


Question:
addField

@param string|Field\AbstractField|\SimpleXMLElement $field
@param string                                       $fieldset
@param string                                       $group

@return  Field\AbstractField|Field\ListField

public function addField($field, $fieldset = null, $group = null)
    {
        return $this->form->addField($field, $fieldset, $group);
    }

function namedParameterList()
    {
        return array( 'texttoimage' => array( "class" => array( 'type' => 'string',
                                                                'required' => false,
                                                                'default' => $this->DefaultClass ),
                                              "family" => array( "type" => "string",
                                                                 "required" => false,
                                                                 "default" => null ),
                                              "pointsize" => array( "type" => "integer",
                                                                    "required" => false,
                                                                    "default" => null ),
                                              "angle" => array( "type" => "integer",
                                                                "required" => false,
                                                                "default" => null ),
                                              "bgcolor" => array( "type" => "mixed",
                                                                  "required" => false,
                                                                  "default" => null ),
                                              "textcolor" => array( "type" => "mixed",
                                                                    "required" => false,
                                                                    "default" => null ),
                                              "x" => array( "type" => "integer",
                                                            "required" => false,
                                                            "default" => null ),
                                              "y" => array( "type" => "integer",
                                                            "required" => false,
                                                            "default" => null ),
                                              "w" => array( "type" => "integer",
                                                            "required" => false,
                                                            "default" => null ),
                                              "h" => array( "type" => "integer",
                                                            "required" => false,
                                                            "default" => null ),
                                              "usecache" => array( "type" => "boolean",
                                                                   "required" => false,
                                                                   "default" => null ),
                                              "storeimage" => array( "type" => "boolean",
                                                                     "required" => false,
                                                                     "default" => true )
                                              ),
                      'imagefile' => array( 'filename' => array( 'type' => 'string',
                                                                 'required' => true ),
                                            'options' => array( 'type' => 'array',
                                                                'default' => array(),
                                                                'required' => false ) ) );
    }

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


Question: Returns d[k] or [d[k]] if the value is not a list

def _index_list_of_values(d, k):
    """"""
    v = d[k]
    if isinstance(v, list):
        return v
    return [v]

def calibrate(self, cali_data, cali_labels):

    self.nb_cali = cali_labels.shape[0]
    self.cali_activations = self.get_activations(cali_data)
    self.cali_labels = cali_labels

    print("Starting calibration of DkNN.")
    cali_knns_ind, cali_knns_labels = self.find_train_knns(
        self.cali_activations)
    assert all([v.shape == (self.nb_cali, self.neighbors)
                for v in cali_knns_ind.itervalues()])
    assert all([v.shape == (self.nb_cali, self.neighbors)
                for v in cali_knns_labels.itervalues()])

    cali_knns_not_in_class = self.nonconformity(cali_knns_labels)
    cali_knns_not_in_l = np.zeros(self.nb_cali, dtype=np.int32)
    for i in range(self.nb_cali):
      cali_knns_not_in_l[i] = cali_knns_not_in_class[i, cali_labels[i]]
    cali_knns_not_in_l_sorted = np.sort(cali_knns_not_in_l)
    self.cali_nonconformity = np.trim_zeros(cali_knns_not_in_l_sorted, trim='f')
    self.nb_cali = self.cali_nonconformity.shape[0]
    self.calibrated = True
    print("DkNN calibration complete.")

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


Question:
Converts swagger schema of parametes into insomnia one.

@param {Object[]} parameters - array of swagger schemas of parameters
@returns {Object[]} array of insomnia parameters definitions

function convertParameters(parameters) {
  return parameters.map(parameter => {
    const { required, name } = parameter;
    return {
      name,
      disabled: required !== true,
      value: `${generateParameterExample(parameter)}`,
    };
  });
}

private function parseModel($definition, $xml = true) {
        $model = strpos($definition, '\\') === false ?
            $this->modelsNamespace . '\\' . $definition :
            $definition;

        if (!is_subclass_of($model, ApiModel::class)) {
            throw new Exception("The model definition for $model was not found", 501);
        }

        $ret = [
            'type' => 'object',
        ];

        $class = new ReflectionClass($model);

        $properties =  $this->parseProperties($class);
        foreach ($properties as $name => &$property) {
            if (isset($property['required'])) {
                unset($property['required']);
                if (!isset($ret['required'])) {
                    $ret['required'] = [];
                }
                $ret['required'][] = $name;
            }
        }
        $ret['properties'] = $properties;

        if ($xml) {
            $ret['xml'] = ['name' => $definition];
        }

        return $ret;
    }

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


Question:
Called after the initial read is completed. This will set the first read flag to false, get the buffer from the TCP Channel,
and post configure the buffer. Without this method we would lose the first byte we are reading

public void configurePostInitialReadBuffer(){
        _isInitialRead = false;
        _isFirstRead = false;
        _buffer = _tcpContext.getReadInterface().getBuffer();
        configurePostReadBuffer();
    }

def parse_buf(self, encoding="unicode"):

        buf_len = len(self.buf)
        replies = []
        reply = b""
        chop = 0
        skip = 0
        i = 0
        buf_len = len(self.buf)
        for i in range(0, buf_len):
            ch = self.buf[i:i + 1]
            if skip:
                skip -= 1
                i += 1
                continue

            nxt = i + 1
            if nxt < buf_len:
                if ch == b"\r" and self.buf[nxt:nxt + 1] == b"\n":

                    # Append new reply.
                    if reply != b"":
                        if encoding == "unicode":
                            replies.append(encode_str(reply, encoding))
                        else:
                            replies.append(reply)
                        reply = b""

                    # Truncate the whole buf if chop is out of bounds.
                    chop = nxt + 1
                    skip = 1
                    i += 1
                    continue

            reply += ch
            i += 1

        # Truncate buf.
        if chop:
            self.buf = self.buf[chop:]

        return replies

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


Question:
// Call returns two values, the name of the template to save
// in the called functions map, and a string that is written
// into the imports

func (f ES6Formatter) Call(name string) (string, string) {
	return ES6Identifier(name), "import { " + ES6Identifier(name) + " } from '" + name + ".js';"
}

def remote(self, func, *args, xfer_func=None, **kwargs):
        """"""
        global HAS_BUFFER
        HAS_BUFFER = self.has_buffer
        if hasattr(func, 'extra_funcs'):
          func_name = func.name
          func_lines = []
          for extra_func in func.extra_funcs:
            func_lines += inspect.getsource(extra_func).split('\n')
            func_lines += ['']
          func_lines += filter(lambda line: line[:1] != '@', func.source.split('\n'))
          func_src = '\n'.join(func_lines)
        else:
          func_name = func.__name__
          func_src = inspect.getsource(func)
        args_arr = [remote_repr(i) for i in args]
        kwargs_arr = ["{}={}".format(k, remote_repr(v)) for k, v in kwargs.items()]
        func_src += 'output = ' + func_name + '('
        func_src += ', '.join(args_arr + kwargs_arr)
        func_src += ')\n'
        func_src += 'if output is None:\n'
        func_src += '    print("None")\n'
        func_src += 'else:\n'
        func_src += '    print(output)\n'
        time_offset = self.time_offset
        if self.adjust_for_timezone:
          time_offset -= time.localtime().tm_gmtoff
        func_src = func_src.replace('TIME_OFFSET', '{}'.format(time_offset))
        func_src = func_src.replace('HAS_BUFFER', '{}'.format(HAS_BUFFER))
        func_src = func_src.replace('BUFFER_SIZE', '{}'.format(BUFFER_SIZE))
        func_src = func_src.replace('IS_UPY', 'True')
        if DEBUG:
            print('----- About to send %d bytes of code to the pyboard -----' % len(func_src))
            print(func_src)
            print('-----')
        self.check_pyb()
        try:
            self.pyb.enter_raw_repl()
            self.check_pyb()
            output = self.pyb.exec_raw_no_follow(func_src)
            if xfer_func:
                xfer_func(self, *args, **kwargs)
            self.check_pyb()
            output, _ = self.pyb.follow(timeout=20)
            self.check_pyb()
            self.pyb.exit_raw_repl()
        except (serial.serialutil.SerialException, TypeError):
            self.close()
            raise DeviceError('serial port %s closed' % self.dev_name_short)
        if DEBUG:
            print('-----Response-----')
            print(output)
            print('-----')
        return output

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


Question:
构建RSA密钥对

@param keySize keySize（必须大于等于512）
@return RSA密钥对

public static KeyHolder buildRSAKey(int keySize) {
        try {
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
            generator.initialize(keySize);
            KeyPair keyPair = generator.generateKeyPair();
            PrivateKey privateKey = keyPair.getPrivate();
            PublicKey publicKey = keyPair.getPublic();
            return new KeyHolder(privateKey, publicKey);
        } catch (NoSuchAlgorithmException e) {
            throw new SecureException("当前系统没有提供生成RSA密钥对的算法", e);
        }
    }

def get_sdr_data_helper(reserve_fn, get_fn, record_id, reservation_id=None):

    if reservation_id is None:
        reservation_id = reserve_fn()

    (next_id, data) = get_fn(reservation_id, record_id, 0, 5)

    header = ByteBuffer(data)
    record_id = header.pop_unsigned_int(2)
    record_version = header.pop_unsigned_int(1)
    record_type = header.pop_unsigned_int(1)
    record_payload_length = header.pop_unsigned_int(1)
    record_length = record_payload_length + 5
    record_data = ByteBuffer(data)

    offset = len(record_data)
    max_req_len = 20
    retry = 20

    # now get the other record data
    while True:
        retry -= 1
        if retry == 0:
            raise RetryError()

        length = max_req_len
        if (offset + length) > record_length:
            length = record_length - offset

        try:
            (next_id, data) = get_fn(reservation_id, record_id, offset, length)
        except CompletionCodeError as e:
            if e.cc == constants.CC_CANT_RET_NUM_REQ_BYTES:
                # reduce max lenght
                max_req_len -= 4
                if max_req_len <= 0:
                    retry = 0
            else:
                raise CompletionCodeError(e.cc)

        record_data.extend(data[:])
        offset = len(record_data)
        if len(record_data) >= record_length:
            break

    return (next_id, record_data)

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


Question: Closes connection to Scratch

def disconnect(self):

        try: # connection may already be disconnected, so catch exceptions
            self.socket.shutdown(socket.SHUT_RDWR) # a proper disconnect
        except socket.error:
            pass
        self.socket.close()
        self.connected = False

def finalize(self):

        self.spinBox.valueChanged.disconnect(self.commitChangedValue)
        super(IntCtiEditor, self).finalize()

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


Question: Terminal oriented; produces a prompt for user input of email and password. Returns crypto.UserLock.

def make_lock_securely(email = None, warn_only = False):
    ""
    email = email or input("Please provide email address: ")
    while True:
        passphrase = getpass.getpass("Please type a secure passphrase (with spaces): ")
        ok, score = check_passphrase(passphrase, email)
        if ok: break
        print("Insufficiently strong passphrase; has {entropy} bits of entropy, could be broken in {crack_time_display}".format(**score))
        if warn_only: break
        print("Suggestion:", make_random_phrase(email))
    key = crypto.UserLock.from_passphrase(email, passphrase)
    return key

def cli(ctx, boring, verbose, zap_path, port, zap_url, api_key, log_path):
    """"""
    console.colorize = not boring

    if verbose:
        console.setLevel('DEBUG')
    else:
        console.setLevel('INFO')

    ctx.obj = ZAPHelper(zap_path=zap_path, port=port, url=zap_url, api_key=api_key, log_path=log_path)

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


Question:
Port part of URL, with scheme-based fallback.

        None for relative URLs or URLs without explicit port and
        scheme without default port substitution.

def port(self):

        return self._val.port or DEFAULT_PORTS.get(self._val.scheme)

func prepareRedirect(options map[int]interface{}) (func(req *http.Request, via []*http.Request) error, error) {
	var redirectPolicy func(req *http.Request, via []*http.Request) error

	if redirectPolicy_, ok := options[OPT_REDIRECT_POLICY]; ok {
		if redirectPolicy, ok = redirectPolicy_.(func(*http.Request, []*http.Request) error); !ok {
			return nil, fmt.Errorf("OPT_REDIRECT_POLICY is not a desired function")
		}
	} else {
		var followlocation bool
		if followlocation_, ok := options[OPT_FOLLOWLOCATION]; ok {
			if followlocation, ok = followlocation_.(bool); !ok {
				return nil, fmt.Errorf("OPT_FOLLOWLOCATION must be bool")
			}
		}

		var maxredirs int
		if maxredirs_, ok := options[OPT_MAXREDIRS]; ok {
			if maxredirs, ok = maxredirs_.(int); !ok {
				return nil, fmt.Errorf("OPT_MAXREDIRS must be int")
			}
		}

		redirectPolicy = func(req *http.Request, via []*http.Request) error {
			// no follow
			if !followlocation || maxredirs <= 0 {
				return &Error{
					Code:    ERR_REDIRECT_POLICY,
					Message: fmt.Sprintf("redirect not allowed"),
				}
			}

			if len(via) >= maxredirs {
				return &Error{
					Code:    ERR_REDIRECT_POLICY,
					Message: fmt.Sprintf("stopped after %d redirects", len(via)),
				}
			}

			last := via[len(via)-1]
			// keep necessary headers
			// TODO: pass all headers or add other headers?
			if useragent := last.Header.Get("User-Agent"); useragent != "" {
				req.Header.Set("User-Agent", useragent)
			}

			return nil
		}
	}

	return redirectPolicy, nil
}

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


Question: Equality function lovingly adapted from isEqual in [Underscore](http://underscorejs.org)

function eq (a, b, aStack, bStack, customTesters) {
    var result = true

    for (var i = 0; i < customTesters.length; i++) {
      var customTesterResult = customTesters[i](a, b)
      if (!j$.util.isUndefined(customTesterResult)) {
        return customTesterResult
      }
    }

    if (a instanceof j$.Any) {
      result = a.jasmineMatches(b)
      if (result) {
        return true
      }
    }

    if (b instanceof j$.Any) {
      result = b.jasmineMatches(a)
      if (result) {
        return true
      }
    }

    if (b instanceof j$.ObjectContaining) {
      result = b.jasmineMatches(a)
      if (result) {
        return true
      }
    }

    if (a instanceof Error && b instanceof Error) {
      return a.message == b.message
    }

    // Identical objects are equal. `0 === -0`, but they aren't identical.
    // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
    if (a === b) { return a !== 0 || 1 / a == 1 / b }
    // A strict comparison is necessary because `null == undefined`.
    if (a === null || b === null) { return a === b }
    var className = Object.prototype.toString.call(a)
    if (className != Object.prototype.toString.call(b)) { return false }
    switch (className) {
      // Strings, numbers, dates, and booleans are compared by value.
      case '[object String]':
        // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
        // equivalent to `new String("5")`.
        return a == String(b)
      case '[object Number]':
        // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
        // other numeric values.
        return a != +a ? b != +b : (a === 0 ? 1 / a == 1 / b : a == +b)
      case '[object Date]':
      case '[object Boolean]':
        // Coerce dates and booleans to numeric primitive values. Dates are compared by their
        // millisecond representations. Note that invalid dates with millisecond representations
        // of `NaN` are not equivalent.
        return +a == +b
      // RegExps are compared by their source patterns and flags.
      case '[object RegExp]':
        return a.source == b.source &&
          a.global == b.global &&
          a.multiline == b.multiline &&
          a.ignoreCase == b.ignoreCase
    }
    if (typeof a != 'object' || typeof b != 'object') { return false }
    // Assume equality for cyclic structures. The algorithm for detecting cyclic
    // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
    var length = aStack.length
    while (length--) {
      // Linear search. Performance is inversely proportional to the number of
      // unique nested structures.
      if (aStack[length] == a) { return bStack[length] == b }
    }
    // Add the first object to the stack of traversed objects.
    aStack.push(a)
    bStack.push(b)
    var size = 0
    // Recursively compare objects and arrays.
    if (className == '[object Array]') {
      // Compare array lengths to determine if a deep comparison is necessary.
      size = a.length
      result = size == b.length
      if (result) {
        // Deep compare the contents, ignoring non-numeric properties.
        while (size--) {
          if (!(result = eq(a[size], b[size], aStack, bStack, customTesters))) { break }
        }
      }
    } else {
      // Objects with different constructors are not equivalent, but `Object`s
      // from different frames are.
      var aCtor = a.constructor, bCtor = b.constructor
      if (aCtor !== bCtor && !(isFunction(aCtor) && (aCtor instanceof aCtor) &&
        isFunction(bCtor) && (bCtor instanceof bCtor))) {
        return false
      }
      // Deep compare objects.
      for (var key in a) {
        if (has(a, key)) {
          // Count the expected number of properties.
          size++
          // Deep compare each member.
          if (!(result = has(b, key) && eq(a[key], b[key], aStack, bStack, customTesters))) { break }
        }
      }
      // Ensure that both objects contain the same number of properties.
      if (result) {
        for (key in b) {
          if (has(b, key) && !(size--)) { break }
        }
        result = !size
      }
    }
    // Remove the first object from the stack of traversed objects.
    aStack.pop()
    bStack.pop()

    return result

    function has (obj, key) {
      return obj.hasOwnProperty(key)
    }

    function isFunction (obj) {
      return typeof obj === 'function'
    }
  }

function hashSet$1(key, value) {
  var data = this.__data__;
  this.size += this.has(key) ? 0 : 1;
  data[key] = nativeCreate$4 && value === undefined ? HASH_UNDEFINED$1 : value;
  return this;
}

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


Question:
// tcsetattr sets terminal file descriptor parameters.
// See man tcsetattr(3).

func tcsetattr(fd int, termios *syscall.Termios) (err error) {
	r, _, errno := syscall.Syscall(uintptr(syscall.SYS_IOCTL),
		uintptr(fd), uintptr(syscall.TIOCSETA), uintptr(unsafe.Pointer(termios)))
	if errno != 0 {
		err = errno
		return
	}
	if r != 0 {
		err = fmt.Errorf("tcsetattr failed %v", r)
	}
	return
}

def _check_local_option(self, option):
        """"""
        if not self.telnet_opt_dict.has_key(option):
            self.telnet_opt_dict[option] = TelnetOption()
        return self.telnet_opt_dict[option].local_option

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


Question:
Returns description of data_for_report() result value.

@return \external_description

public static function data_for_report_returns() {
        return new external_single_structure(array (
            'courseid' => new external_value(PARAM_INT, 'Course id'),
            'user' => user_summary_exporter::get_read_structure(),
            'course' => course_summary_exporter::get_read_structure(),
            'usercompetencies' => new external_multiple_structure(
                new external_single_structure(array(
                    'usercompetencycourse' => user_competency_course_exporter::get_read_structure(),
                    'competency' => competency_summary_exporter::get_read_structure()
                ))
            ),
            'pushratingstouserplans' => new external_value(PARAM_BOOL, 'True if rating is push to user plans')
        ));
    }

public function setCallbacks() {
        if ($this->jasperClient) {
            //Get the entity manager
            $em = $this->container->get('doctrine')->getManager($this->entityManager);
            $this->jasperClient->addPostReportExecutionCallback(new PostReportExecution($em, $this->container->get('security.context')));
            $this->jasperClient->addPostReportCacheCallback(new PostReportCache($em));
        }
    }

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


Question: Returns all option values stored that match p as a list.

def getoptlist(self, p):
        """"""
        optlist = []
        for k, v in self.pairs:
            if k == p:
                optlist.append(v)
        return optlist

function parseOptions(input, callback, keyValueDelim, groupDelim) {
    var groups = groupDelim ? input.split(groupDelim) : [input];
    for (var i in groups) {
      if (typeof groups[i] !== "string") {
        continue;
      }
      var kv = groups[i].split(keyValueDelim);
      if (kv.length !== 2) {
        continue;
      }
      var k = kv[0];
      var v = kv[1];
      callback(k, v);
    }
  }

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


Question:
Checks registered hooks if a SerializedValueDetector detects a serialized response.

@param array $indexingConfiguration
@param string $solrFieldName
@return bool

protected static function isSerializedResultFromRegisteredHook(array $indexingConfiguration, $solrFieldName)
    {
        if (!is_array($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['detectSerializedValue'])) {
            return false;
        }

        foreach ($GLOBALS['TYPO3_CONF_VARS']['EXTCONF']['solr']['detectSerializedValue'] as $classReference) {
            $serializedValueDetector = GeneralUtility::makeInstance($classReference);
            if (!$serializedValueDetector instanceof SerializedValueDetector) {
                $message = get_class($serializedValueDetector) . ' must implement interface ' . SerializedValueDetector::class;
                throw new \UnexpectedValueException($message, 1404471741);
            }

            $isSerialized = (boolean)$serializedValueDetector->isSerializedValue($indexingConfiguration, $solrFieldName);
            if ($isSerialized) {
                return true;
            }
        }
    }

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

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

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

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

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


Question: // NewAdapter is a constructor.

func NewAdapter(registerHTTPHandler registerHTTPHandler, localtransp *syncbase.Registry) *Adapter {
	return &Adapter{registerHTTPHandler: registerHTTPHandler, base: localtransp}
}

public function getNewComment(Portfolio $portfolio, User $user)
    {
        $comment = $this->commentFactory->createComment($portfolio, $user);

        return $comment;
    }

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


Question:
Return an array overwrite if found same key containing the elements in each()

@return array

public function toArray()
    {
        $result = [];
        foreach ($this->each() as $k => $v) {
            $this->_toArray($result, $k, $v);
        }
        return $result;
    }

public function content()
    {
        $out = [
            'content' => []
        ];

        foreach ($this->_contentAreas as $contentArea) {
            $out['content'][] = $contentArea->toArray();
        }

        return $out;
    }

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


Question:
Translates a SQL SIMILAR pattern to Java regex pattern, with optional
escape string.

static String sqlToRegexSimilar(
		String sqlPattern,
		CharSequence escapeStr) {
		final char escapeChar;
		if (escapeStr != null) {
			if (escapeStr.length() != 1) {
				throw invalidEscapeCharacter(escapeStr.toString());
			}
			escapeChar = escapeStr.charAt(0);
		} else {
			escapeChar = 0;
		}
		return sqlToRegexSimilar(sqlPattern, escapeChar);
	}

public static Writer getInstance(Writer out) {
		// Already in Unix format, no conversion necessary
		if(UNIX_EOL.equals(EOL)) return out;
		// Use FindReplaceWriter
		return new FindReplaceWriter(out, EOL, UNIX_EOL);
	}

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


Question:
Quick shortcut to get mastery information by $masteryId

@param int $masteryId
@return Mastery|null

public function getMastery($masteryId)
	{
		if (isset($this->info['data'][$masteryId]))
		{
			return $this->info['data'][$masteryId];
		}

		return null;
	}

public static function findParamValue(&$value, &$operator): bool
    {
        if (is_array($value) || is_object($value)) {
            $value = static::assembleParamValue($value, $operator);
        } else {
            self::normalizeEmptyValue($value);

            $operator = self::parseParamOperator($value);

            if (is_numeric($value)) {
                $value = self::prependOperator($value, $operator);
            } else {
                $value = StringHelper::toLowerCase($value);

                if ($value !== ':empty:' || $value !== 'not :empty:') {
                    // Trim any whitespace from the value
                    $value = StringHelper::trim($value);

                    return false;
                }
            }
        }

        return true;
    }

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


Question: // FindResources selects a set of resource objects and returns them.

func FindResources(tx ReadTx, by By) ([]*api.Resource, error) {
	checkType := func(by By) error {
		switch by.(type) {
		case byIDPrefix, byName, byNamePrefix, byKind, byCustom, byCustomPrefix:
			return nil
		default:
			return ErrInvalidFindBy
		}
	}

	resourceList := []*api.Resource{}
	appendResult := func(o api.StoreObject) {
		resourceList = append(resourceList, o.(resourceEntry).Resource)
	}

	err := tx.find(tableResource, by, checkType, appendResult)
	return resourceList, err
}

public function initSelection(GroupType $type, $name = 'group')
    {
        $group_name = $type->getName();

        if(!array_key_exists($group_name, $this->units))
        {
            $this->units[$group_name] = [];
        }

        if(array_key_exists($name, $this->units[$group_name]))
        {
            throw new ExtractorException('Выборка для группы '.$group_name.' по имени '.$name.' уже создана!');
        }

        $paramSet         = new ParamSet($type);
        $sortingSet       = new SortingSet($type);
        $specificationSet = new SpecificationSet($type);

        $unit = new SelectionUnit($type, $paramSet, $sortingSet, $specificationSet, $name);

        $this->units[$group_name][$name] = $unit;

        return $unit;
    }

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


Question:
Set Item creator.

@param Account|string $objectOrId User or his ID.

@throws \InvalidArgumentException

@since 0.1

public function setCreator($objectOrId)
    {
        $this->dropCachedProperty('creator');
        if (!$objectOrId instanceof Account) {
            $objectOrId = new Account(['id' => $objectOrId]);
        }

        $this->setValue('creator', $objectOrId->export());
    }

public function addExpression(
            O\Expression $expression,
            IParameterHasher $hasher,
            IFunction $context = null,
            $data = null
    ) {
        $this->parameters[] = new ExpressionParameter($expression, $hasher, $context, $data);
    }

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


Question:
Adds a range to be looked up.

@param start The beginning of the range (inclusive). Can be null to represent negative
infinity.
@param end The end of the range (exclusive). Can be null to represent positive infinity.

public Query range(ByteString start, ByteString end) {
    RowRange.Builder rangeBuilder = RowRange.newBuilder();
    if (start != null) {
      rangeBuilder.setStartKeyClosed(start);
    }
    if (end != null) {
      rangeBuilder.setEndKeyOpen(end);
    }
    builder.getRowsBuilder().addRowRanges(rangeBuilder.build());
    return this;
  }

protected function applyFilters(QueryBuilder $qb, array $filters)
    {
        $definition = $this->objectDefinition;
        foreach ($filters as $field => $value) {
            if (!$definition->hasField($field) || !$prop = $definition->getField($field)->getOriginName()) {
                continue;
            }

            $entityField = sprintf('%s.%s', $this->queryAlias, $prop);

            switch (gettype($value)) {
                case 'string':
                    $qb->andWhere($qb->expr()->eq($entityField, $qb->expr()->literal($value)));
                    break;
                case 'integer':
                case 'double':
                    $qb->andWhere($qb->expr()->eq($entityField, $value));
                    break;
                case 'boolean':
                    $qb->andWhere($qb->expr()->eq($entityField, (int) $value));
                    break;
                case 'array':
                    if (empty($value)) {
                        $qb->andWhere($qb->expr()->isNull($entityField));
                    } else {
                        $qb->andWhere($qb->expr()->in($entityField, $value));
                    }
                    break;
                case 'NULL':
                    $qb->andWhere($qb->expr()->isNull($entityField));
                    break;
            }
        }
    }

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


Question:
Читает конфигурации разработчика с локальной машины или из переменных окружения
    При этом переменная окружения приоритетнее

    :return: dict|None

def read_developer_settings():

    ret = read_cfg("/.rwmeta/developer_settings.json")

    env_developer_settings = os.environ.get('META_SERVICE_ACCOUNT_SECRET', None)
    if not env_developer_settings:
        env_developer_settings = os.environ.get('X-META-Developer-Settings', None)
    if env_developer_settings:
        ret = json.loads(env_developer_settings)

    return ret

def get_interface_detail_output_interface_ifHCInErrors(self, **kwargs):

        config = ET.Element("config")
        get_interface_detail = ET.Element("get_interface_detail")
        config = get_interface_detail
        output = ET.SubElement(get_interface_detail, "output")
        interface = ET.SubElement(output, "interface")
        interface_type_key = ET.SubElement(interface, "interface-type")
        interface_type_key.text = kwargs.pop('interface_type')
        interface_name_key = ET.SubElement(interface, "interface-name")
        interface_name_key.text = kwargs.pop('interface_name')
        ifHCInErrors = ET.SubElement(interface, "ifHCInErrors")
        ifHCInErrors.text = kwargs.pop('ifHCInErrors')

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

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


Question:
Edit the parameters.

@param Request $request
@return \Symfony\Component\HttpFoundation\Response

public function editAction(Request $request)
    {
        $this->isGranted('EDIT');

        $this->container->get('ekyna_admin.menu.builder')
            ->breadcrumbAppend('settings', 'ekyna_setting.parameter.label.plural');

        $manager = $this->getSettingsManager();
        $schemas = $this->getSettingsRegistry()->getSchemas();

        $settings = [];
        $builder = $this
            ->createFormBuilder(null, [
                'data_class' => null,
                'admin_mode' => true,
                'cascade_validation' => true,
            ])
            ->add('actions', 'form_actions', [
                'buttons' => [
                    'save' => [
                        'type' => 'submit', 'options' => [
                            'button_class' => 'primary',
                            'label' => 'ekyna_core.button.save',
                            'attr' => [
                                'icon' => 'ok',
                            ],
                        ],
                    ],
                    'cancel' => [
                        'type' => 'button', 'options' => [
                            'label' => 'ekyna_core.button.cancel',
                            'button_class' => 'default',
                            'as_link' => true,
                            'attr' => [
                                'class' => 'form-cancel-btn',
                                'icon' => 'remove',
                                'href' => $this->generateUrl('ekyna_setting_parameter_admin_show'),
                            ],
                        ],
                    ],
                ],
            ])
        ;
        foreach($schemas as $namespace => $schema) {
            $builder->add($namespace, $schema);
            $settings[$namespace] = $manager->loadSettings($namespace);
        }

        $form = $builder
            ->getForm()
            ->setData($settings)
        ;

        if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
            $messageType = 'success';
            try {
                foreach($schemas as $namespace => $schema) {
                    $manager->saveSettings($namespace, $form->get($namespace)->getData());
                }
                $message = $this->getTranslator()->trans('ekyna_setting.parameter.flash.edit');
            } catch (ValidatorException $exception) {
                $message = $this->getTranslator()->trans($exception->getMessage(), [], 'validators');
                $messageType = 'danger';
            }
            $this->addFlash($message, $messageType);

            return $this->redirect($this->generateUrl('ekyna_setting_parameter_admin_show'));
        }

        return $this->render('EkynaSettingBundle:Settings:edit.html.twig', [
            'labels'     => $manager->getLabels(),
            'templates'  => $manager->getFormTemplates(),
            'form'       => $form->createView(),
        ]);
    }

public ApiSuccessResponse modifyOutboundSettings(ModifyOutboundData body) throws ApiException {
        ApiResponse<ApiSuccessResponse> resp = modifyOutboundSettingsWithHttpInfo(body);
        return resp.getData();
    }

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


Question:
Initializes a box in order to be a proper child box of the specified parent. Copies
all the necessary information from the parent.
@param parent the parent box

public void adoptParent(ElementBox parent)
    {
        if (parent instanceof BlockBox)
            setContainingBlockBox(parent);
        else
            setContainingBlockBox(parent.getContainingBlockBox());
        setParent(parent);
        setViewport(parent.getViewport());
        setClipBlock(parent.getClipBlock());
    }

private function loadParameters(ContainerBuilder $container)
    {
        $container->setParameter('gherkin.paths.lib', $this->getLibPath());
        $container->setParameter('gherkin.paths.i18n', '%gherkin.paths.lib%/i18n.php');
        $container->setParameter(
            'suite.generic.default_settings',
            array(
                'paths'    => array('%paths.base%/features'),
                'contexts' => array('FeatureContext')
            )
        );
    }

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


Question: // NewDecoderMock creates new instance of the mock and initializes response list

func NewDecoderMock() *Mock {
	return &Mock{
		responses: make([]*WhenResp, 0),
		eventChan: make(chan fsnotify.Event),
	}
}

protected function initQueue($ipc_filename, $msg_type)
    {
        $this->key_t = $this->getIpcKey($ipc_filename, $msg_type);
        $this->queue = \msg_get_queue($this->key_t);
        if (!$this->queue) throw new \RuntimeException('msg_get_queue failed');
    }

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


Question:
Download actvity log

@return \Symfony\Component\HttpFoundation\Response

public function download()
    {
        set_time_limit(0);
        ini_set('max_execution_time', 0);
        ignore_user_abort();

        $datatable = app(ActivityLogs::class);

        list($headers, $data) = $this->prepareHeadersAndKeys($datatable);
        $items = $this->prepareContent($datatable, $data);

        $top      = implode(self::separator, $headers);
        $content  = implode("\n", $items);
        $csv      = implode("\n", [$top, $content]);
        $date     = date('Y_m_d_H_i_s', time());
        $filename = "activity_log_{$date}.csv";

        return response($csv, 200, [
            'Content-Type'              => 'text/csv',
            'Content-Description'       => 'File Transfer',
            'Content-Disposition'       => 'attachment; filename=' . $filename,
            'Content-Transfer-Encoding' => 'binary',
            'Connection'                => 'Keep-Alive',
            'Expires'                   => '0',
            'Cache-Control'             => 'must-revalidate, post-check=0, pre-check=0',
            'Pragma'                    => 'public',
            'Content-Length'            => strlen($csv)]);
    }

public function changeAction(ChangeCollection $changes)
    {
        try {
            $count = $changes->count();
            $changes->apply();

            $success = new Info();
            $success->setMessage(sprintf('%d change(s) successfully applied.', $count));

            $this->feedbackCollection->add($success);
            $this->persistenceManager->persistAll();
        } catch (\Exception $e) {
            $error = new Error();
            $error->setMessage($e->getMessage());

            $this->feedbackCollection->add($error);
        }

        $this->view->assign('value', $this->feedbackCollection);
    }

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


Question:
Parse the 'extension' element
@param element The element
@return A {@link Extension} instance for the element

private static <T> Extension<T> parseBinderExtensionElement(Element element) {

        @SuppressWarnings("unchecked")
		Class<T> providerClass = (Class<T>)lookupClass(element.getAttribute("class"));

        Class<?> implementationClass = lookupClass(element.getAttribute("implementationClass"));

        if (providerClass == null) {
            throw new IllegalStateException("Referenced class {" + element.getAttribute("class")
                    + "} could not be found");
        }
        if (implementationClass == null) {
            throw new IllegalStateException("Referenced implementation class {" + element.getAttribute("implementationClass")
                    + "} could not be found");
        }
        if (providerClass.isAssignableFrom(implementationClass)) {
            throw new IllegalStateException("Referenced class {" + element.getAttribute("class")
                    + "} did not implement BindingProvider");
        }

		try {
			@SuppressWarnings("unchecked")
			final Class<? extends T> myImplementationClass = (Class<T>) implementationClass.newInstance();
			return new Extension<T>(providerClass, myImplementationClass);
		} catch (InstantiationException e) {
            throw new IllegalStateException("Referenced implementation class {" + element.getAttribute("implementationClass")
                    + "} could not be instantiated");
		} catch (IllegalAccessException e) {
            throw new IllegalStateException("Referenced implementation class {" + element.getAttribute("implementationClass")
                    + "} could not be accessed");
		}
    }

def extract_hash_pair(node, key)
      node.children.detect do |child|
        next unless child.type == :pair
        key_node = child.children[0]
        %i[sym str].include?(key_node.type) && key_node.children[0].to_s == key
      end
    end

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


Question: extract the article version history details

def version_history(soup, html_flag=True):
    ""
    convert = lambda xml_string: xml_to_html(html_flag, xml_string)
    version_history = []
    related_object_tags = raw_parser.related_object(raw_parser.article_meta(soup))
    for tag in related_object_tags:
        article_version = OrderedDict()
        date_tag = first(raw_parser.date(tag))
        if date_tag:
            copy_attribute(date_tag.attrs, 'date-type', article_version, 'version')
            (day, month, year) = ymd(date_tag)
            article_version['day'] = day
            article_version['month'] = month
            article_version['year'] = year
            article_version['date'] = date_struct_nn(year, month, day)
        copy_attribute(tag.attrs, 'xlink:href', article_version, 'xlink_href')
        set_if_value(article_version, "comment",
                     convert(node_contents_str(first(raw_parser.comment(tag)))))
        version_history.append(article_version)
    return version_history

@Override
  public String getVersion(URI uri) throws IOException
  {
    try {
      return StringUtils.format("%d", buildFileObject(uri, config).getLastModified());
    }
    catch (HdfsIOException ex) {
      throw ex.getIOException();
    }
  }

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


function createDateTimeFormatter( type, inputFormat ) {
   return ( options, value ) => {
      if( value == null ) {
         return '';
      }

      if( value instanceof Date ) {
         return format( moment( value ) );
      }

      if( typeof value !== 'string' ) {
         throw argumentError( value );
      }

      const useInputFormat = value.length < ISO_FULL_FORMAT_MIN_LENGTH;
      const momentTime = value.toLowerCase() === 'now' ?
         moment() :
         moment( value, useInputFormat ? inputFormat : undefined, useInputFormat || undefined );

      if( !momentTime.isValid() ) {
         throw argumentError( value );
      }

      return format( momentTime );

      ////////////////////////////////////////////////////////////////////////////////////////////////////////

      function format( momentTime ) {
         return momentTime.format( options[ `${type}Format` ] );
      }

      function argumentError( value ) {
         return new TypeError(
            'Expected argument to be a Date object, the string "NOW", or an ISO-8601 string ' +
            `(full, or ${type} as ${inputFormat}), but got "${typeof value}". Value: ${value}`
         );
      }
   };
}

public final void inlineListExpression() throws RecognitionException {
		try {
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:5: ( LEFT_SQUARE ( expressionList )? RIGHT_SQUARE )
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:9: LEFT_SQUARE ( expressionList )? RIGHT_SQUARE
			{
			match(input,LEFT_SQUARE,FOLLOW_LEFT_SQUARE_in_inlineListExpression3100); if (state.failed) return;
			// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:21: ( expressionList )?
			int alt61=2;
			int LA61_0 = input.LA(1);
			if ( (LA61_0==BOOL||(LA61_0 >= DECIMAL && LA61_0 <= DECR)||LA61_0==FLOAT||LA61_0==HEX||(LA61_0 >= ID && LA61_0 <= INCR)||(LA61_0 >= LEFT_PAREN && LA61_0 <= LESS)||LA61_0==MINUS||LA61_0==NEGATION||LA61_0==NULL||LA61_0==PLUS||(LA61_0 >= STAR && LA61_0 <= TIME_INTERVAL)) ) {
				alt61=1;
			}
			switch (alt61) {
				case 1 :
					// src/main/resources/org/drools/compiler/lang/DRL5Expressions.g:560:21: expressionList
					{
					pushFollow(FOLLOW_expressionList_in_inlineListExpression3102);
					expressionList();
					state._fsp--;
					if (state.failed) return;
					}
					break;

			}

			match(input,RIGHT_SQUARE,FOLLOW_RIGHT_SQUARE_in_inlineListExpression3105); if (state.failed) return;
			}

		}

		catch (RecognitionException re) {
		    throw re;
		}

		finally {
			// do for sure before leaving
		}
	}

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


Question:
Turn notifications on.

 @param [Hash] options the turn_on options
 @option options [Boolean] silent disable any logging

def turn_on(options = {})
      _check_server!
      return unless enabled?

      fail "Already active!" if active?

      _turn_on_notifiers(options)
      _env.notify_active = true
    end

public function display()
    {
        if (!$this->visible) {
            return;
        }

        SwatWidget::display();

        if ($this->alt == '') {
            throw new SwatException(
                'The $alt property of SwatImageButton must be set to an ' .
                    'appropriate value. The "alt" attribute is required in ' .
                    'HTML5 and can not be an empty string.'
            );
        }

        $input_tag = new SwatHtmlTag('input');
        $input_tag->type = 'image';
        $input_tag->id = $this->id;
        $input_tag->name = $this->id;
        $input_tag->value = $this->title;
        $input_tag->alt = $this->alt;
        $input_tag->class = $this->getCSSClassString();

        if (count($this->values)) {
            $input_tag->src = vsprintf($this->image, $this->values);
        } else {
            $input_tag->src = $this->image;
        }

        $input_tag->tabindex = $this->tab_index;
        $input_tag->accesskey = $this->access_key;

        if (!$this->isSensitive()) {
            $input_tag->disabled = 'disabled';
        }

        $input_tag->display();

        if (
            $this->show_processing_throbber ||
            $this->confirmation_message !== null
        ) {
            Swat::displayInlineJavaScript($this->getInlineJavaScript());
        }
    }

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


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

@Override
  public long skip(long n) throws IOException {
    return n > 0 ? (long) inner.skip(Math.min(n, remaining)) : 0;
  }

protected void checkOutput()
    {
        if (_out==_realOut)
        {
            if (_bufferedOut==null)
            {
                _bufferedOut=new ChunkingOutputStream(_realOut,
                                                      _bufferSize,
                                                      _headerReserve,
                                                      false);
                _bufferedOut.setCommitObserver(this);
                _bufferedOut.setBypassBuffer(true);
                _bufferedOut.setFixed(true);
            }
            _out=_bufferedOut;
        }
    }

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