comment
stringlengths
16
255
code
stringlengths
52
3.87M
Returns the next $fact value or FALSE if there are no more facts. {@inheritDoc} @see Iterator::next()
public function next() { if ( is_null( $this->facts ) ) { return false; } $this->yieldedFact = null; $success = $this->facts->next(); return $success; }
Compare the structures of two databases. Analysis's and compares the column definitions of each table in both databases's. Identifies differences in column names, data types and keys.
def compare_schemas(self, db_x, db_y, show=True): # TODO: Improve method self._printer("\tComparing database schema's {0} and {1}".format(db_x, db_y)) # Run compare_dbs_getter to get row counts x = self._schema_getter(db_x) y = self._schema_getter(db_y) x_count = len(x) y_count = len(y) # Check that database does not have zero tables if x_count == 0: self._printer('\tThe database {0} has no tables'.format(db_x)) self._printer('\tDatabase differencing was not run') return None elif y_count == 0: self._printer('\tThe database {0} has no tables'.format(db_y)) self._printer('\tDatabase differencing was not run') return None # Print comparisons if show: uniques_x = diff(x, y, x_only=True) if len(uniques_x) > 0: self._printer('\nUnique keys from {0} ({1} of {2}):'.format(db_x, len(uniques_x), x_count)) self._printer('------------------------------') # print(uniques) for k, v in sorted(uniques_x): self._printer('{0:25} {1}'.format(k, v)) self._printer('\n') uniques_y = diff(x, y, y_only=True) if len(uniques_y) > 0: self._printer('Unique keys from {0} ({1} of {2}):'.format(db_y, len(uniques_y), y_count)) self._printer('------------------------------') for k, v in sorted(uniques_y): self._printer('{0:25} {1}'.format(k, v)) self._printer('\n') if len(uniques_y) == 0 and len(uniques_y) == 0: self._printer("Databases's {0} and {1} are identical:".format(db_x, db_y)) self._printer('------------------------------') return diff(x, y)
Display a listing of the resource. @param $type @param Request $request @return Response
public function index($type, Request $request) { try { $resultColumns = []; $query = $request->get('q'); $column = $request->get('c'); $model = app()->make(config('mentions.' . $type)); $records = $model->where($column, 'LIKE', "%$query%") ->get([$column]); foreach ($records as $record) { $resultColumns[] = $record->$column; } return response()->json($resultColumns); } catch (\ReflectionException $e) { return response()->json('Not Found', 404); } }
// NewRocR100ForStreamWithSrcLen creates a Rate of Change Ratio 100 Scale Indicator (RocR100) for offline usage with a source data stream
func NewRocR100ForStreamWithSrcLen(sourceLength uint, priceStream gotrade.DOHLCVStreamSubscriber, timePeriod int, selectData gotrade.DOHLCVDataSelectionFunc) (indicator *RocR100, err error) { ind, err := NewRocR100WithSrcLen(sourceLength, timePeriod, selectData) priceStream.AddTickSubscription(ind) return ind, err }
/* ------------------------------------------------------------
public void reset() { try{ out=IO.getNullWriter(); super.flush(); out=new OutputStreamWriter(os,encoding); written=false; } catch(UnsupportedEncodingException e) { log.fatal(e); System.exit(1); } }
When an error status the payload is holding an AsyncException that is converted to a serializable dict.
def _payload_to_dict(self): if self.status != self.ERROR or not self.payload: return self.payload import traceback return { "error": self.payload.error, "args": self.payload.args, "traceback": traceback.format_exception(*self.payload.traceback) }
// IsEmptyConfig returns true if the provided error indicates the provided configuration // is empty.
func IsEmptyConfig(err error) bool { switch t := err.(type) { case errConfigurationInvalid: return len(t) == 1 && t[0] == ErrEmptyConfig } return err == ErrEmptyConfig }
Generate file name. @return the string
public static String generatePreviousPreviousFileName() { StringBuffer name = new StringBuffer(); name.append("Audit_Log-").append(AuditUtil.dateToString(new Date(), "yyyy-MM-dd")) .append(CoreConstants.AUDIT_EXTENTION); return name.toString(); }
// SetDeploymentStatusMessages sets the DeploymentStatusMessages field's value.
func (s *DeploymentInfo) SetDeploymentStatusMessages(v []*string) *DeploymentInfo { s.DeploymentStatusMessages = v return s }
Load dependencies on demand. @see \SimpleComplex\Config\EnvSectionedConfig @return void
protected function loadDependencies() /*: void*/ { if (!$this->validate) { $this->validate = Validate::getInstance(); if (!$this->config) { // Use enviroment variable wrapper config class if exists; // fall back on empty sectioned map. try { if (class_exists('\\SimpleComplex\\Config\\EnvSectionedConfig')) { $this->config = call_user_func('\\SimpleComplex\\Config\\EnvSectionedConfig::getInstance'); } else { $this->config = new SectionedMap(); } } catch (\Throwable $ignore) { $this->config = new SectionedMap(); } } if (!$this->unicode) { $this->unicode = Unicode::getInstance(); } if (!$this->sanitize) { $this->sanitize = Sanitize::getInstance(); } } }
Encode an arbitrary value
private void encodeObject(StringBuffer result, Object value) { if (value != null) { if (value instanceof byte[]) { result.append("[]"); HexString.binToHex((byte[])value, 0, ((byte[])value).length, result); } else URLEncode(result, value.toString()); }
Create a new UnboundNode representing a given class.
def _createunbound(kls, **info): """""" if issubclass(kls, Bitfield): nodetype = UnboundBitfieldNode elif hasattr(kls, '_fields_'): nodetype = UnboundStructureNode elif issubclass(kls, ctypes.Array): nodetype = UnboundArrayNode else: nodetype = UnboundSimpleNode return nodetype(type=kls, **info)
/* Get singleton instance @return Some\Class Object singleton instance
public static function getInstance () { // If this class is used for multiple singletons, we need to keep // track of multiple singleton objects, one for each class name static $instances = array(); // Get class name to use. Use late static binding here, // if method is overriden by derived classes. $singletonClassName = static::_getInstanceClassName(); // If already instantiated, use that if (isset($instances[$singletonClassName])) { return $instances[$singletonClassName]; } // Otherwise create new instance $instances[$singletonClassName] = new $singletonClassName (static::_getInstanceFuseValue()); return $instances[$singletonClassName]; }
Compile an expression and return the corresponding executable @param string $expression @return \FormulaInterpreter\Executable
function compile($expression) { $options = $this->parser->parse($expression); $command = $this->commandFactory->create($options); return new Executable($command, $this->variables); }
Outputs the current progress string.
public function display(): void { if (null === $this->format) { $this->format = self::DEFAULT_FORMAT; } $this->render($this->buildLine()); }
Add field rules from either a Jpf.ValidationField or a Jpf.ValidationLocaleRules annotation.
private void addFieldRules( AnnotationInstance rulesContainerAnnotation, RuleInfo ruleInfo, boolean applyToAllLocales ) { // // First parse the locale from the wrapper annotation. This will apply to all rules inside. // Locale locale = null; if ( ! applyToAllLocales ) { String language = CompilerUtils.getString( rulesContainerAnnotation, LANGUAGE_ATTR, true ); // // If there's no language specified, then this rule will only apply for the default ruleset // (i.e., if there are explicit rules for the requested locale, this rule will not be run). // if ( language != null ) { String country = CompilerUtils.getString( rulesContainerAnnotation, COUNTRY_ATTR, true ); String variant = CompilerUtils.getString( rulesContainerAnnotation, VARIANT_ATTR, true ); language = language.trim(); if ( country != null ) country = country.trim(); if ( variant != null ) variant = variant.trim(); if ( country != null && variant != null ) locale = new Locale( language, country, variant ); else if ( country != null ) locale = new Locale( language, country ); else locale = new Locale( language ); } } Map valuesPresent = rulesContainerAnnotation.getElementValues(); for ( Iterator ii = valuesPresent.entrySet().iterator(); ii.hasNext(); ) { Map.Entry entry = ( Map.Entry ) ii.next(); AnnotationValue value = ( AnnotationValue ) entry.getValue(); Object val = value.getValue(); if ( val instanceof AnnotationInstance ) { addFieldRuleFromAnnotation( ruleInfo, ( AnnotationInstance ) val, locale, applyToAllLocales ); } else if ( val instanceof List ) { List annotations = CompilerUtils.getAnnotationArray( value ); for ( Iterator i3 = annotations.iterator(); i3.hasNext(); ) { AnnotationInstance i = ( AnnotationInstance ) i3.next(); addFieldRuleFromAnnotation( ruleInfo, i, locale, applyToAllLocales ); } } } setEmpty( false ); // this ValidationModel is only "empty" if there are no rules. }
Execute unpublishing documents
private function manageDeleteDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId) { $params->loadRootCategory = true; // get complete path to root, for checking inherited access rights $params->loadAccessRights = true; $params->loadDocuments = false; $category = $dmsLoader->loadCategory($manageCategory, $params); if (!$category->isDeletableForCurrentMember()) { $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed']; $blnShowStart = true; } else { $document = $dmsLoader->loadDocument($documentId, $params); if ($document != null) { // delete the document in the database $dmsWriter = \DmsWriter::getInstance(); if ($dmsWriter->deleteDocument($document)) { $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_deleted']; // delete the file $filePath = \DmsConfig::getDocumentFilePath($document->getFileNameVersioned()); if (file_exists(TL_ROOT . '/' . $filePath)) { unlink($filePath); \Dbafs::deleteResource($filePath); $arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_deleted']; } else { $arrMessages['infos'][] = $GLOBALS['TL_LANG']['DMS']['INFO']['document_delete_file_not_exists']; } } else { $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['delete_document_failed']; } } else { $arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_found']; } $this->manageSelectDocument($params, $dmsLoader, $manageCategory, $arrMessages, $blnShowStart); } }
Gets the value for the given key in the {@link Properties}; if this key is not found, a RuntimeException is thrown. @param key the key to get the value for @param options options for getting configuration value @return the value for the given key
public static String get(PropertyKey key, ConfigurationValueOptions options) { return sConf.get(key, options); }
Generate vendor directory @param string $sVendor
protected function _generateVendorDir($sVendor) { $sVendorDir = $this->_sModuleDir . $sVendor . DIRECTORY_SEPARATOR; if (!file_exists($sVendorDir)) { mkdir($sVendorDir); // Generate vendor metadata file file_put_contents($sVendorDir . 'vendormetadata.php', '<?php'); } }
Read a 32-bit little-endian integer from the internal buffer.
public int readRawLittleEndian32() throws IOException { final byte[] buffer = this.buffer; int offset = this.offset; final byte b1 = buffer[offset++]; final byte b2 = buffer[offset++]; final byte b3 = buffer[offset++]; final byte b4 = buffer[offset++]; this.offset = offset; return (((int) b1 & 0xff)) | (((int) b2 & 0xff) << 8) | (((int) b3 & 0xff) << 16) | (((int) b4 & 0xff) << 24); }
{@inheritdoc} @param FlowQuery $flowQuery @param array $arguments @return void @throws FizzleException @throws \Neos\Eel\Exception
public function evaluate(FlowQuery $flowQuery, array $arguments) { $subject = $arguments[0]; if (!isset($subject) || empty($subject)) { $flowQuery->setContext([]); return; } $filteredContext = []; $context = $flowQuery->getContext(); if (is_string($subject)) { foreach ($context as $contextElement) { $contextElementQuery = new FlowQuery([$contextElement]); $contextElementQuery->pushOperation('children', $arguments); if ($contextElementQuery->count() > 0) { $filteredContext[] = $contextElement; } } } else { if ($subject instanceof FlowQuery) { $elements = $subject->get(); } elseif ($subject instanceof \Traversable) { $elements = iterator_to_array($subject); } elseif (is_object($subject)) { $elements = [$subject]; } elseif (is_array($subject)) { $elements = $subject; } else { throw new FizzleException('supplied argument for has operation not supported', 1332489625); } foreach ($elements as $element) { if ($element instanceof TraversableNodeInterface) { $parentsQuery = new FlowQuery([$element]); foreach ($parentsQuery->parents([])->get() as $parent) { /** @var TraversableNodeInterface $parent */ foreach ($context as $contextElement) { /** @var TraversableNodeInterface $contextElement */ if ($contextElement === $parent) { $filteredContext[] = $contextElement; } } } } } $filteredContext = array_unique($filteredContext); } $flowQuery->setContext($filteredContext); }
ensureExists @param string $dir @return void
private function ensureExists($dir) { if (!is_dir($dir)) { mkdir($dir, 0755, true); } return $this->validatePath($dir); }
// Error returns the JSONified version of this error which will // trigger the appropriate integration mapping.
func (apigError *Error) Error() string { bytes, bytesErr := json.Marshal(apigError) if bytesErr != nil { bytes = []byte(http.StatusText(http.StatusInternalServerError)) } return string(bytes) }
Clean up, return key/value pairs @param array $matched @return array @access protected
protected function clearPairs(/*# array */ $matched)/*# : array */ { $pairs = []; foreach ($matched as $m) { // source another env file if (isset($m[5])) { $file = trim($m[5]); $pairs[$file] = $this->source_marker; // value found } elseif (isset($m[3])) { $pairs[$m[1]] = $m[3]; // no value defined } else { $pairs[$m[1]] = ''; } } return $pairs; }
Connects to all the event listeners @method startListening @chainable
function () { this.events.on('report:run:browser', this.runBrowser.bind(this)); this.events.on('report:assertion', this.assertion.bind(this)); this.events.on('report:test:started', this.testStarted.bind(this)); this.events.on('report:test:finished', this.testFinished.bind(this)); this.events.on('report:runner:finished', this.runnerFinished.bind(this)); this.events.on('report:testsuite:started', this.testsuiteStarted.bind(this)); //this.events.on('report:testsuite:finished', this.testsuiteFinished.bind(this)); return this; }
12.12 Labelled Statement
private ParseTree parseLabelledStatement() { SourcePosition start = getTreeStartLocation(); IdentifierToken name = eatId(); eat(TokenType.COLON); return new LabelledStatementTree(getTreeLocation(start), name, parseStatement()); }
Browse Episodes of an remote application (with the keychain) @Route("/remote/{keychain}", name="oktolab_media_remote_episodes") @Method("GET") @Template()
public function listRemoteEpisodes(Keychain $keychain) { $episodes_url = $this->get('bprs_applink')->getApiUrlsForKey( $keychain, 'oktolab_media_api_list_episodes' ); if ($episodes_url) { $client = new Client(); $response = $client->request( 'GET', $episodes_url, ['auth' => [$keychain->getUser(), $keychain->getApiKey()]] ); if ($response->getStatusCode() == 200) { $info = json_decode( html_entity_decode((string)$response->getBody()), true ); return ['result' => $info, 'keychain' => $keychain]; } } return new Response('', Response::HTTP_BAD_REQUEST); }
Checks if a symbol is a special. @param NumberPatternSymbol $symbol @param array $is An array of self::SYMBOL_* constants, one of which the symbol should match. @return boolean
function symbolIsSpecial(NumberPatternSymbol $symbol, array $is) { return !$symbol->escaped && in_array($symbol->symbol, $is, TRUE); }
Invoke method, every class will have its own returns true/false on completion, setting both errormsg and output as necessary
function invoke() { parent::invoke(); $result = true; // Set own core attributes $this->does_generate = ACTION_NONE; // These are always here global $CFG, $XMLDB; // Do the job, setting result as needed // Get the dir containing the file $dirpath = required_param('dir', PARAM_PATH); $dirpath = $CFG->dirroot . $dirpath; // Get the original dir and delete some elements if (!empty($XMLDB->dbdirs)) { if (isset($XMLDB->dbdirs[$dirpath])) { $dbdir = $XMLDB->dbdirs[$dirpath]; if ($dbdir) { unset($dbdir->xml_file); unset($dbdir->xml_loaded); unset($dbdir->xml_changed); unset($dbdir->xml_exists); unset($dbdir->xml_writeable); } } } // Get the edited dir and delete it completely if (!empty($XMLDB->editeddirs)) { if (isset($XMLDB->editeddirs[$dirpath])) { unset($XMLDB->editeddirs[$dirpath]); } } // Launch postaction if exists (leave this here!) if ($this->getPostAction() && $result) { return $this->launch($this->getPostAction()); } // Return ok if arrived here return $result; }
// Beep beeps the PC speaker (https://en.wikipedia.org/wiki/PC_speaker).
func Beep(freq float64, duration int) error { if freq == 0 { freq = DefaultFreq } else if freq > 32767 { freq = 32767 } else if freq < 37 { freq = DefaultFreq } if duration == 0 { duration = DefaultDuration } kernel32, _ := syscall.LoadLibrary("kernel32.dll") beep32, _ := syscall.GetProcAddress(kernel32, "Beep") defer syscall.FreeLibrary(kernel32) _, _, e := syscall.Syscall(uintptr(beep32), uintptr(2), uintptr(int(freq)), uintptr(duration), 0) if e != 0 { return e } return nil }
Returns the direct properties of this resource in a map.<p> This is without "search", so it will not include inherited properties from the parent folders.<p> @return the direct properties of this resource in a map
public Map<String, String> getProperty() { if (m_properties == null) { try { List<CmsProperty> properties = m_cms.readPropertyObjects(this, false); m_properties = CmsProperty.toMap(properties); } catch (CmsException e) { if (LOG.isDebugEnabled()) { LOG.debug(e.getMessage(), e); } } } return m_properties; }
Write mesage to tansport. msg should be a member of a valid `protobuf class <https://developers.google.com/protocol-buffers/docs/pythontutorial>`_ with a SerializeToString() method.
def write(self, msg): ser = msg.SerializeToString() header = struct.pack(">HL", mapping.get_type(msg), len(ser)) self._write(b"##" + header + ser, msg)
@param CreditCard $card @return CreditCard
public function tokenizeCard(CreditCard $card) { $tokenizeCardRequest = new TokenizeCardRequest($this->merchant, $this->environment); return $tokenizeCardRequest->execute($card); }
Drop several tables at once @param array $tables @param boolean $fkChecks Whether to enabled Foreign Key checks @return boolean
final public function dropTables(array $tables, $fkChecks = false) { // Whether FK checks are enabled if ($fkChecks == false) { $this->db->raw('SET FOREIGN_KEY_CHECKS=0') ->execute(); } foreach ($tables as $table) { if (!$this->dropTable($table)) { return false; } } // Whether FK checks are enabled if ($fkChecks == false) { $this->db->raw('SET FOREIGN_KEY_CHECKS=1') ->execute(); } return true; }
Executes a detach operation on the given entity. @param object $entity @param array $visited @param boolean $noCascade if true, don't cascade detach operation. @return void
private function doDetach($entity, array &$visited, $noCascade = false) { $oid = spl_object_hash($entity); if (isset($visited[$oid])) { return; // Prevent infinite recursion } $visited[$oid] = $entity; // mark visited switch ($this->getEntityState($entity, self::STATE_DETACHED)) { case self::STATE_MANAGED: if ($this->isInIdentityMap($entity)) { $this->removeFromIdentityMap($entity); } unset( $this->entityInsertions[$oid], $this->entityUpdates[$oid], $this->entityDeletions[$oid], $this->entityIdentifiers[$oid], $this->entityStates[$oid], $this->originalEntityData[$oid] ); break; case self::STATE_NEW: case self::STATE_DETACHED: return; } if ( ! $noCascade) { $this->cascadeDetach($entity, $visited); } }
@param array $attributes @param Assertion $assertion @return array
private function resolveAttributesFromAssertion(array $attributes, Assertion $assertion) { $attributeStatements = $assertion->getAllAttributeStatements(); return array_reduce($attributeStatements, [$this, 'resolveAttributesFromAttributeStatement'], $attributes); }
To date. @param value the value @return the date
public static Date toDate(final Object value) { if (value instanceof Date) { return (Date) value; } if (value == null || value.equals("null")) { return null; } if (value instanceof String) { throw new IllegalStateException("fix me"); } return null; }
Calculate the centre x position
function (d, chart, series) { var returnCx = 0; if (series.x.measure !== null && series.x.measure !== undefined) { returnCx = series.x._scale(d.cx); } else if (series.x._hasCategories() && series.x.categoryFields.length >= 2) { returnCx = series.x._scale(d.cx) + dimple._helpers.xGap(chart, series) + ((d.xOffset + 0.5) * (((chart._widthPixels() / series.x._max) - 2 * dimple._helpers.xGap(chart, series)) * d.width)); } else { returnCx = series.x._scale(d.cx) + ((chart._widthPixels() / series.x._max) / 2); } return returnCx; }
HTTP Method Patch @param string $uri optional uri to use @param string $payload data to send in body of request @param string $mime MIME to use for Content-Type @return Request
public static function patch($uri, $payload = null, $mime = null) { return self::init(Http::PATCH)->uri($uri)->body($payload, $mime); }
@param Ability $ability @param array $options @return array
public function serialize(Ability $ability, array $options = []) { $serialized = [ 'id' => $ability->getUuid(), 'name' => $ability->getName(), 'minResourceCount' => $ability->getMinResourceCount(), 'minEvaluatedResourceCount' => $ability->getMinEvaluatedResourceCount(), ]; return $serialized; }
// NoAutoCondition disable generate SQL condition from beans
func (session *Session) NoAutoCondition(no ...bool) *Session { session.Statement.NoAutoCondition(no...) return session }
Make data filter definition consistent. Create a tuple where first element is the row filter and the second element is the column filter
def _homogenize_data_filter(dfilter): if isinstance(dfilter, tuple) and (len(dfilter) == 1): dfilter = (dfilter[0], None) if (dfilter is None) or (dfilter == (None, None)) or (dfilter == (None,)): dfilter = (None, None) elif isinstance(dfilter, dict): dfilter = (dfilter, None) elif isinstance(dfilter, (list, str)) or ( isinstance(dfilter, int) and (not isinstance(dfilter, bool)) ): dfilter = (None, dfilter if isinstance(dfilter, list) else [dfilter]) elif isinstance(dfilter[0], dict) or ( (dfilter[0] is None) and (not isinstance(dfilter[1], dict)) ): pass else: dfilter = (dfilter[1], dfilter[0]) return dfilter
Modifies a list of contacts. Provide comma separated list of contact ids and desired paused state Returns status message
def modifyContacts(self, contactids, paused): response = self.request("PUT", "notification_contacts", {'contactids': contactids, 'paused': paused}) return response.json()['message']
Returns the @GROUPID. If derived_from is set, returns that group_id.
def group_id(self): if self.derived_from is not None: return self.derived_from.group_id() if self.file_uuid is None: return None return utils.GROUP_ID_PREFIX + self.file_uuid
Create a TypedArray instance. @param {object} config @returns {TypedArray} @augments Typed @constructor
function TypedArray (config) { const array = this; // validate min items if (config.hasOwnProperty('minItems') && (!util.isInteger(config.minItems) || config.minItems < 0)) { throw Error('Invalid configuration value for property: minItems. Must be an integer that is greater than or equal to zero. Received: ' + config.minItems); } const minItems = config.hasOwnProperty('minItems') ? config.minItems : 0; // validate max items if (config.hasOwnProperty('maxItems') && (!util.isInteger(config.maxItems) || config.maxItems < minItems)) { throw Error('Invalid configuration value for property: maxItems. Must be an integer that is greater than or equal to the minItems. Received: ' + config.maxItems); } // validate schema if (config.hasOwnProperty('schema')) config.schema = FullyTyped(config.schema); // define properties Object.defineProperties(array, { maxItems: { /** * @property * @name TypedArray#maxItems * @type {number} */ value: Math.round(config.maxItems), writable: false }, minItems: { /** * @property * @name TypedArray#minItems * @type {number} */ value: Math.round(config.minItems), writable: false }, schema: { /** * @property * @name TypedArray#schema * @type {object} */ value: config.schema, writable: false }, uniqueItems: { /** * @property * @name TypedArray#uniqueItems * @type {boolean} */ value: !!config.uniqueItems, writable: false } }); return array; }
/* (non-Javadoc) @see javax.servlet.sip.SipServletMessage#getLocalAddr()
public String getLocalAddr() { final SIPTransaction sipTransaction = (SIPTransaction)getTransaction(); if(sipTransaction != null) { return sipTransaction.getHost(); } else { final String transport = JainSipUtils.findTransport(message); final MobicentsExtendedListeningPoint listeningPoint = sipFactoryImpl.getSipNetworkInterfaceManager().findMatchingListeningPoint(transport, false); return listeningPoint.getHost(true); } }
Export a literal as an XPath expression @param mixed $value Literal, e.g. "foo" @return string XPath expression, e.g. "'foo'"
public static function export($value) { if (!is_scalar($value)) { throw new InvalidArgumentException(__METHOD__ . '() cannot export non-scalar values'); } if (is_int($value)) { return (string) $value; } if (is_float($value)) { // Avoid locale issues by using sprintf() return preg_replace('(\\.?0+$)', '', sprintf('%F', $value)); } return self::exportString((string) $value); }
Set person address @param array|Address $value Parameter value @return Person provides a fluent interface.
public function setAddress($value) { if (is_array($value)) { $value = new Address($value); } return $this->setParameter('address', $value); }
Return connection base type device @param array $params @param string $type @return object
public function getConnection(array $params, $type) { if ($type == 'S') { $host = (!empty($params['num_ip'])) ? $params['num_ip'] : '127.0.0.1'; $community = (!empty($params['des_snmp_community'])) ? $params['des_snmp_community'] : 'public'; $version = (!empty($params['des_snmp_version'])) ? $params['des_snmp_version'] : '2c'; $seclevel = (!empty($params['des_snmp_sec_level'])) ? $params['des_snmp_sec_level'] : 'noAuthNoPriv'; $authprotocol = (!empty($params['des_snmp_auth_protocol'])) ? $params['des_snmp_auth_protocol'] : 'MD5'; $authpassphrase = (!empty($params['des_snmp_auth_passphrase'])) ? $params['des_snmp_auth_passphrase'] : 'None'; $privprotocol = (!empty($params['des_snmp_priv_protocol'])) ? $params['des_snmp_priv_protocol'] : 'DES'; $privpassphrase = (!empty($params['des_snmp_priv_passphrase'])) ? $params['des_snmp_priv_passphrase'] : 'None'; $connection = new \Cityware\Snmp\SNMP($host, $community, $version, $seclevel, $authprotocol, $authpassphrase, $privprotocol, $privpassphrase); $connection->setSecLevel(3); $connection->disableCache(); $this->setSnmpCon($connection); } else if ($type == 'W') { $host = (!empty($params['num_ip'])) ? $params['num_ip'] : '127.0.0.1'; $username = (!empty($params['des_wmi_user'])) ? $params['des_wmi_user'] : null; $password = (!empty($params['des_wmi_password'])) ? $params['des_wmi_password'] : null; $domain = (!empty($params['des_wmi_domain'])) ? $params['des_wmi_domain'] : null; $wmi = new \Cityware\Wmi\Wmi($host, $username, $password, $domain); $connection = $wmi->connect('root\\cimv2'); $this->setWmiCon($connection); } return $connection; }
Marks passed node as active @param string $nodeId node id
public function markNodeActive($nodeId) { $xPath = new DOMXPath($this->getDomXml()); $nodeList = $xPath->query("//*[@cl='{$nodeId}' or @list='{$nodeId}']"); if ($nodeList->length) { foreach ($nodeList as $node) { // special case for external resources $node->setAttribute('active', 1); $node->parentNode->setAttribute('active', 1); } } }
Remove keys from the public or secret keyrings. :param keys: Single key ID or list of mutiple IDs :param secret: Delete secret keys :rtype: DeleteResult
def delete_keys(self, keys, secret=False): ''' ''' return self.execute( DeleteResult(), ['--batch', '--yes', '--delete-secret-key' if secret else '--delete-key'] + list(make_list(keys)) )
unique method @method unique
public function unique() : Collection { $acc = []; foreach ($this->list as $item) { if (!in_array($item, $acc)) { $acc[] = $item; } } return self::from(...$acc); }
ubuntu 16.04 systemctl service config :param service_name: :param start_cmd: :param stop_cmd: :return:
def systemctl_autostart(self, service_name, start_cmd, stop_cmd): # get config content service_content = bigdata_conf.systemctl_config.format( service_name=service_name, start_cmd=start_cmd, stop_cmd=stop_cmd ) # write config into file with cd('/lib/systemd/system'): if not exists(service_name): sudo('touch {0}'.format(service_name)) put(StringIO(service_content), service_name, use_sudo=True) # make service auto-start sudo('systemctl daemon-reload') sudo('systemctl disable {0}'.format(service_name)) sudo('systemctl stop {0}'.format(service_name)) sudo('systemctl enable {0}'.format(service_name)) sudo('systemctl start {0}'.format(service_name))
Set the ``xlink:href`` of this file.
def url(self, url): if url is None: return el_FLocat = self._el.find('mets:FLocat', NS) if el_FLocat is None: el_FLocat = ET.SubElement(self._el, TAG_METS_FLOCAT) el_FLocat.set("{%s}href" % NS["xlink"], url)
@param mixed $use_customer_key @return Realm
public function setUseCustomerKey( $use_customer_key ) { $this->use_customer_key = ($use_customer_key == 1 || $use_customer_key == 'Y' || $use_customer_key === TRUE) ? TRUE : FALSE; return $this; }
Create an instance of {@link JAXBElement }{@code <}{@link MsupType }{@code >}}
@XmlElementDecl(namespace = "http://www.w3.org/1998/Math/MathML", name = "msup") public JAXBElement<MsupType> createMsup(MsupType value) { return new JAXBElement<MsupType>(_Msup_QNAME, MsupType.class, null, value); }
Compute SHA-1 hash value for a given input stream. @param in Input stream @return SHA-1 hash value (array of 20 bytes).
static byte[] sha1(InputStream in) { try { MessageDigest md = MessageDigest.getInstance(SHA1_DIGEST); byte[] buffer = new byte[4096]; int bytes; while ( (bytes = in.read(buffer)) > 0) { md.update(buffer, 0, bytes); } return md.digest(); } catch(NoSuchAlgorithmException | IOException e) { throw new InternalErrorException(e); } }
// SplitFullName splits a name and returns the firstname, lastname
func SplitFullName(fullName string) (string, string) { nameComponents := strings.Split(fullName, " ") firstName := nameComponents[0] lastName := "" if len(nameComponents) > 1 { lastName = strings.Join(nameComponents[1:], " ") } return firstName, lastName }
Sets the WHERE param to the query. @param int|array $where WHERE param. @param QueryBuilder $query Query to build. @param string $primaryKey Table primary key. @return QueryBuilder Query object.
private static function _setWhere($where, QueryBuilder $query, string $primaryKey = "id") : QueryBuilder { if(!is_array($where)) { return $query->where([ $primaryKey => $where ]); } $columns = $where; unset($columns["ORDER BY"]); unset($columns["LIMIT"]); unset($columns["OFFSET"]); if(!empty($columns)) { $query->where($columns); } if(isset($where["ORDER BY"])) { $order = $where["ORDER BY"]; if(!is_array($order)) { $order = [$order]; } $query->order(... $order); } if(isset($where["LIMIT"])) { $limit = $where["LIMIT"]; if(!is_array($limit)) { $limit = [$limit]; } $query->limit(... $limit); } if(isset($where["OFFSET"])) { $query->offset($where["OFFSET"]); } return $query; }
Create an enum config :param enum_type: :param help_string: :param default: :return:
def create_enum(enum_type, help_string=NO_HELP, default=NO_DEFAULT): # type: (Type[Enum], str, Union[Any, NO_DEFAULT_TYPE]) -> Type[Enum] # noinspection PyTypeChecker return ParamEnum( help_string=help_string, default=default, enum_type=enum_type, )
e @param {String} label the label of the async task @required @param {Any} gen the object to yield @return {Function} trunked function
function e(label, gen) { if (!gen) { gen = label; label = ''; } if (!enabled) { return gen; } var hackErr = new Error('hack'); hackErr.label = label; return function *() { try { return yield gen; } catch(err) { throw buildError(err, hackErr); } }; }
Add faxes. @param \Sulu\Bundle\ContactBundle\Entity\Fax $faxes @return FaxType
public function addFaxe(\Sulu\Bundle\ContactBundle\Entity\Fax $faxes) { $this->faxes[] = $faxes; return $this; }
Lists the views this connection has. @return View[]
public function listViews() { $database = $this->_conn->getDatabase(); $sql = $this->_platform->getListViewsSQL($database); $views = $this->_conn->fetchAll($sql); return $this->_getPortableViewsList($views); }
Block a user. Returns a `relationship dict`_ containing the updated relationship to the user.
def account_block(self, id): id = self.__unpack_id(id) url = '/api/v1/accounts/{0}/block'.format(str(id)) return self.__api_request('POST', url)
// MysqlAddr returns hostname:mysql port.
func (ti *TabletInfo) MysqlAddr() string { return netutil.JoinHostPort(topoproto.MysqlHostname(ti.Tablet), topoproto.MysqlPort(ti.Tablet)) }
// Custom marshaller to add the resourceType property, as required by the specification
func (resource *AppointmentResponse) MarshalJSON() ([]byte, error) { resource.ResourceType = "AppointmentResponse" // Dereferencing the pointer to avoid infinite recursion. // Passing in plain old x (a pointer to AppointmentResponse), would cause this same // MarshallJSON function to be called again return json.Marshal(*resource) }
Check the user has configured API version correctly.
def check_stripe_api_version(app_configs=None, **kwargs): """""" from . import settings as djstripe_settings messages = [] default_version = djstripe_settings.DEFAULT_STRIPE_API_VERSION version = djstripe_settings.get_stripe_api_version() if not validate_stripe_api_version(version): msg = "Invalid Stripe API version: {}".format(version) hint = "STRIPE_API_VERSION should be formatted as: YYYY-MM-DD" messages.append(checks.Critical(msg, hint=hint, id="djstripe.C004")) if version != default_version: msg = ( "The Stripe API version has a non-default value of '{}'. " "Non-default versions are not explicitly supported, and may " "cause compatibility issues.".format(version) ) hint = "Use the dj-stripe default for Stripe API version: {}".format(default_version) messages.append(checks.Warning(msg, hint=hint, id="djstripe.W001")) return messages
Resumes all the worker threads.
def resume(self): for child in chain(self.consumers.values(), self.workers): child.resume()
boolean response if a message contains correct information to serialize :param msg: <proto object> :param raise_err: <bool> :return: <bool>
def successfuly_encodes(msg, raise_err=False): result = True try: msg.SerializeToString() except EncodeError as encode_error: if raise_err: raise encode_error result = False return result
Convert co-ordinate values to floats.
def floatize(self): """""" self.x = float(self.x) self.y = float(self.y)
Get the route to the error page @param ServerRequestInterface $request @param ResponseInterface $response @return Router\Route
protected function getErrorRoute(ServerRequestInterface $request, ResponseInterface $response) { if ( interface_exists('Jasny\HttpMessage\GlobalEnvironmentInterface') && $request instanceof GlobalEnvironmentInterface ) { $request = $request->withoutGlobalEnvironment(); } $status = $response->getStatusCode(); $errorUri = $request->getUri() ->withPath($status) ->withQuery(null) ->withFragment(null); return $this->router->getRoutes()->getRoute($request->withUri($errorUri)); }
Returns a copy of this LocalTime with the nano-of-second value altered. @param int $nano The new nano-of-second. @return LocalTime @throws DateTimeException If the nano-of-second if not valid.
public function withNano(int $nano) : LocalTime { if ($nano === $this->nano) { return $this; } Field\NanoOfSecond::check($nano); return new LocalTime($this->hour, $this->minute, $this->second, $nano); }
Internal method to validate the local part of the email address @return boolean
private function _validateLocalPart() { // First try to match the local part on the common dot-atom format $result = false; // Dot-atom characters are: 1*atext *("." 1*atext) // atext: ALPHA / DIGIT / and "!", "#", "$", "%", "&", "'", "*", // "+", "-", "/", "=", "?", "^", "_", "`", "{", "|", "}", "~" $atext = 'a-zA-Z0-9\x21\x23\x24\x25\x26\x27\x2a\x2b\x2d\x2f\x3d\x3f\x5e\x5f\x60\x7b\x7c\x7d\x7e'; if (preg_match('/^[' . $atext . ']+(\x2e+[' . $atext . ']+)*$/', $this->_localPart)) { $result = true; } else { // Try quoted string format // Quoted-string characters are: DQUOTE *([FWS] qtext/quoted-pair) [FWS] DQUOTE // qtext: Non white space controls, and the rest of the US-ASCII characters not // including "\" or the quote character $noWsCtl = '\x01-\x08\x0b\x0c\x0e-\x1f\x7f'; $qtext = $noWsCtl . '\x21\x23-\x5b\x5d-\x7e'; $ws = '\x20\x09'; if (preg_match('/^\x22([' . $ws . $qtext . '])*[$ws]?\x22$/', $this->_localPart)) { $result = true; } else { $this->_error(self::DOT_ATOM); $this->_error(self::QUOTED_STRING); $this->_error(self::INVALID_LOCAL_PART); } } return $result; }
Returns all RDF types (classes) of a given resource. @return array
public function getClasses(): array { $this->loadMetadata(); $ret = array(); foreach ($this->metadata->allResources('http://www.w3.org/1999/02/22-rdf-syntax-ns#type') as $i) { $ret[] = $i->getUri(); } return $ret; }
Set closed date from this issue @param [Hash] event @param [Hash] issue
def set_date_from_event(event, issue) if event["commit_id"].nil? issue["actual_date"] = issue["closed_at"] else begin commit = @fetcher.fetch_commit(event["commit_id"]) issue["actual_date"] = commit["commit"]["author"]["date"] # issue['actual_date'] = commit['author']['date'] rescue StandardError puts "Warning: Can't fetch commit #{event['commit_id']}. It is probably referenced from another repo." issue["actual_date"] = issue["closed_at"] end end end
// SetUserName sets the UserName field's value.
func (s *DescribeUserStackAssociationsInput) SetUserName(v string) *DescribeUserStackAssociationsInput { s.UserName = &v return s }
/* insert line breaks into first-pass tokenized data
function breakLines(tokens, maxWidth) { if (!maxWidth) { maxWidth = Infinity; } let i = 0; let lineLength = 0; let lastTokenWithSpace = -1; while (i < tokens.length) { /* take all text tokens, remove space, apply linebreaks */ let token = tokens[i]; if (token.type == TYPE_NEWLINE) { /* reset */ lineLength = 0; lastTokenWithSpace = -1; } if (token.type != TYPE_TEXT) { /* skip non-text tokens */ i++; continue; } /* remove spaces at the beginning of line */ while (lineLength == 0 && token.value.charAt(0) == " ") { token.value = token.value.substring(1); } /* forced newline? insert two new tokens after this one */ let index = token.value.indexOf("\n"); if (index != -1) { token.value = breakInsideToken(tokens, i, index, true); /* if there are spaces at the end, we must remove them (we do not want the line too long) */ let arr = token.value.split(""); while (arr.length && arr[arr.length - 1] == " ") { arr.pop(); } token.value = arr.join(""); } /* token degenerated? */ if (!token.value.length) { tokens.splice(i, 1); continue; } if (lineLength + token.value.length > maxWidth) { /* line too long, find a suitable breaking spot */ /* is it possible to break within this token? */ let index = -1; while (1) { let nextIndex = token.value.indexOf(" ", index + 1); if (nextIndex == -1) { break; } if (lineLength + nextIndex > maxWidth) { break; } index = nextIndex; } if (index != -1) { /* break at space within this one */ token.value = breakInsideToken(tokens, i, index, true); } else if (lastTokenWithSpace != -1) { /* is there a previous token where a break can occur? */ let token = tokens[lastTokenWithSpace]; let breakIndex = token.value.lastIndexOf(" "); token.value = breakInsideToken(tokens, lastTokenWithSpace, breakIndex, true); i = lastTokenWithSpace; } else { /* force break in this token */ token.value = breakInsideToken(tokens, i, maxWidth - lineLength, false); } } else { /* line not long, continue */ lineLength += token.value.length; if (token.value.indexOf(" ") != -1) { lastTokenWithSpace = i; } } i++; /* advance to next token */ } tokens.push({ type: TYPE_NEWLINE }); /* insert fake newline to fix the last text line */ /* remove trailing space from text tokens before newlines */ let lastTextToken = null; for (let i = 0; i < tokens.length; i++) { let token = tokens[i]; switch (token.type) { case TYPE_TEXT: lastTextToken = token; break; case TYPE_NEWLINE: if (lastTextToken) { /* remove trailing space */ let arr = lastTextToken.value.split(""); while (arr.length && arr[arr.length - 1] == " ") { arr.pop(); } lastTextToken.value = arr.join(""); } lastTextToken = null; break; } } tokens.pop(); /* remove fake token */ return tokens; }
Gets the member attribute. @return Member|null The member attribute.
public function getMemberAttribute() { $guild = $this->discord->guilds->get('id', $this->guild_id); return $guild->members->get('id', $this->user_id); }
Given supplied arguments, find a contained subcommand @param array $args @return \WP_CLI\Dispatcher\Subcommand|false
public function find_subcommand( &$args ) { $name = array_shift( $args ); $subcommands = $this->get_subcommands(); if ( ! isset( $subcommands[ $name ] ) ) { $aliases = self::get_aliases( $subcommands ); if ( isset( $aliases[ $name ] ) ) { $name = $aliases[ $name ]; } } if ( ! isset( $subcommands[ $name ] ) ) { return false; } return $subcommands[ $name ]; }
Handles rolling back to a selected version on save. @param int $version
public function savePreviousVersion($version) { if (!is_numeric($version)) { return; } try { $this->setVersionNumber($version); $this->owner->write(); } catch (Exception $e) { throw new ValidationException(new ValidationResult( false, "Could not replace file #{$this->owner->ID} with version #$version." )); } }
Initializes the options for the object. Called from {@link __construct()} as a first step of object instantiation. @param object An optional AnConfig object with configuration options.
protected function _initialize(AnConfig $config) { $config->append(array( 'name' => 'google', 'version' => '3', 'url' => 'https://maps.googleapis.com/maps/api/geocode/json?', 'key' => get_config_value('locations.api_key', null) )); parent::_initialize($config); }
Adds the given component as a child of this component. The tag is used to identify the child in a velocity template. @param component the component to add. @param tag the tag used to identify the component. @deprecated Use {@link WTemplate} instead.
@Deprecated void add(final WComponent component, final String tag) { add(component); component.setTag(tag); }
read a file and inject a string of swagger (str, str) -> null
function useMain (mdFile, swagger) { const mainOpts = { position: argv.position, title: argv.title } opts.yaml ? mainOpts.yaml = true : mainOpts.json = true fs.readFile(mdFile, { encoding: 'utf8' }, function (err, md) { assert.ifError(err) const compiled = remark() .use(main(swagger, mainOpts)) .process(md) const rs = fromString(compiled) const ws = argv.w ? fs.createWriteStream(mdFile) : stdout pump(rs, ws, handleErr) }) }
{@inheritdoc} @see Knp\Menu.MenuItem::addChild() Our menu items created by menu factory and $child always MenuItemInterface. Factory sets current uri and other variable parts of menu item options We don't need to set it here
public function addChild($child, array $options = array()) { $child->setParent($this); $this->children[$child->getName()] = $child; return $child; }
Get a default db value, if any is available @return ConnectionInterface|null A default db value or Null if no default value is available
public function getDefaultDb(): ?ConnectionInterface { // By default, the DB Facade does not return the // any actual database connection, but rather an // instance of \Illuminate\Database\DatabaseManager. // Therefore, we make sure only to obtain its // "connection", to make sure that its only the connection // instance that we obtain. $manager = DB::getFacadeRoot(); if (isset($manager)) { return $manager->connection(); } return $manager; }
Loads source HTML into memory, either from $source string or a file. @param string $source HTML content @param bool $from_file Indicates $source is a file to pull content from
public function set_html($source, $from_file = false) { if ($from_file && file_exists($source)) { $this->html = file_get_contents($source); } else { $this->html = $source; } $this->_converted = false; }
文字列のダイアクリティカルマークや囲みを外します。 @param string $input @return string
protected static function deleteMarks(string $input): string { return preg_replace( '/\\p{M}+/u', '', \Normalizer::normalize($input, \Normalizer::FORM_KD) ); }
Update components.
def command_update(prog_name, prof_mgr, prof_name, prog_args): # Retrieve arguments parser = argparse.ArgumentParser( prog=prog_name ) parser.add_argument( "components", metavar="comps", nargs=argparse.REMAINDER, help="system components" ) args = parser.parse_args(prog_args) # Profile load prof_stub = prof_mgr.load(prof_name) # Collect component stubs comp_stubs = [] if len(args.components) == 0: raise Exception("Empty component list") for comp_name in args.components: comp_stub = prof_stub.component(comp_name) component_exists(prof_stub, comp_stub) comp_stubs.append(comp_stub) context = prof_stub.context() # Create delete plan plan = [] for comp_stub in comp_stubs: comp_stub.delete(context, plan) # Execute delete plan for op in plan: operation_execute(op, context) # Update component stub list for op in plan: comp_stub = prof_stub.component(op.name()) if comp_stub not in comp_stubs: comp_stubs.append(comp_stub) # Create insert plan plan = [] for comp_stub in comp_stubs: comp_stub.insert(context, plan) # Execute insert plan for op in plan: operation_execute(op, context)
@param string $input @param int $length @param string $string @param int $type @return string
public static function pad(string $input, int $length, string $string = ' ', int $type = STR_PAD_RIGHT): string { $diff = strlen($input) - mb_strlen($input, 'utf-8'); return str_pad($input, $length + $diff, $string, $type); }
The system creates a new draft version as a copy from the current version. @param mixed $contentId @throws ForbiddenException if the current version is already a draft @return \eZ\Publish\Core\REST\Server\Values\CreatedVersion
public function createDraftFromCurrentVersion($contentId) { $contentInfo = $this->repository->getContentService()->loadContentInfo($contentId); $contentType = $this->repository->getContentTypeService()->loadContentType($contentInfo->contentTypeId); $versionInfo = $this->repository->getContentService()->loadVersionInfo( $contentInfo ); if ($versionInfo->isDraft()) { throw new ForbiddenException('Current version is already in status DRAFT'); } $contentDraft = $this->repository->getContentService()->createContentDraft($contentInfo); return new Values\CreatedVersion( array( 'version' => new Values\Version( $contentDraft, $contentType, $this->repository->getContentService()->loadRelations($contentDraft->getVersionInfo()) ), ) ); }
Set name @throws \InvalidArgumentException if the name is empty @param string $name Capability name @return \RolesCapabilities\Capability
public function setName(string $name): \RolesCapabilities\Capability { if (empty($name)) { throw new InvalidArgumentException("Name cannot be empty"); } $this->name = $name; return $this; }
// Receives a multi-part message.
func (s *Socket) Recv() (parts [][]byte, err error) { parts = make([][]byte, 0) for more := true; more; { var part []byte if part, more, err = s.RecvPart(); err != nil { return } parts = append(parts, part) } return }
Prints alerts and updates the prompt any time the prompt is showing
def _alerter_thread_func(self) -> None: self._alert_count = 0 self._next_alert_time = 0 while not self._stop_thread: # Always acquire terminal_lock before printing alerts or updating the prompt # To keep the app responsive, do not block on this call if self.terminal_lock.acquire(blocking=False): # Get any alerts that need to be printed alert_str = self._generate_alert_str() # Generate a new prompt new_prompt = self._generate_colored_prompt() # Check if we have alerts to print if alert_str: # new_prompt is an optional parameter to async_alert() self.async_alert(alert_str, new_prompt) new_title = "Alerts Printed: {}".format(self._alert_count) self.set_window_title(new_title) # No alerts needed to be printed, check if the prompt changed elif new_prompt != self.prompt: self.async_update_prompt(new_prompt) # Don't forget to release the lock self.terminal_lock.release() time.sleep(0.5)
// Warningf forwards to Logger.Warning
func (l logf) Warningf(s string, args ...interface{}) { l.log.Warning(s, args...) }
Build an instance of TodayInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.usage.record.today.TodayInstance :rtype: twilio.rest.api.v2010.account.usage.record.today.TodayInstance
def get_instance(self, payload): return TodayInstance(self._version, payload, account_sid=self._solution['account_sid'], )
// SetAuthenticationToken sets the AuthenticationToken field's value.
func (s *CreateUserInput) SetAuthenticationToken(v string) *CreateUserInput { s.AuthenticationToken = &v return s }
// Everything but the last element of the full type name, CamelCased. // The values of type Foo.Bar are call Foo_value1... not Foo_Bar_value1... .
func (e *EnumDescriptor) prefix() string { typeName := e.alias() if e.parent == nil { // If the enum is not part of a message, the prefix is just the type name. return CamelCase(typeName[len(typeName)-1]) + "_" } return CamelCaseSlice(typeName[0:len(typeName)-1]) + "_" }
expects pages/:name/template.hbs
function (id) { var o = this.options; return path.resolve(o.root, o.viewsDir, id, "template" + o.extension); }
General power-of-2 base conversion.
def convertbits(data, frombits, tobits, pad=True): """""" acc = 0 bits = 0 ret = [] maxv = (1 << tobits) - 1 max_acc = (1 << (frombits + tobits - 1)) - 1 for value in data: if value < 0 or (value >> frombits): return None acc = ((acc << frombits) | value) & max_acc bits += frombits while bits >= tobits: bits -= tobits ret.append((acc >> bits) & maxv) if pad: if bits: ret.append((acc << (tobits - bits)) & maxv) elif bits >= frombits or ((acc << (tobits - bits)) & maxv): return None return ret
Adds new tag words. @param string[] $allWords All words extracted from post @throws Exception
protected function addNewWords($allWords) { try { $newWords = $allWords; $query = (new Query())->from(Vocabulary::tableName())->where(['word' => $allWords]); foreach ($query->each() as $vocabularyFound) { if (($key = array_search($vocabularyFound['word'], $allWords)) !== false) { unset($newWords[$key]); } } $formatWords = []; foreach ($newWords as $word) { $formatWords[] = [$word]; } if (!empty($formatWords)) { if (!Podium::getInstance()->db->createCommand()->batchInsert( Vocabulary::tableName(), ['word'], $formatWords )->execute()) { throw new Exception('Words saving error!'); } } } catch (Exception $e) { Log::error($e->getMessage(), null, __METHOD__); throw $e; } }