comment
stringlengths
16
255
code
stringlengths
52
3.87M
Calls the specified handler when this promise is fulfilled. If the handler returns a promise, @param callable $handler @return PromiseInterface
public function to($handler /*, $args… */) { $args = array_slice(func_get_args(), 1); return $this->then( function (Allocation $allocation) use ($handler, $args) { try { $result = call_user_func_array($handler, $args); $result = \R...
Make JsonResponse :param rv: Response: the object to encode, or tuple (response, status, headers) :type rv: tuple|* :rtype: JsonResponse
def make_json_response(rv): # Tuple of (response, status, headers) rv, status, headers = normalize_response_value(rv) # JsonResponse if isinstance(rv, JsonResponse): return rv # Data return JsonResponse(rv, status, headers)
Computes the bounding circle @param geometry @return
public static Geometry computeBoundingCircle(Geometry geometry) { if (geometry == null) { return null; } return new MinimumBoundingCircle(geometry).getCircle(); }
// NewMockClientFacade creates a new mock instance
func NewMockClientFacade(ctrl *gomock.Controller) *MockClientFacade { mock := &MockClientFacade{ctrl: ctrl} mock.recorder = &MockClientFacadeMockRecorder{mock} return mock }
Describes tget_grades_table return value. @return external_single_structure @since Moodle 2.9
public static function get_grades_table_returns() { return new external_single_structure( array( 'tables' => new external_multiple_structure( new external_single_structure( array( 'courseid' => new external_value...
/* getWsagObject receives in serializedData the object information in xml must returns a eu.atos.sla.parser.data.wsag.Agreement
@Override public Agreement getWsagObject(String serializedData) throws ParserException{ Agreement agreementXML = null; try{ logger.info("Will parse {}", serializedData); JAXBContext jaxbContext = JAXBContext.newInstance(Agreement.class); Unmarshaller jaxbUnmarshal...
Visit the given $query parameters into hash representation.
private function visitParameters(Query $query, VisitorInterface $subVisitor): array { $parametersByLanguage = [ $query->getLocale() => iterator_to_array( $this->visitTranslationParameters($query, $subVisitor) ), ]; foreach ($query->getAvailableLocales...
Try to restore user from data in session. @return void
protected static function restoreFromSession() { $session = Http\Session::getInstance(); try { $mapper = new UserMapper(Database::get()); $user = $mapper->findFromSession($session); } catch (\Exception $exception) { $user = new Data\User\User(); ...
// Init will initialize or reset a StringTree.
func (t *StringTree) Init(flags byte) *StringTree { t.Tree.Init(stringCompare, flags) return t }
Resize the given BufferedImage. @param originalImage the original image @param formatName the format name @param targetWidth the target width @param targetHeight the target height @return the byte[]
public static byte[] resize(final BufferedImage originalImage, final String formatName, final int targetWidth, final int targetHeight) { return resize(originalImage, Scalr.Method.QUALITY, Scalr.Mode.FIT_EXACT, formatName, targetWidth, targetHeight); }
Close a ResultSet @param rs a database ResultSet object
public static void closeResultSet(final ResultSet rs) { if (rs == null) { return; } try { rs.close(); } catch (Exception e) { if (LOG.isWarnEnabled()) LOG.warn("Error closing ResultSet: " + rs, e); } }
Recurse through the data tree and fill an array of paths that reference the nodes in the decoded JSON data structure. @param mixed $s Decoded JSON data (decoded with json_decode) @param string $r The current path key (for example: '#children.0').
private function getPaths(&$s, $r = "#") { $this->paths[$r] = &$s; if (is_array($s) || is_object($s)) { foreach ($s as $k => &$v) { if ($k !== "\$ref") { $this->getPaths($v, $r == "#" ? "#{$k}" : "{$r}.{$k}"); } } } ...
TODO handler.addTo
function (name, HandlerClass) { if (!HandlerClass) { return this; } var handler = this[name] = new HandlerClass(this); this._handlers.push(handler); if (this.options[name]) { handler.enable(); } return this; }
expression : LNOT expression %prec ULNOT
def p_expression_ulnot(self, p): '' p[0] = Ulnot(p[2], lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
Checks if the current user has the specified role. @param roleNames the names of the required roles @return true iff the current user has the specified role
public static boolean hasRoles(List<String> roleNames) throws Throwable { DEADBOLT_HANDLER.beforeRoleCheck(); RoleHolder roleHolder = getRoleHolder(); return roleHolder != null && roleHolder.getRoles() != null && hasAllRoles(roleHolder, ...
Create an instance of {@link JAXBElement }{@code <}{@link ArithType }{@code >}}
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "abs") public JAXBElement<ArithType> createAbs(ArithType value) { return new JAXBElement<ArithType>(_Abs_QNAME, ArithType.class, null, value); }
// SetStatus sets the completion status of the Package.
func (p *Package) SetStatus(inc JobStatus) { p.statusLock.Lock() defer p.statusLock.Unlock() p.status = inc }
Returns warning according to GetSystemPowerStatus().BatteryLifeTime/BatteryLifePercent @raise WindowsError if any underlying error occures.
def get_low_battery_warning_level(self): power_status = SYSTEM_POWER_STATUS() if not GetSystemPowerStatus(pointer(power_status)): raise WinError() if POWER_TYPE_MAP[power_status.ACLineStatus] == common.POWER_TYPE_AC: return common.LOW_BATTERY_WARNING_NONE ...
Create a CryptKey instance without permissions check. @param string $key @return \League\OAuth2\Server\CryptKey
protected function makeCryptKey($type) { $key = str_replace('\\n', "\n", $this->app->make(Config::class)->get('passport.'.$type.'_key')); if (! $key) { $key = 'file://'.Passport::keyPath('oauth-'.$type.'.key'); } return new CryptKey($key, null, false); }
Gets a configuration. @param key the configuration key @return a map, or null if the key is not found
public synchronized Map<String, Object> getConfiguration(String key) { return Optional.ofNullable(inventory.get(key)) .flatMap(v->v.getConfiguration()) .map(v->v.getMap()) .orElse(null); }
// Start starts the scheduler
func (s *scheduler) Start() error { if s.metricManager == nil { schedulerLogger.WithFields(log.Fields{ "_block": "start-scheduler", "_error": ErrMetricManagerNotSet.Error(), }).Error("error on scheduler start") return ErrMetricManagerNotSet } s.state = schedulerStarted schedulerLogger.WithFields(log.Fie...
A specific, existing tag can be deleted by making a DELETE request on the URL for that tag. Returns an empty data record. @param tag The tag to delete. @return response
public function delete($tag, $params = array(), $options = array()) { $path = sprintf("/tags/%s", $tag); return $this->client->delete($path, $params, $options); }
Validate a value @param mixed $value Value to be validated @return bool True when the variable is valid
public function validate($value) { $result = false; if (is_string($value) && strlen($value)) { if ($value[0] == '/' || $value[0] == '\\' || (strlen($value) > 3 && ctype_alpha($value[0]) && $value[1] == ':' && ($value[2] == ...
Saves the service and types php code to file @param PhpClass $service @param array $types
public function save(PhpClass $service, array $types) { $this->setOutputDirectory(); $this->saveClassToFile($service); foreach ($types as $type) { $this->saveClassToFile($type); } $classes = array_merge(array($service), $types); $this->saveAutoloader($se...
Gets the list of entries in the specified directory. @param directory the directory to get the entries of. @return the list of entries (never <code>null</code>). @since 1.0
private synchronized List<Entry> getEntriesList( DirectoryEntry directory ) { List<Entry> entries = contents.get( directory ); if ( entries == null ) { entries = new ArrayList<Entry>(); contents.put( directory, entries ); } return entries; }
Checks, that option exists in config. @param string $name Option name. @return void @throws ConfigException Thrown when option with a given name doesn't exist.
protected function assertOptionName($name) { if ( !isset($this->options[$name]) ) { throw new ConfigException( 'Option "' . $name . '" doesn\'t exist in configuration', ConfigException::TYPE_NOT_FOUND ); } }
// WeekdayShort returns the locales short weekday given the 'weekday' provided
func (kkj *kkj_CM) WeekdayShort(weekday time.Weekday) string { return kkj.daysShort[weekday] }
// For any index defined by IndexFields, if a matcher can match only (a subset) // of objects that return <value> for a given index, a pair (<index name>, <value>) // wil be returned. // TODO: Consider supporting also labels.
func (s *SelectionPredicate) MatcherIndex() []MatchValue { var result []MatchValue for _, field := range s.IndexFields { if value, ok := s.Field.RequiresExactMatch(field); ok { result = append(result, MatchValue{IndexName: field, Value: value}) } } return result }
// SetId sets the Id field's value.
func (s *GetBucketAnalyticsConfigurationInput) SetId(v string) *GetBucketAnalyticsConfigurationInput { s.Id = &v return s }
Overloaded to display the correctly formatted value for this data type @param array $properties @return string
public function Field($properties = array()) { if ($this->value) { $val = Convert::raw2xml($this->value); $val = DBCurrency::config()->get('currency_symbol') . number_format(preg_replace('/[^0-9.-]/', '', $val), 2); $valforInput = Convert::raw2att($val); ...
分词时查询到一个用户词典中的词语,此处控制是否接受它 @param begin 起始位置 @param end 终止位置 @param value 词性 @return true 表示接受 @deprecated 自1.6.7起废弃,强制模式下为最长匹配,否则按分词结果合并
protected boolean acceptCustomWord(int begin, int end, CoreDictionary.Attribute value) { return config.forceCustomDictionary || (end - begin >= 4 && !value.hasNatureStartsWith("nr") && !value.hasNatureStartsWith("ns") && !value.hasNatureStartsWith("nt")); }
是否可以删除缓存 @param cacheDeleteKey CacheDeleteKey注解 @param arguments 参数 @param retVal 结果值 @return Can Delete @throws Exception 异常
public boolean isCanDelete(CacheDeleteKey cacheDeleteKey, Object[] arguments, Object retVal) throws Exception { boolean rv = true; if (null != arguments && arguments.length > 0 && null != cacheDeleteKey.condition() && cacheDeleteKey.condition().length() > 0) { rv = this.g...
Factory function that creates a value. :param value_id: id of the value, used to reference the value within this list.BaseException :param value_class: The class of the value that should be created with this function.
def add(self, value_id, name, value_class): item = value_class( name, value_id=self.controller.component_id + "." + value_id, is_input=self.is_input, index=self.count, spine = self.controller.spine ) #if self._inject and self....
Updates the state machine context.
void update(long index, Instant instant, Type type) { this.index = index; this.type = type; clock.set(instant); }
Creates a {@link UTF8StreamJsonParser} from the inputstream with the supplied buf {@code inBuffer} to use.
public static UTF8StreamJsonParser newJsonParser(InputStream in, byte[] buf, int offset, int limit) throws IOException { return newJsonParser(in, buf, offset, limit, false, new IOContext(DEFAULT_JSON_FACTORY._getBufferRecycler(), in, false)); }
// LoadGopmfile loads and returns given gopmfile.
func LoadGopmfile(fileName string) (*goconfig.ConfigFile, error) { if !base.IsFile(fileName) { return goconfig.LoadFromData([]byte("")) } gf, err := goconfig.LoadConfigFile(fileName) if err != nil { return nil, fmt.Errorf("Fail to load gopmfile: %v", err) } return gf, nil }
Loads a collection from the database @param array|int|string $condition @return array
public function get($condition) { $result = null; $this->hook->attach('collection.get.before', $condition, $result, $this); if (isset($result)) { return $result; } if (!is_array($condition)) { $condition = array('collection_id' => $condition); ...
Performs a forward pass using multiple GPUs. This is a simplification of torch.nn.parallel.data_parallel to support the allennlp model interface.
def data_parallel(batch_group: List[TensorDict], model: Model, cuda_devices: List) -> Dict[str, torch.Tensor]: assert len(batch_group) <= len(cuda_devices) moved = [nn_util.move_to_device(batch, device) for batch, device in zip(batch_group, cuda_devices)] ...
Randomly augment a single image tensor. # Arguments sample: 3D or 4D tensor, single sample. seed: random seed. # Returns A randomly transformed version of the input (same shape).
def random_transform(self, sample, seed=None): img_row_axis = self.row_axis - 1 img_col_axis = self.col_axis - 1 img_channel_axis = self.channel_axis - 1 transform_matrix = self.get_random_transform_matrix(sample, seed) if transform_matrix is not None: h, w...
Gets the list of Microsoft.CognitiveServices SKUs available for your Subscription. @throws IllegalArgumentException thrown if parameters fail the validation @return the observable to the PagedList&lt;ResourceSkuInner&gt; object
public Observable<Page<ResourceSkuInner>> listAsync() { return listWithServiceResponseAsync() .map(new Func1<ServiceResponse<Page<ResourceSkuInner>>, Page<ResourceSkuInner>>() { @Override public Page<ResourceSkuInner> call(ServiceResponse<Page<ResourceSkuInner>> respo...
// Machine provides access to methods of a state.Machine through the facade.
func (st *State) Machine(tag names.MachineTag) (*Machine, error) { life, err := st.machineLife(tag) if err != nil { return nil, errors.Annotate(err, "can't get life for machine") } return &Machine{ tag: tag, life: life, st: st, }, nil }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__OBJ_TYPE: setObjType(OBJ_TYPE_EDEFAULT); return; case AfplibPackage.OBJECT_FUNCTION_SET_SPECIFICATION__ARCH_VRSN: setArchVrsn(ARCH_VRSN_EDEFAULT); return; case AfplibPacka...
Tries to find a directory with a .git repository
def find_git_repository(self, path): while path is not None: git_path = os.path.join(path,'.git') if os.path.exists(git_path) and os.path.isdir(git_path): return path path = os.path.dirname(path) return None
指定したK値、対象点、データセットを基に局所外れ係数スコアを算出する。<br> 本メソッド呼び出しによってデータセットの更新は行われない。<br> 学習データの更新を伴わないため、高速に処理が可能となっている。 @param kn K値 @param targetPoint 対象点 @param dataSet 学習データセット @return LOFスコア
public static double calculateLofWithoutUpdate(int kn, LofPoint targetPoint, LofDataSet dataSet) { // 対象点のK距離、K距離近傍を算出する。 KDistanceResult kResult = calculateKDistance(kn, targetPoint, dataSet); LofPoint tmpPoint = targetPoint.deepCopy(); tmpPoint.setkDistance(kResult.getkDistance())...
Sets the time zone for which this <code>Calendar</code> will be resolved. @param \DateTimeZone $timeZone The time zone to use for this Calendar, null if default should be used
public function setTimeZone(\DateTimeZone $timeZone = null) { if ($timeZone) { $value = $timeZone->getName(); } else { $value = null; } $this->setValue('timezone', $value); }
Builds thumb uploader @param string $dir Target directory @param integer $quality Desired quality for thumbs @param array $options @return \Krystal\Image\Tool\Upload\Plugin\ThumbFactory
public function build($dir, $quality, array $options = array()) { // Alter default quality on demand if (isset($options['quality'])) { $quality = $options['quality']; } return new Thumb($dir, $options['dimensions'], $quality); }
Parses a PHP File and returns nested Array of collected Information. @access public @param string $fileName File Name of PHP File to parse @param string $innerPath Base Path to File to be removed in Information @return array
public function parseFile( $fileName, $innerPath ) { $content = FS_File_Reader::load( $fileName ); if( !Alg_Text_Unicoder::isUnicode( $content ) ) $content = Alg_Text_Unicoder::convertToUnicode( $content ); $lines = explode( "\n", $content ); $fileBlock = NULL; $openClass = FALSE; $function = N...
Determine whether an array value is empty, taking into account casting. @param string $key @param array $value @return mixed
private function nullIfEmptyArray($key, $value) { if ($this->isJsonCastable($key) && ! empty($value)) { return $this->setJsonCastValue($value); } return empty($value) ? null : $value; }
Parse an input stream containing a Fortran namelist.
def _readstream(self, nml_file, nml_patch_in=None): """""" nml_patch = nml_patch_in if nml_patch_in is not None else Namelist() tokenizer = Tokenizer() f90lex = [] for line in nml_file: toks = tokenizer.parse(line) while tokenizer.prior_delim: ...
Initializes curl resource with options. @param string $url @param string $postString @param array $headers @return $this
protected function init($url, $postString, $headers) { $this->headers = $headers; $this->curl = curl_init($url); if (empty($this->cookieJar)) { $this->loadCookies(); } curl_setopt_array($this->curl, $this->makeHttpOptions($postString)); return $this; ...
Load executable code from a URL or a path
def load_code(name, base_path=None, recurse=False): """""" if '/' in name: return load_location(name, base_path, module=False) return importer.import_code(name, base_path, recurse=recurse)
// NextMatcher gets the immediately following sibling of each element in the // Selection filtered by a matcher. It returns a new Selection object // containing the matched elements.
func (s *Selection) NextMatcher(m Matcher) *Selection { return filterAndPush(s, getSiblingNodes(s.Nodes, siblingNext, nil, nil), m) }
_Really_ obtain the config for a named class @param string $class The class to get the config for @return \Weasel\JsonMarshaller\Config\ClassMarshaller The config, or null if not found
protected function _getConfig($class) { $rClass = new \ReflectionClass($class); // Delegate actually loading the config for the class to the ClassAnnotationDriver $classDriver = new ClassAnnotationDriver($rClass, $this->annotationReaderFactory, $this->annotationNamespace); return $...
// SetCacheLength sets the CacheLength field's value.
func (s *RtmpGroupSettings) SetCacheLength(v int64) *RtmpGroupSettings { s.CacheLength = &v return s }
Initialize grid lines.
private void initGridLines() { gridLines = new Line[base.getDimension() - 1][linesSlicing.length]; int i2 = 0; for (int i = 0; i < base.getDimension() - 1; i++) { if (i2 == index) { i2++; } for (int j = 0; j < gridLines[i].length; j++) { ...
Modifies the given N1QL query (as a {@link JsonObject}) to reflect these {@link N1qlParams}. @param queryJson the N1QL query
public void injectParams(JsonObject queryJson) { if (this.serverSideTimeout != null) { queryJson.put("timeout", this.serverSideTimeout); } if (this.consistency != null) { queryJson.put("scan_consistency", this.consistency.n1ql()); } if (this.scanWait != nu...
Send stat command to Memcached Server and return response lines. @param cmd: Command string. @return: Array of strings.
def _sendStatCmd(self, cmd): try: self._conn.write("%s\r\n" % cmd) regex = re.compile('^(END|ERROR)\r\n', re.MULTILINE) (idx, mobj, text) = self._conn.expect([regex,], self._timeout) #@UnusedVariable except: raise Exception("Communication with %s...
<p>readContent.</p> @param in a {@link java.io.Reader} object. @return a {@link java.lang.String} object. @throws java.io.IOException if any.
public static String readContent( Reader in ) throws IOException { char[] buffer = new char[2048]; StringBuilder sb = new StringBuilder(); int read; while ((read = in.read( buffer )) != -1) { sb.append( buffer, 0, read ); } return sb.toString(); ...
// AddNode add new node to directory (name must be unique in directory)
func (d *Dir) AddNode(newNode os.FileInfo) error { for _, node := range d.nodes { if newNode.Name() == node.Name() { return fmt.Errorf("node named " + newNode.Name() + " exists") } } d.nodes = append(d.nodes, newNode) return nil }
Load image from path. @param path Path to image. @return Image @throws java.io.IOException @throws NullPointerException if {@code path} is null.
private Image loadImage(Resource path) throws IOException { URL url = path.getURL(); if (url == null) { logger.warn("Unable to locate splash screen in classpath at: " + path); return null; } return Toolkit.getDefaultToolkit().createImage(url); }
/* (non-Javadoc) @see javax.persistence.EntityManager#createQuery(java.lang.String)
@Override public Query createQuery(String qlString) { try { return ivEm.createQuery(qlString); } finally { if (!inJTATransaction()) { ivEm.clear(); } } }
// NewService creates an instance of a Service.
func NewService() *Service { s := &Service{ TokenGenerator: rand.NewTokenGenerator(64), IDGenerator: snowflake.NewIDGenerator(), time: time.Now, } s.initializeSources(context.TODO()) return s }
Loads PHPExcel from file @param string $pFilename @return PHPExcel @throws PHPExcel_Reader_Exception
public function load($pFilename) { // Read the OLE file $this->_loadOLE($pFilename); // Initialisations $this->_phpExcel = new PHPExcel; $this->_phpExcel->removeSheetByIndex(0); // remove 1st sheet if (!$this->_readDataOnly) { $this->_phpExcel->removeCellStyleXfByIndex(0); // remove the defaul...
Commit an http request. @param string $method @param string $url @param array $params @param array $options @return \Shoperti\PayMe\Contracts\ResponseInterface
public function commit($method, $url, $params = [], $options = []) { if (empty($this->connectionToken)) { $this->loginApplication(); } $request = [ 'exceptions' => false, 'timeout' => '80', 'connect_timeout' => '30', '...
Compares the two Git trees (with caching).
private List<DiffEntry> blockingCompareTrees(RevTree treeA, RevTree treeB) { if (cache == null) { return blockingCompareTreesUncached(treeA, treeB, TreeFilter.ALL); } final CacheableCompareTreesCall key = new CacheableCompareTreesCall(this, treeA, treeB); CompletableFuture<L...
Rewrite references to `local_path` with `remote_path` in job inputs.
def rewrite_paths(self, local_path, remote_path): self.__rewrite_command_line(local_path, remote_path) self.__rewrite_config_files(local_path, remote_path)
Returns the initial of given name. For standard names: "First [Midddles] Last", returns capital "FL"; For others, returns substr(0, 2). @param {string} name - @return {string} - initial
function getNameInitial(name) { var namePart = name.split(' '); if (namePart.length >= 2) { return (namePart[0].charAt(0) + namePart[namePart.length - 1].charAt(0)).toUpperCase(); } else { return name.substr(0, 2); } }
Sets the variables to the selected stage using cap rbenv set
def set_vars_to_stage(stage, variables) # convert to array using VAR=value vars_array = variables.map{|k,v| "#{k}=#{v}" } Capistrano::Application.invoke(stage) Capistrano::Application.invoke("rbenv:vars:set", *vars_array) end
Create a 500 response. @param \Exception $exception The exception to log. @return JsonResponse
private function createInternalServerError(\Exception $exception) { $message = sprintf( '%s: %s (uncaught exception) at %s line %s', get_class($exception), $exception->getMessage(), $exception->getFile(), $exception->getLine() ); $...
// SetAmznClientToken sets the AmznClientToken field's value.
func (s *CreateConnectorDefinitionVersionInput) SetAmznClientToken(v string) *CreateConnectorDefinitionVersionInput { s.AmznClientToken = &v return s }
// SetApplicationVersionId sets the ApplicationVersionId field's value.
func (s *AddApplicationInputProcessingConfigurationOutput) SetApplicationVersionId(v int64) *AddApplicationInputProcessingConfigurationOutput { s.ApplicationVersionId = &v return s }
Writes out headers for $this->part and follows them with an empty line. @param StreamInterface $stream
public function writePartHeadersTo(StreamInterface $stream) { foreach ($this->getPartHeadersIterator() as $header) { $stream->write("${header[0]}: ${header[1]}\r\n"); } $stream->write("\r\n"); }
Add all additional defined and undefined symbols.
def __add_symbols(self, cmd): if self.__config.define_symbols: symbols = self.__config.define_symbols cmd.append(''.join( [' -D"%s"' % def_symbol for def_symbol in symbols])) if self.__config.undefine_symbols: un_symbols = self.__config.unde...
// CanCastle returns true if the given color and side combination // can castle, otherwise returns false.
func (cr CastleRights) CanCastle(c Color, side Side) bool { char := "k" if side == QueenSide { char = "q" } if c == White { char = strings.ToUpper(char) } return strings.Contains(string(cr), char) }
Finds all nodes that are after the ``min_line_number``
def filter_assert_nodes(nodes: List[ast.stmt], min_line_number: int) -> List[ast.stmt]: return [node for node in nodes if node.lineno > min_line_number]
Checks for valid uploaded file. @param array $package @return bool
protected function isUploadedFile($package) { if (isset($package['name'], $package['tmp_name'], $package['type'], $package['size'])) { if (in_array($package['type'], ['application/zip', 'application/x-zip-compressed'])) { return true; } } return false...
Compare two attributes @param control @param test @param listener @throws DifferenceFoundException
protected void compareRecognizedXMLSchemaInstanceAttribute(Attr control, Attr test, DifferenceListener listener) throws DifferenceFoundException { Attr nonNullNode = control != n...
Export this data so it can be used as the context for a mustache template. @param \renderer_base $output @return stdClass
public function export_for_template(renderer_base $output) { global $USER, $OUTPUT; $data = new \stdClass(); if (!isset($this->config->display_picture) || $this->config->display_picture == 1) { $data->userpicture = $OUTPUT->user_picture($USER, array('class' => 'userpicture')); ...
// AddMultiple adds a list of cookies.
func AddMultiple(cookies []*http.Cookie) p.Plugin { return p.NewRequestPlugin(func(ctx *c.Context, h c.Handler) { for _, cookie := range cookies { ctx.Request.AddCookie(cookie) } h.Next(ctx) }) }
Gets the next match_temp_var.
def get_temp_var(self): """""" tempvar = match_temp_var + "_" + str(self.var_index) self.var_index += 1 return tempvar
Returns true if the associate PushMode was selected in the configuration @param Configuration $configuration @return bool
public function isMode( Configuration $configuration ) { if( $this->inServiceChecker->isInService($configuration) ) return false; if( $this->replaceUpgradeChecker->isReplaceUpgrade($configuration) ) return false; return true; }
Start healthcheck (status monitoring) for a peer It also whitelists the address to answer invites and listen for messages
def start_health_check(self, node_address): if self._stop_event.ready(): return with self._health_lock: if self._address_mgr.is_address_known(node_address): return # already healthchecked node_address_hex = to_normalized_address(node_addres...
Custom error handler that will throw an exception on any errors
public function handleError() { // get error info list ($errno, $message, $file, $line) = func_get_args(); // construct error message $msg = "ERROR ($errno): $message"; if ($line !== null) { $file = "$file:$line"; } if ($file !== null) { ...
// details outputs details for a single transaction.
func (w *walletAPIHandler) details(ctx context.Context, c Call, wr io.Writer) error { var opts txIDOptions if err := unmarshalOptions(c, &opts); err != nil { return w.encodeErr(c, err, wr) } detail, err := w.cli.PaymentDetailCLILocal(ctx, opts.TxID) if err != nil { return w.encodeErr(c, err, wr) } return w.e...
Set dotted attr (like "a.b.c") on obj to val.
def setattrdeep(obj, attr, val): '' attrs = attr.split('.') for a in attrs[:-1]: obj = getattr(obj, a) setattr(obj, attrs[-1], val)
---------------------------------------------------------------------------
function replaceInFile (filename, regex, replacement) { let contents = fs.readFileSync (filename, 'utf8') const parts = contents.split (regex) const newContents = parts[0] + replacement + parts[1] fs.truncateSync (filename) fs.writeFileSync (filename, newContents) }
Check so Locale settings (country, currency, language) are set. @throws KlarnaException @return void
private function _checkLocale() { if (!is_int($this->_country) || !is_int($this->_language) || !is_int($this->_currency) ) { throw new Klarna_InvalidLocaleException; } }
@param \PHP_CodeSniffer\Files\File $phpCsFile @param int $stackPointer @return bool
protected function hasMethodAnnotation(File $phpCsFile, int $stackPointer): bool { $position = $phpCsFile->findPrevious(T_DOC_COMMENT_CLOSE_TAG, $stackPointer); $tokens = $phpCsFile->getTokens(); while ($position !== false) { $position = $phpCsFile->findPrevious(T_DOC_COMMENT_TA...
Remove a parser from the render queue. @param \Ems\Contracts\Core\TextParser $parser @return self
public function remove(TextParser $parser) { $parserHash = $this->objectHash($parser); $this->parsers = array_filter($this->parsers, function ($known) use ($parserHash) { return $this->objectHash($known) != $parserHash; }); if (isset($this->parserIds[$parserHash])) { ...
// GetZone returns the Zone containing the current availability zone and locality region that the program is running in. // If the node is not running with availability zones, then it will fall back to fault domain.
func (az *Cloud) GetZone(ctx context.Context) (cloudprovider.Zone, error) { if az.UseInstanceMetadata { metadata, err := az.metadata.GetMetadata() if err != nil { return cloudprovider.Zone{}, err } if metadata.Compute == nil { return cloudprovider.Zone{}, fmt.Errorf("failure of getting compute informati...
Decode sensor data. Returns: dict: Sensor values
def decode_data(self, encoded): ''' ''' try: identifier = None data_format = 2 if len(encoded) > 8: data_format = 4 identifier = encoded[8:] encoded = encoded[:8] decoded = bytearray(base64.b...
<p> A list of the configuration options and their values in this configuration set. </p> @return A list of the configuration options and their values in this configuration set.
public java.util.List<ConfigurationOptionSetting> getOptionSettings() { if (optionSettings == null) { optionSettings = new com.amazonaws.internal.SdkInternalList<ConfigurationOptionSetting>(); } return optionSettings; }
// SetDeadline implements the net.PacketConn SetDeadline method.
func (c *Conn) SetDeadline(t time.Time) error { return c.p.SetDeadline(t) }
// Reset cleans up the request queue
func (s *BulkService) Reset() { s.requests = make([]BulkableRequest, 0) s.sizeInBytes = 0 s.sizeInBytesCursor = 0 }
Registers a named object in the store.
function(obj, type, name, nameIsUnique, oldName) { var nameMap, objList this._store[type] = nameMap = this._store[type] || {} nameMap[name] = objList = nameMap[name] || [] // Adding new mapping if (objList.indexOf(obj) === -1) { if (nameIsUnique && objList.length > 0) throw new Error...
Function creating an iterator of edges for the given type. @param {Graph} graph - Target Graph instance. @param {string} type - Type of edges to retrieve. @return {Iterator}
function createEdgeIterator(graph, type) { if (graph.size === 0) return Iterator.empty(); let iterator; if (type === 'mixed') { iterator = graph._edges.values(); return new Iterator(function next() { const step = iterator.next(); if (step.done) return step; const data = ...
// SetFIFOCompactionOptions sets the options for FIFO compaction style. // Default: nil
func (opts *Options) SetFIFOCompactionOptions(value *FIFOCompactionOptions) { C.rocksdb_options_set_fifo_compaction_options(opts.c, value.c) }
Method to create the blank transaction nodes as a dict. If bic is True, the BIC node will also be created.
def _create_TX_node(self, bic=True): ED = dict() ED['DrctDbtTxInfNode'] = ET.Element("DrctDbtTxInf") ED['PmtIdNode'] = ET.Element("PmtId") ED['EndToEndIdNode'] = ET.Element("EndToEndId") ED['InstdAmtNode'] = ET.Element("InstdAmt") ED['DrctDbtTxNode'] = ET.Element...
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case BpsimPackage.NUMERIC_PARAMETER_TYPE__CURRENCY_UNIT: return getCurrencyUnit(); case BpsimPackage.NUMERIC_PARAMETER_TYPE__TIME_UNIT: return getTimeUnit(); case BpsimPackage.NUMERIC_PARAMETER_TYPE...
@param GitUserInterface $user @param FilePath $relativeFilePath @param string $commitMessage @throws \Exception
public function removeFile(GitUserInterface $user, FilePath $relativeFilePath, $commitMessage) { $this->assertCommitMessageExists($commitMessage); $this->createLock($user, $relativeFilePath); $this->gitService->removeAndCommit($user, $relativeFilePath, $commitMessage); $this->removeL...