comment
stringlengths
16
255
code
stringlengths
52
3.87M
// Info returns detailed configuration information about the selected server.
func (s *ServerMethods) Info() (*Server, error) { r := &Server{} if _, err := s.ExecCmd(NewCmd("serverinfo").WithResponse(&r)); err != nil { return nil, err } return r, nil }
Get parameter from a form for creating a pager URL. @param Form $form @return array
public function getPrmForUrl(Form $form) { $ret = array(); foreach ($form->getData() as $k => $data) { if (isset($data['value'])) { $data['value'] = $this->prepareDataForUrl($data['value'], $form->get($k)->get('value')); $ret[$k] = $data; } } return count($ret) ? array($form->getName() => $ret) : array(); }
// AddParser adds DagParser under give input encoding and format
func (iep InputEncParsers) AddParser(ienc, format string, f DagParser) { m, ok := iep[ienc] if !ok { m = make(FormatParsers) iep[ienc] = m } m[format] = f }
<!-- begin-user-doc --> <!-- end-user-doc --> @generated
@Override public void eUnset(int featureID) { switch (featureID) { case AfplibPackage.GBOX__RES: setRES(RES_EDEFAULT); return; case AfplibPackage.GBOX__XPOS0: setXPOS0(XPOS0_EDEFAULT); return; case AfplibPackage.GBOX__YPOS0: setYPOS0(YPOS0_EDEFAULT); return; case AfplibPackage.GBOX__XPOS1: setXPOS1(XPOS1_EDEFAULT); return; case AfplibPackage.GBOX__YPOS1: setYPOS1(YPOS1_EDEFAULT); return; case AfplibPackage.GBOX__HAXIS: setHAXIS(HAXIS_EDEFAULT); return; case AfplibPackage.GBOX__VAXIS: setVAXIS(VAXIS_EDEFAULT); return; } super.eUnset(featureID); }
Saves extracted strings from the project to locale mo and po files.
private function saveStringToLocales() { $gettextEntries = $this->extractGettextStrings(); $root = Strata::getRootPath(); foreach ($gettextEntries as $translation) { $references = $translation->getReferences(); $translation->deleteReferences(); foreach ($references as $idx => $context) { $translation->addReference(str_replace($root, "~", $context[0]), $context[1]); } } foreach ($this->getLocales() as $locale) { $this->addGettextEntriesToLocale($locale, $gettextEntries); } }
Derive q home from the environment
def get_q_home(env): """""" q_home = env.get('QHOME') if q_home: return q_home for v in ['VIRTUAL_ENV', 'HOME']: prefix = env.get(v) if prefix: q_home = os.path.join(prefix, 'q') if os.path.isdir(q_home): return q_home if WINDOWS: q_home = os.path.join(env['SystemDrive'], r'\q') if os.path.isdir(q_home): return q_home raise RuntimeError('No suitable QHOME.')
Finds all documents which match with the given example, then apply the given sort to results @param example example object to construct query with @param sort sort object to sort results @param <S> @return sorted iterable of all matching documents
@Override public <S extends T> Iterable<S> findAll(final Example<S> example, final Sort sort) { final ArangoCursor cursor = findAllInternal(sort, example, new HashMap()); return cursor; }
// Readdir creates FileInfo entries by calling Lstat if possible.
func (l *languageFile) Readdir(c int) (ofi []os.FileInfo, err error) { names, err := l.File.Readdirnames(c) if err != nil { return nil, err } fis := make([]os.FileInfo, len(names)) for i, name := range names { fi, _, err := l.fs.LstatIfPossible(filepath.Join(l.Name(), name)) if err != nil { return nil, err } fis[i] = fi } return fis, err }
Create AuthController.
public function createAuthController() { $authController = $this->directory.'/Controllers/AuthController.php'; $contents = $this->getStub('AuthController'); $this->laravel['files']->put( $authController, str_replace('DummyNamespace', Admin::controllerNamespace(), $contents) ); $this->line('<info>AuthController file was created:</info> '.str_replace(base_path(), '', $authController)); }
Use up()/down() to run migration code without a transaction.
public function up() { $table = file_get_contents(dirname(__FILE__) . '/media.sql'); return $this->db->createCommand($table)->execute(); }
handle a message and return an gif
def on_message(msg, server): """""" text = msg.get("text", "") match = re.findall(r"!gif (.*)", text) if not match: return res = gif(match[0]) if not res: return attachment = { "fallback": match[0], "title": match[0], "title_link": res, "image_url": res } server.slack.post_message( msg['channel'], '', as_user=server.slack.username, attachments=json.dumps([attachment]))
Output a string @param string $str String to output @param false|int $row The optional row to output to @param false|int $col The optional column to output to
public static function string( $str, $row = null, $col = null ) { if( $col !== null || $row !== null ) { Cursor::rowcol($row, $col); } fwrite(self::$stream, $str); }
Get a list of parsed recipes from BeerXML input
def parse(self, xml_file): "" recipes = [] with open(xml_file, "rt") as f: tree = ElementTree.parse(f) for recipeNode in tree.iter(): if self.to_lower(recipeNode.tag) != "recipe": continue recipe = Recipe() recipes.append(recipe) for recipeProperty in list(recipeNode): tag_name = self.to_lower(recipeProperty.tag) if tag_name == "fermentables": for fermentable_node in list(recipeProperty): fermentable = Fermentable() self.nodes_to_object(fermentable_node, fermentable) recipe.fermentables.append(fermentable) elif tag_name == "yeasts": for yeast_node in list(recipeProperty): yeast = Yeast() self.nodes_to_object(yeast_node, yeast) recipe.yeasts.append(yeast) elif tag_name == "hops": for hop_node in list(recipeProperty): hop = Hop() self.nodes_to_object(hop_node, hop) recipe.hops.append(hop) elif tag_name == "miscs": for misc_node in list(recipeProperty): misc = Misc() self.nodes_to_object(misc_node, misc) recipe.miscs.append(misc) elif tag_name == "style": style = Style() recipe.style = style self.nodes_to_object(recipeProperty, style) elif tag_name == "mash": for mash_node in list(recipeProperty): mash = Mash() recipe.mash = mash if self.to_lower(mash_node.tag) == "mash_steps": for mash_step_node in list(mash_node): mash_step = MashStep() self.nodes_to_object(mash_step_node, mash_step) mash.steps.append(mash_step) else: self.nodes_to_object(mash_node, mash) else: self.node_to_object(recipeProperty, recipe) return recipes
Clean up the child procress and socket. @throws IOException
void cleanup() throws IOException { serverSocket.close(); try { downlink.close(); } catch (InterruptedException ie) { Thread.currentThread().interrupt(); } }
Remove a logger by passing in its instance. @param LoggerInterface $logger @param bool $trigger @return AggregateLogger
public function removeLoggerByInstance($logger, $trigger = true) { foreach ($this->loggers as $key => $addedLogger) { if ($addedLogger[0] === $logger) { unset($this->loggers[$key]); return $this; } } if ($trigger) { $class = get_class($logger); trigger_error("Logger $class was removed without being added."); } return $this; }
Clean the user data. @param stdClass|array $user the user data to be validated against properties definition. @return stdClass $user the cleaned user data.
public static function clean_data($user) { if (empty($user)) { return $user; } foreach ($user as $field => $value) { // Get the property parameter type and do the cleaning. try { $user->$field = core_user::clean_field($value, $field); } catch (coding_exception $e) { debugging("The property '$field' could not be cleaned.", DEBUG_DEVELOPER); } } return $user; }
Set owner for an existing file. @throws IOException
public void setOwner(String src, String username, String group ) throws IOException { INode[] inodes = null; writeLock(); try { if (isInSafeMode()) { throw new SafeModeException("Cannot set permission for " + src, safeMode); } inodes = dir.getExistingPathINodes(src); if (isPermissionCheckingEnabled(inodes)) { FSPermissionChecker pc = checkOwner(src, inodes); if (!pc.isSuper) { if (username != null && !pc.user.equals(username)) { if (this.permissionAuditOnly) { // do not throw the exception, we would like to only log. LOG.warn("PermissionAudit failed on " + src + ": non-super user cannot change owner."); } else { throw new AccessControlException("Non-super user cannot change owner."); } } if (group != null && !pc.containsGroup(group)) { if (this.permissionAuditOnly) { // do not throw the exception, we would like to only log. LOG.warn("PermissionAudit failed on " + src + ": user does not belong to " + group + " ."); } else { throw new AccessControlException("User does not belong to " + group + " ."); } } } } dir.setOwner(src, username, group); } finally { writeUnlock(); } getEditLog().logSync(false); if (auditLog.isInfoEnabled()) { logAuditEvent(getCurrentUGI(), Server.getRemoteIp(), "setOwner", src, null, getLastINode(inodes)); } }
// Init implements Command.Init.
func (c *deleteImageMetadataCommand) Init(args []string) (err error) { if len(args) == 0 { return errors.New("image ID must be supplied when deleting image metadata") } if len(args) != 1 { return errors.New("only one image ID can be supplied as an argument to this command") } c.ImageId = args[0] return nil }
Set the detected keyword text. @param keyword detected keyword text
public void setKeyword(String keyword) { if(keyword != null) { keyword = keyword.trim(); } this.keyword = keyword; }
Retrieve prev node. @return NodeContract|null
public function prev() { return $this->getParent() !== null ? $this->getParent()->getChildByIndex($this->getIndex() - 1) : null; }
Convert content to CSV. @param array $data @param array $config @return \Orchestra\Support\Collection
protected function convertToExcel(array $data, array $config): Collection { $uses = $config['uses'] ?? 'data'; $content = $data[$uses] ?? []; if ($content instanceof Arrayable) { $content = $content->toArray(); } return Collection::make(\array_map([$this, 'transformToArray'], $content)); }
Return an object as a dictionary of its attributes.
def get_as_dict(x): """""" if isinstance(x, dict): return x else: try: return x._asdict() except AttributeError: return x.__dict__
split a json-reference into (url, json-pointer)
def jr_split(s): p = six.moves.urllib.parse.urlparse(s) return ( normalize_url(six.moves.urllib.parse.urlunparse(p[:5]+('',))), '#'+p.fragment if p.fragment else '#' )
Get the children of each element in the set of matched elements, optionally filtering by selector.
function children(selector) { var arr = [], slice = this.slice, nodes, matches; this.each(function(el) { nodes = slice.call(el.childNodes); // only include elements nodes = nodes.filter(function(n) { if(n instanceof Element) { return n;} }) // filter direct descendants by selector if(selector) { matches = slice.call(el.querySelectorAll(selector)); for(var i = 0;i < nodes.length;i++) { if(~matches.indexOf(nodes[i])) { arr.push(nodes[i]); } } // get all direct descendants }else{ arr = arr.concat(nodes); } }); return this.air(arr); }
Asserts that the next token in the stream matches the specified token. @param token expected token @throws ParseException
public void assertToken(final int token) throws ParseException { try { if (nextToken() != token) { throw new ParseException("Expected [" + token + "], read [" + ttype + "] at " + lineno()); } if (debug()) { if (token > 0) { debug("[" + (char)token + "]"); } else { debug("[" + token + "]"); } } } catch (IOException e) { throw new ParseException(e); } }
Heatmap Chart @class
function Heatmap() { var canvas = zrUtil.createCanvas(); this.canvas = canvas; this.blurSize = 30; this.pointSize = 20; this.maxOpacity = 1; this.minOpacity = 0; this._gradientPixels = {}; }
Caches the value into redis with errors suppressed. @param string $key The key. @param string $value The value. @param int $cacheTime The optional cache time @return void
private function cache(string $key, string $value, int $cacheTime = null) { try { $this->client->set($key, $value); if ($cacheTime !== null) { $this->client->expire($key, $cacheTime); } } catch (\Exception $e) { // We don't want exceptions in accessing the cache to break functionality. // The cache should be as transparent as possible. // If insight is needed into these exceptions, // a better way would be by notifying an observer with the errors. } }
A method (exposed on return object for external use) that mimics onload by polling document.styleSheets until it includes the new sheet.
function( cb ){ var resolvedHref = ss.href; var i = sheets.length; while( i-- ){ if( sheets[ i ].href === resolvedHref ){ return cb(); } } setTimeout(function() { onloadcssdefined( cb ); }); }
// Retrieves a list of entries after a given index as well as the term of the // index provided. A nil list of entries is returned if the index no longer // exists because a snapshot was made.
func (l *Log) getEntriesAfter(index uint64, maxLogEntriesPerRequest uint64) ([]*LogEntry, uint64) { l.mutex.RLock() defer l.mutex.RUnlock() // Return nil if index is before the start of the log. if index < l.startIndex { traceln("log.entriesAfter.before: ", index, " ", l.startIndex) return nil, 0 } // Return an error if the index doesn't exist. if index > (uint64(len(l.entries)) + l.startIndex) { panic(fmt.Sprintf("raft: Index is beyond end of log: %v %v", len(l.entries), index)) } // If we're going from the beginning of the log then return the whole log. if index == l.startIndex { traceln("log.entriesAfter.beginning: ", index, " ", l.startIndex) return l.entries, l.startTerm } traceln("log.entriesAfter.partial: ", index, " ", l.entries[len(l.entries)-1].Index) entries := l.entries[index-l.startIndex:] length := len(entries) traceln("log.entriesAfter: startIndex:", l.startIndex, " length", len(l.entries)) if uint64(length) < maxLogEntriesPerRequest { // Determine the term at the given entry and return a subslice. return entries, l.entries[index-1-l.startIndex].Term() } else { return entries[:maxLogEntriesPerRequest], l.entries[index-1-l.startIndex].Term() } }
Create an equivalent signature string for a NumPy gufunc. Unlike __str__, handles dimensions that don't map to Python identifiers.
def to_gufunc_string(self): all_dims = self.all_core_dims dims_map = dict(zip(sorted(all_dims), range(len(all_dims)))) input_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims] for core_dims in self.input_core_dims] output_core_dims = [['dim%d' % dims_map[dim] for dim in core_dims] for core_dims in self.output_core_dims] alt_signature = type(self)(input_core_dims, output_core_dims) return str(alt_signature)
Pushes a new item into the jiterator. The new item will be added to the end of the jiterator. @param item the item to be added @throws IllegalStateException an attempt was made to push an item on a jiterator marked complete
public synchronized void push(@Nullable T item) { if( waiting == null ) { throw new IllegalStateException("Invalid attempt to add an item to a completed list."); } if( filter != null ) { try { if( !filter.filter(item) ) { return; } } catch( Throwable t ) { logger.error("[" + this + "] Error filtering " + item + ": " + t.getMessage()); Exception e; if( t instanceof Exception ) { e = (Exception)t; } else { e = new RuntimeException(t); } setLoadException(e); return; } } waiting.add(item); lastTouch = System.currentTimeMillis(); notifyAll(); }
Returns the sorted xml as an OutputStream. @return the sorted xml
public String getSortedXml(Document newDocument) { try (ByteArrayOutputStream sortedXml = new ByteArrayOutputStream()) { BufferedLineSeparatorOutputStream bufferedLineOutputStream = new BufferedLineSeparatorOutputStream(lineSeparatorUtil.toString(), sortedXml); XMLOutputter xmlOutputter = new PatchedXMLOutputter(bufferedLineOutputStream, indentBlankLines); xmlOutputter.setFormat(createPrettyFormat()); xmlOutputter.output(newDocument, bufferedLineOutputStream); bufferedLineOutputStream.close(); return sortedXml.toString(encoding); } catch (IOException ioex) { throw new FailureException("Could not format pom files content", ioex); } }
// 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) }
获取当前的关联模型类的实例 @access public @return Model
public function getModel() { $morphType = $this->morphType; $model = $this->parseModel($this->parent->$morphType); return (new $model); }
Read file by handle and verify if content is expired @param resource $handle file handle @param string $file file path @return false|array false or file content array
protected function readAndVerify($handle, $file) { // Read all content $content = fread($handle, filesize($file)); $content = @unserialize($content); // Check if content is valid if ($content && is_array($content) && time() < $content[0]) { return $content; } else { return false; } }
:return AudioPortBuilder
def generate_builder(self, json, audio_port): if 'effect' in json[audio_port]: return Lv2AudioPortBuilder(self.pedalboard) else: return SystemAudioPortBuilder(self.system_effect)
Returns curent fate time in RFC1123 format, using UTC time zone @return string
private function getRFC1123DateString() { $date = new \DateTime(null, new \DateTimeZone("UTC")); return str_replace("+0000", "GMT", $date->format(\DateTime::RFC1123)); }
// appendUpdate appends a new update to the tip of the updateLog. The entry is // also added to index accordingly.
func (u *updateLog) appendUpdate(pd *PaymentDescriptor) { u.updateIndex[u.logIndex] = u.PushBack(pd) u.logIndex++ }
Find file file. @param callingFrame the calling frame @return the file
@javax.annotation.Nonnull public static File findFile(@javax.annotation.Nonnull final StackTraceElement callingFrame) { @javax.annotation.Nonnull final String[] packagePath = callingFrame.getClassName().split("\\."); @javax.annotation.Nonnull final String path = Arrays.stream(packagePath).limit(packagePath.length - 1).collect(Collectors.joining(File.separator)) + File.separator + callingFrame.getFileName(); return com.simiacryptus.util.lang.CodeUtil.findFile(path); }
Sets the data of a node at the given path, or creates it.
def set_or_create(self, path, *args, **kwargs): """""" d = self.set(path, *args, **kwargs) @d.addErrback def _error(result): return self.create(path, *args, **kwargs) return d
read config from confingPath @param confingFilename like axu4j.xml
public static void load(String confingFilename) { try { if (config == null) { config = new AXUConfig(); logger.debug("create new AXUConfig instance"); } // DEV 모드인 경우 각 태그마다 config를 요청하므로 3초에 한 번씩만 설정을 로딩하도록 한다. long nowTime = (new Date()).getTime(); if (nowTime - lastLoadTime < 3000) { return; } else { lastLoadTime = nowTime; } Serializer serializer = new Persister(); URL configUrl = config.getClass().getClassLoader().getResource(confingFilename); if (configUrl == null) { configUrl = ClassLoader.getSystemClassLoader().getResource(confingFilename); } File configFile = new File(configUrl.toURI()); serializer.read(config, configFile); logger.info("load config from {}", configFile.getAbsolutePath()); if (logger.isDebugEnabled()) { logger.debug("axu4j.xml\n{}", config); } } catch(Exception e) { logger.error("Fail to load axu4j.xml", e); } }
// needsUpdate returns true if the given row needs to be updated to match the given config.
func (*RackKVMsTable) needsUpdate(row, cfg *RackKVM) bool { return row.KVMId != cfg.KVMId }
see all of these messages and control their transmission.
public void handleInitiateResponseMessage(InitiateResponseMessage message) { final VoltTrace.TraceEventBatch traceLog = VoltTrace.log(VoltTrace.Category.MPI); if (traceLog != null) { traceLog.add(() -> VoltTrace.endAsync("initmp", message.getTxnId())); } DuplicateCounter counter = m_duplicateCounters.get(message.getTxnId()); // A transaction may be routed back here for EveryPartitionTask via leader migration if (counter != null && message.isMisrouted()) { tmLog.info("The message on the partition is misrouted. TxnID: " + TxnEgo.txnIdToString(message.getTxnId())); Long newLeader = m_leaderMigrationMap.get(message.m_sourceHSId); if (newLeader != null) { // Update the DuplicateCounter with new replica counter.updateReplica(message.m_sourceHSId, newLeader); m_leaderMigrationMap.remove(message.m_sourceHSId); // Leader migration has updated the leader, send the request to the new leader m_mailbox.send(newLeader, counter.getOpenMessage()); } else { // Leader migration not done yet. m_mailbox.send(message.m_sourceHSId, counter.getOpenMessage()); } return; } if (counter != null) { int result = counter.offer(message); if (result == DuplicateCounter.DONE) { m_duplicateCounters.remove(message.getTxnId()); // Only advance the truncation point on committed transactions that sent fragments to SPIs. // See ENG-4211 & ENG-14563 if (message.shouldCommit() && message.haveSentMpFragment()) { m_repairLogTruncationHandle = m_repairLogAwaitingCommit; m_repairLogAwaitingCommit = message.getTxnId(); } m_outstandingTxns.remove(message.getTxnId()); m_mailbox.send(counter.m_destinationId, message); } else if (result == DuplicateCounter.MISMATCH) { VoltDB.crashLocalVoltDB("HASH MISMATCH running every-site system procedure.", true, null); } else if (result == DuplicateCounter.ABORT) { VoltDB.crashLocalVoltDB("PARTIAL ROLLBACK/ABORT running every-site system procedure.", true, null); } // doing duplicate suppresion: all done. } else { // Only advance the truncation point on committed transactions that sent fragments to SPIs. if (message.shouldCommit() && message.haveSentMpFragment()) { m_repairLogTruncationHandle = m_repairLogAwaitingCommit; m_repairLogAwaitingCommit = message.getTxnId(); } MpTransactionState txn = (MpTransactionState)m_outstandingTxns.remove(message.getTxnId()); assert(txn != null); // the initiatorHSId is the ClientInterface mailbox. Yeah. I know. m_mailbox.send(message.getInitiatorHSId(), message); // We actually completed this MP transaction. Create a fake CompleteTransactionMessage // to send to our local repair log so that the fate of this transaction is never forgotten // even if all the masters somehow die before forwarding Complete on to their replicas. CompleteTransactionMessage ctm = new CompleteTransactionMessage(m_mailbox.getHSId(), message.m_sourceHSId, message.getTxnId(), message.isReadOnly(), 0, !message.shouldCommit(), false, false, false, txn.isNPartTxn(), message.m_isFromNonRestartableSysproc, false); ctm.setTruncationHandle(m_repairLogTruncationHandle); // dump it in the repair log // hacky castage ((MpInitiatorMailbox)m_mailbox).deliverToRepairLog(ctm); } }
Reduce the strings. @param int $start Position of first character. @param int $length Maximum number of characters. @return self
public function reduce($start, $length = null) { $this->_string = \mb_substr($this->_string, $start, $length); return $this; }
Creates a connection manager from a <code>.kkdb.php</code> config file. @param string $file @return ConnectionManager @throws \RuntimeException When the config file could not be found.
public static function fromConfigFile($file) { if(!is_file($file)) { throw new \RuntimeException(sprintf('Config file "%s" does not exist', $file)); } $config = new Configuration(static::processConfigFileData(require $file)); return new ConnectionManager($config->getConfig('ConnectionManager')); }
The first two time delay weighted statistical moments of the MA coefficients.
def moments(self): """""" moment1 = statstools.calc_mean_time(self.delays, self.coefs) moment2 = statstools.calc_mean_time_deviation( self.delays, self.coefs, moment1) return numpy.array([moment1, moment2])
Registers a callback to be invoked when the RDFValue named is declared.
def RegisterLateBindingCallback(target_name, callback, **kwargs): """""" _LATE_BINDING_STORE.setdefault(target_name, []).append((callback, kwargs))
Is authenticating at a public workstation? @param ctx the ctx @return true if the cookie value is present
public static boolean isAuthenticatingAtPublicWorkstation(final RequestContext ctx) { if (ctx.getFlowScope().contains(PUBLIC_WORKSTATION_ATTRIBUTE)) { LOGGER.debug("Public workstation flag detected. SSO session will be considered renewed."); return true; } return false; }
Accept url @param string $until @return string
protected function acceptUrl( $until = ';' ) { if ( 'url' == strtolower( substr( $this->buffer, 0, 3 ) ) ) { $this->buffer = substr( $this->buffer, 3 ); $this->acceptWhiteSpace(); if ( '(' == $this->buffer[0] ) { $this->buffer = substr( $this->buffer, 1 ); $this->acceptWhiteSpace(); $result = $this->acceptString( ')' ); if ( ')' == $this->buffer[0] ) { $this->buffer = substr( $this->buffer, 1 ); $this->acceptWhiteSpace(); } return $result; } } return $this->acceptString( $until ); }
Returns aliased value or default value if requested alias does not exists. @param string $name @param string|null $default @return string|null
public function get($name, $default = null) { if (array_key_exists($name, $this->aliases)) { return $this->aliases[$name]; } else { return $default; } }
Initializes the status list.
def init_with_context(self, context): super(CacheStatusGroup, self).init_with_context(context) if 'dashboardmods' in settings.INSTALLED_APPS: import dashboardmods memcache_mods = dashboardmods.get_memcache_dash_modules() try: varnish_mods = dashboardmods.get_varnish_dash_modules() except (socket.error, KeyError) as e: # dashboardmods 2.2 throws KeyError for 'cache_misses' when the Varnish cache is empty. # Socket errors are also ignored, to work similar to the memcache stats. logger.exception("Unable to request Varnish stats: {0}".format(str(e))) varnish_mods = [] except ImportError: varnish_mods = [] self.children = memcache_mods + varnish_mods
// Needs to be called to allocate the GPIO pin
func (op *DTGPIOModuleOpenPin) gpioUnexport() error { s := strconv.FormatInt(int64(op.gpioLogical), 10) e := WriteStringToFile("/sys/class/gpio/unexport", s) if e != nil { return e } return nil }
Renders the HTML head @param $custom_head_markup string A string of data to include in the HTML head, right before </head>
public function htmlHead($custom_head_markup = '') { if (!empty($custom_head_markup)) { $this->custom_head_markup = $custom_head_markup; } $html = $this->doc_type . "\n"; $html .= $this->opening_html_tag . "\n"; $html .= '<head>' . "\n"; $html .= '<meta http-equiv="Content-Type" content="text/html; charset=' . $this->charset . '" />' . "\n"; $html .= '<meta http-equiv="X-UA-Compatible" content="IE=edge" />'."\n"; $html .= '<title>' . $this->title . '</title>' . "\n"; if ($this->meta instanceof HeadMeta) { foreach (get_object_vars($this->meta) as $key => $val) { $html .= '<meta name="' . $key . '" content="' . $val . '" />' . "\n"; } } $html .= '<style type="text/css">'; foreach ($this->styles as $style) { if (!preg_match("~^(http|/)~", $style)) { $style = '/css/' . $style; } $html .= "@import '" . $style . "';\n"; } $html .= "</style>\n"; if (!empty($this->custom_head_markup)) { $html.= $this->custom_head_markup; } $html.= "</head>\n"; return $html; }
Create a new Date. To the last day.
public static java.sql.Date newDate() { return new java.sql.Date((System.currentTimeMillis() / DAY_MILLIS) * DAY_MILLIS); }
Drops the database indices relating to n-grams.
def _drop_indices(self): """""" self._logger.info('Dropping database indices') self._conn.execute(constants.DROP_TEXTNGRAM_INDEX_SQL) self._logger.info('Finished dropping database indices')
Retrieve object metadata only.
def head_object(self, bucket, object_name): details = self._details( method=b"HEAD", url_context=self._url_context(bucket=bucket, object_name=object_name), ) d = self._submit(self._query_factory(details)) d.addCallback(lambda (response, body): _to_dict(response.responseHeaders)) return d
set the self link on the resource @param string $href @param array $meta optional
public function setSelfLink($href, array $meta=[], $level=Document::LEVEL_RESOURCE) { $this->ensureResourceObject(); if ($level === Document::LEVEL_RESOURCE) { $this->resource->setSelfLink($href, $meta); } else { parent::setSelfLink($href, $meta, $level); } }
// * Check if user passphrase matches argument. Launches SecretUI prompt if // * passphrase argument is empty. Returns `true` if passphrase is correct, // * false if not, or an error if something else went wrong.
func (c AccountClient) PassphraseCheck(ctx context.Context, __arg PassphraseCheckArg) (res bool, err error) { err = c.Cli.Call(ctx, "keybase.1.account.passphraseCheck", []interface{}{__arg}, &res) return }
Sanitize Naughty HTML Callback method for xss_clean() to remove naughty HTML elements. @used-by XSS::clean() @param array $matches @return string
protected static function sanitizeNaughtyHTML($matches) { // First, escape unclosed tags if (empty($matches[ 'closeTag' ])) { return '&lt;' . $matches[ 1 ]; } // Is the element that we caught naughty? If so, escape it elseif (in_array(strtolower($matches[ 'tagName' ]), self::getConfig('naughty_tags'), true)) { return '&lt;' . $matches[ 1 ] . '&gt;'; } // For other tags, see if their attributes are "evil" and strip those elseif (isset($matches[ 'attributes' ])) { // We'll store the already fitlered attributes here $attributes = []; // Attribute-catching pattern $attributesPattern = '#' . '(?<name>[^\s\042\047>/=]+)' // attribute characters // optional attribute-value . '(?:\s*=(?<value>[^\s\042\047=><`]+|\s*\042[^\042]*\042|\s*\047[^\047]*\047|\s*(?U:[^\s\042\047=><`]*)))' // attribute-value separator . '#i'; // Blacklist pattern for evil attribute names $is_evil_pattern = '#^(' . implode('|', self::getConfig('evil_attributes')) . ')$#i'; // Each iteration filters a single attribute do { // Strip any non-alpha characters that may preceed an attribute. // Browsers often parse these incorrectly and that has been a // of numerous XSS issues we've had. $matches[ 'attributes' ] = preg_replace('#^[^a-z]+#i', '', $matches[ 'attributes' ]); if ( ! preg_match($attributesPattern, $matches[ 'attributes' ], $attribute, PREG_OFFSET_CAPTURE)) { // No (valid) attribute found? Discard everything else inside the tag break; } if ( // Is it indeed an "evil" attribute? preg_match($is_evil_pattern, $attribute[ 'name' ][ 0 ]) // Or does it have an equals sign, but no value and not quoted? Strip that too! OR (trim($attribute[ 'value' ][ 0 ]) === '') ) { $attributes[] = 'xss=removed'; } else { $attributes[] = $attribute[ 0 ][ 0 ]; } $matches[ 'attributes' ] = substr( $matches[ 'attributes' ], $attribute[ 0 ][ 1 ] + strlen($attribute[ 0 ][ 0 ]) ); } while ($matches[ 'attributes' ] !== ''); $attributes = empty($attributes) ? '' : ' ' . implode(' ', $attributes); return '<' . $matches[ 'slash' ] . $matches[ 'tagName' ] . $attributes . '>'; } return $matches[ 0 ]; }
// Drive is called from simra. // This is used to update sprites position. // This will be called 60 times per sec.
func (s *sample) Drive() { degree++ if degree >= 360 { degree = 0 } p := s.ball.GetPosition() switch s.buttonState { case ctrlUp: s.ball.SetPositionY(p.Y + 1) case ctrlDown: s.ball.SetPositionY(p.Y - 1) } s.ball.SetRotate(degree * math.Pi / 180) }
// SetPlatform sets the Platform field's value.
func (s *ADMChannelResponse) SetPlatform(v string) *ADMChannelResponse { s.Platform = &v return s }
// SetRenderTarget sets a texture as the current rendering target. // (https://wiki.libsdl.org/SDL_SetRenderTarget)
func (renderer *Renderer) SetRenderTarget(texture *Texture) error { return errorFromInt(int( C.SDL_SetRenderTarget(renderer.cptr(), texture.cptr()))) }
Allows the ability to override the Inmage's Pretty name stored in cache @param string $name
public function setImagePrettyName($name) { $this->set('prettyname', $name); if ($this->image) { $this->image->setPrettyName($name); } }
Assert value is not a bool (boolean). @param mixed $actual @param string $message
public static function assertNotBool($actual, string $message = '') { self::assertTypeOfScalar($actual, $message, 'assertNotBool', new LogicalNot(new ScalarConstraint(ScalarConstraint::TYPE_BOOL))); }
// Encode encodes the parameters into "URL encoded" form ("bar=baz&foo=quux") // sorted by key.
func (p Parameters) Encode() string { var buf bytes.Buffer keys := make([]string, 0, len(p)) for k := range p { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { if buf.Len() > 0 { buf.WriteByte('&') } buf.WriteString(url.QueryEscape(k) + "=") buf.WriteString(url.QueryEscape(p[k])) } return buf.String() }
Lookup (Section 3.4) matches a language priority list consisting of basic language ranges to sets of language tags to find the one exact language tag that best matches the range.
function lookup(tag, range) { var pos tag = lower(tag) range = lower(range) while (true) { if (range === asterisk || tag === range) { return true } pos = range.lastIndexOf(dash) if (pos === -1) { return false } if (pos > 3 && range.charAt(pos - 2) === dash) { pos -= 2 } range = range.substring(0, pos) } }
判断日志级别 @param logger Logger @param l Level @return boolean
public boolean isLoggable(Logger logger, Level l) { return logger.isLoggable(l) && l.intValue() >= this.logLevel; }
Delete all publications @param int $advertised search for advertised courses @param int $shared search for shared courses @throws moodle_exception
public static function delete_all_publications($advertised = true, $shared = true) { global $DB; if (!$advertised && !$shared) { // Nothing to do. return true; } $params = ['huburl' => HUB_MOODLEORGHUBURL]; if (!$advertised || !$shared) { // Retrieve ONLY advertised or ONLY shared. $params['enrollable'] = $advertised ? 1 : 0; } if (!$publications = $DB->get_records('course_published', $params)) { // Nothing to unpublish. return true; } foreach ($publications as $publication) { $hubcourseids[] = $publication->hubcourseid; } api::unregister_courses($hubcourseids); // Delete the published courses from local db. $DB->delete_records('course_published', $params); return true; }
Retrieves (and caches) the locale @param string $locale @return int|null null if language was not found for locale
public function lookUpLanguageIdForLocale($locale) { $locale = $this->normalizeLocale($locale); /** @var Model $languageModel */ $languageModel = static::$cmsLanguageModel; $language = $languageModel::where(config('pxlcms.translatable.locale_code_column'), $locale) ->remember((config('pxlcms.cache.languages', 15))) ->first(); if (empty($language)) return null; return $language->id; }
// SetFilters sets the Filters field's value.
func (s *ListResolverRuleAssociationsInput) SetFilters(v []*Filter) *ListResolverRuleAssociationsInput { s.Filters = v return s }
Get all strips from a scraper.
def _getStrips(self, scraperobj): """""" if self.options.all or self.options.cont: numstrips = None elif self.options.numstrips: numstrips = self.options.numstrips else: # get current strip numstrips = 1 try: if scraperobj.isComplete(self.options.basepath): out.info(u"All comics are already downloaded.") return 0 for strip in scraperobj.getStrips(numstrips): skipped = self.saveComicStrip(strip) if skipped and self.options.cont: # stop when retrieval skipped an image for one comic strip out.info(u"Stop retrieval because image file already exists") break if self.stopped: break if self.options.all and not (self.errors or self.options.dry_run or self.options.cont or scraperobj.indexes): scraperobj.setComplete(self.options.basepath) except Exception as msg: out.exception(msg) self.errors += 1
Utility method to create a single header instance with the given information. If elements already exist, this will delete secondary ones and overlay the value on the first element. @param key @param value @param offset @param length
private void createSingleHeader(HeaderKeys key, byte[] value, int offset, int length) { HeaderElement elem = findHeader(key); if (null != elem) { // delete all secondary instances first if (null != elem.nextInstance) { HeaderElement temp = elem.nextInstance; while (null != temp) { temp.remove(); temp = temp.nextInstance; } } if (HeaderStorage.NOTSET != this.headerChangeLimit) { // parse buffer reuse is enabled, see if we can use existing obj if (length <= elem.getValueLength()) { this.headerChangeCount++; elem.setByteArrayValue(value, offset, length); } else { elem.remove(); elem = null; } } else { // parse buffer reuse is disabled elem.setByteArrayValue(value, offset, length); } } if (null == elem) { // either it didn't exist or we chose not to re-use the object elem = getElement(key); elem.setByteArrayValue(value, offset, length); addHeader(elem, FILTER_NO); } else if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) { Tr.debug(tc, "Replacing header " + key.getName() + " [" + elem.getDebugValue() + "]"); } }
This will give a boolean list corresponding to whether each individual is homozygous for the alternative allele.
def is_homozygous(self, individual=None): if individual is not None: if isinstance(individual, str): individual = self.individuals[individual] alts = self.genotype[individual] return [sum(alts) == len(alts)] if sum(alts) > 0 else [False] else: return [sum(alts) == len(alts) if sum(alts) > 0 else False for i, alts in self.genotype.iteritems()]
Imports a field by its dotted class path, prepending "django.db.models" to raw class names and raising an exception if the import fails.
def import_field(field_classpath): if '.' in field_classpath: fully_qualified = field_classpath else: fully_qualified = "django.db.models.%s" % field_classpath try: return import_dotted_path(fully_qualified) except ImportError: raise ImproperlyConfigured("The EXTRA_MODEL_FIELDS setting contains " "the field '%s' which could not be " "imported." % field_classpath)
build a new timer and add it to the set of running timers.
public Timer newTimer(String opType, int sampleCount) { final Timer timer = new Timer(sampleCount); if (!timers.containsKey(opType)) timers.put(opType, new ArrayList<Timer>()); timers.get(opType).add(timer); return timer; }
Set the rules of this Validator. @param string $lang @param string $langDir @return Validator
public function setLanguage($lang = 'en', $langDir = __DIR__ . '/lang/') { $this->lang = $lang; $this->langDir = $langDir; $langFile = realpath($langDir . $lang . '.php'); if (!file_exists($langFile)) { throw new \InvalidArgumentException('No such file: ' . $langDir . $lang . '.php'); } $callable = require $langFile; $callable($this); return $this; }
Get all fields defined in custom modules. @return array All fields defined in custom modules.
private function getAllCustomFields() { $fields = []; $this->moduleHandler->alter('acm_sku_base_field_additions', $fields); foreach ($fields as $field_code => $field) { $fields[$field_code] = $this->applyDefaults($field_code, $field); } return $fields; }
Update folder. Updates a folder
def update_folder(self, id, hidden=None, lock_at=None, locked=None, name=None, parent_folder_id=None, position=None, unlock_at=None): path = {} data = {} params = {} # REQUIRED - PATH - id """ID""" path["id"] = id # OPTIONAL - name """The new name of the folder""" if name is not None: data["name"] = name # OPTIONAL - parent_folder_id """The id of the folder to move this folder into. The new folder must be in the same context as the original parent folder.""" if parent_folder_id is not None: data["parent_folder_id"] = parent_folder_id # OPTIONAL - lock_at """The datetime to lock the folder at""" if lock_at is not None: data["lock_at"] = lock_at # OPTIONAL - unlock_at """The datetime to unlock the folder at""" if unlock_at is not None: data["unlock_at"] = unlock_at # OPTIONAL - locked """Flag the folder as locked""" if locked is not None: data["locked"] = locked # OPTIONAL - hidden """Flag the folder as hidden""" if hidden is not None: data["hidden"] = hidden # OPTIONAL - position """Set an explicit sort position for the folder""" if position is not None: data["position"] = position self.logger.debug("PUT /api/v1/folders/{id} with query params: {params} and form data: {data}".format(params=params, data=data, **path)) return self.generic_request("PUT", "/api/v1/folders/{id}".format(**path), data=data, params=params, single_item=True)
// DeepCopyObject is an autogenerated deepcopy function, copying the receiver, creating a new runtime.Object.
func (in *ObjectReference) DeepCopyObject() runtime.Object { if c := in.DeepCopy(); c != nil { return c } return nil }
Returns the node's class identifier @return string|bool|string|null
public function classIdentifier() { if ( $this->ClassIdentifier === null ) { $object = $this->object(); $this->ClassIdentifier = $object->contentClassIdentifier(); } return $this->ClassIdentifier; }
Parse from a byte array (containing utf-8 encoded string with the Python literal expression in it)
public Ast parse(byte[] serialized) throws ParseException { try { return parse(new String(serialized, "utf-8")); } catch (UnsupportedEncodingException e) { throw new ParseException(e.toString()); } }
Check a parsed packet and figure out if it is an Eddystone Beacon. If it is , return the relevant data as a dictionary. Return None, it is not an Eddystone Beacon advertising packet
def decode(self, packet): """""" ssu=packet.retrieve("Complete uuids") found=False for x in ssu: if EDDY_UUID in x: found=True break if not found: return None found=False adv=packet.retrieve("Advertised Data") for x in adv: luuid=x.retrieve("Service Data uuid") for uuid in luuid: if EDDY_UUID == uuid: found=x break if found: break if not found: return None try: top=found.retrieve("Adv Payload")[0] except: return None #Rebuild that part of the structure found.payload.remove(top) #Now decode result={} data=top.val etype = aios.EnumByte("type",self.type.val,{ESType.uid.value:"Eddystone-UID", ESType.url.value:"Eddystone-URL", ESType.tlm.value:"Eddystone-TLM", ESType.eid.value:"Eddystone-EID"}) data=etype.decode(data) found.payload.append(etype) if etype.val== ESType.uid.value: power=aios.IntByte("tx_power") data=power.decode(data) found.payload.append(power) result["tx_power"]=power.val nspace=aios.Itself("namespace") xx=nspace.decode(data[:10]) #According to https://github.com/google/eddystone/tree/master/eddystone-uid data=data[10:] found.payload.append(nspace) result["name space"]=nspace.val nspace=aios.Itself("instance") xx=nspace.decode(data[:6]) #According to https://github.com/google/eddystone/tree/master/eddystone-uid data=data[6:] found.payload.append(nspace) result["instance"]=nspace.val elif etype.val== ESType.url.value: power=aios.IntByte("tx_power") data=power.decode(data) found.payload.append(power) result["tx_power"]=power.val url=aios.EnumByte("type",0,{0x00:"http://www.",0x01:"https://www.",0x02:"http://",0x03:"https://"}) data=url.decode(data) result["url"]=url.strval for x in data: if bytes([x]) == b"\x00": result["url"]+=".com/" elif bytes([x]) == b"\x01": result["url"]+=".org/" elif bytes([x]) == b"\x02": result["url"]+=".edu/" elif bytes([x]) == b"\x03": result["url"]+=".net/" elif bytes([x]) == b"\x04": result["url"]+=".info/" elif bytes([x]) == b"\x05": result["url"]+=".biz/" elif bytes([x]) == b"\x06": result["url"]+=".gov/" elif bytes([x]) == b"\x07": result["url"]+=".com" elif bytes([x]) == b"\x08": result["url"]+=".org" elif bytes([x]) == b"\x09": result["url"]+=".edu" elif bytes([x]) == b"\x10": result["url"]+=".net" elif bytes([x]) == b"\x11": result["url"]+=".info" elif bytes([x]) == b"\x12": result["url"]+=".biz" elif bytes([x]) == b"\x13": result["url"]+=".gov" else: result["url"]+=chr(x) #x.decode("ascii") #Yep ASCII only url=aios.String("url") url.decode(result["url"]) found.payload.append(url) elif etype.val== ESType.tlm.value: myinfo=aios.IntByte("version") data=myinfo.decode(data) found.payload.append(myinfo) myinfo=aios.ShortInt("battery") data=myinfo.decode(data) result["battery"]=myinfo.val found.payload.append(myinfo) myinfo=aios.Float88("temperature") data=myinfo.decode(data) found.payload.append(myinfo) result["temperature"]=myinfo.val myinfo=aios.LongInt("pdu count") data=myinfo.decode(data) found.payload.append(myinfo) result["pdu count"]=myinfo.val myinfo=aios.LongInt("uptime") data=myinfo.decode(data) found.payload.append(myinfo) result["uptime"]=myinfo.val*100 #in msecs return result #elif etype.val== ESType.tlm.eid: else: result["data"]=data xx=Itself("data") xx.decode(data) found.payload.append(xx) rssi=packet.retrieve("rssi") if rssi: result["rssi"]=rssi[-1].val mac=packet.retrieve("peer") if mac: result["mac address"]=mac[-1].val return result
Append an integer index array of values to this XML document @param array $data @param string $elementName @param string|null $nsPrefix @param string|null $nsUri @return bool
public function appendList(array $data, $elementName, $nsPrefix = null, $nsUri = null) { if (null === $nsPrefix) { foreach ($data as $value) { $this->writeElement($elementName, $value); } } else { foreach ($data as $value) { $this->writeElementNS($nsPrefix, $elementName, $nsUri, $value); } } return true; }
/* Get a Uint8 array of pixel values: [r, g, b, a, r, g, b, a, ...] Length of the array will be width * height * 4.
function getPixelArray() { var gl = store.get('gl') var w = this._.texture.width; var h = this._.texture.height; var array = new Uint8Array(w * h * 4); this._.texture.drawTo(function() { gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, array); }); return array; }
Marshall the given parameter object.
public void marshall(ListOfferingsRequest listOfferingsRequest, ProtocolMarshaller protocolMarshaller) { if (listOfferingsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(listOfferingsRequest.getChannelClass(), CHANNELCLASS_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getChannelConfiguration(), CHANNELCONFIGURATION_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getCodec(), CODEC_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getMaxResults(), MAXRESULTS_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getMaximumBitrate(), MAXIMUMBITRATE_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getMaximumFramerate(), MAXIMUMFRAMERATE_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getNextToken(), NEXTTOKEN_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getResolution(), RESOLUTION_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getResourceType(), RESOURCETYPE_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getSpecialFeature(), SPECIALFEATURE_BINDING); protocolMarshaller.marshall(listOfferingsRequest.getVideoQuality(), VIDEOQUALITY_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } }
Returns the considered object.
def get_object(self, queryset=None): profile, dummy = ForumProfile.objects.get_or_create(user=self.request.user) return profile
Converts a sequence of indices into their corresponding labels.
def indices_to_labels(self, indices: Sequence[int]) -> List[str]: return [(self.INDEX_TO_LABEL[index]) for index in indices]
// SetDomainName sets the DomainName field's value.
func (s *CertificateDetail) SetDomainName(v string) *CertificateDetail { s.DomainName = &v return s }
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - allow writing per character, auto flush per line
function chars(target, splitExp) { var inst = core.base(); inst.textBuffer = ''; inst.enabled = true; inst.splitExp = (splitExp || /(.*?)\r?\n/g); inst.useTarget = function (target) { inst.target = (target || { // dummy writeln: function () { //nothing } }); }; inst.clear = function () { inst.textBuffer = ''; inst.splitExp.lastIndex = 0; }; inst.write = function (str) { if (str === '') { return; } if (inst.enabled) { //fast path inst.textBuffer += str; inst.flush(true); } }; inst.writeln = function (str) { if (inst.enabled) { //fast path if (arguments.length === 0) { inst.textBuffer += '\n'; } else { inst.textBuffer += str + '\n'; } inst.flush(true); } }; inst.flush = function (linesOnly) { if (inst.textBuffer.length > 0) { var match; var end = 0; //TODO verify if we really need a capture group? // instead not search for line break and use index + length of match + substing while ((match = inst.splitExp.exec(inst.textBuffer))) { inst.target.writeln(match[1]); end = match.index + (match[0].length || 1); inst.splitExp.lastIndex = end; } if (end > 0) { inst.textBuffer = inst.textBuffer.substring(end); inst.splitExp.lastIndex = 0; } if (!linesOnly && inst.textBuffer.length > 0) { inst.target.writeln(inst.textBuffer); inst.textBuffer = 0; inst.splitExp.lastIndex = 0; } } }; inst.has = function () { return inst.textBuffer.length > 0; }; inst.toString = function () { return '<miniwrite-chars>'; }; // use target inst.useTarget(target); return inst; }
Private constructor: create graph from the given Python objects. The constructor examines the referents of each given object to build up a graph showing the objects and their links.
def _from_objects(cls, objects): vertices = ElementTransformSet(transform=id) out_edges = KeyTransformDict(transform=id) in_edges = KeyTransformDict(transform=id) for obj in objects: vertices.add(obj) out_edges[obj] = [] in_edges[obj] = [] # Edges are identified by simple integers, so # we can use plain dictionaries for mapping # edges to their heads and tails. edge_label = itertools.count() edges = set() head = {} tail = {} for referrer in vertices: for referent in gc.get_referents(referrer): if referent not in vertices: continue edge = next(edge_label) edges.add(edge) tail[edge] = referrer head[edge] = referent out_edges[referrer].append(edge) in_edges[referent].append(edge) return cls._raw( vertices=vertices, edges=edges, out_edges=out_edges, in_edges=in_edges, head=head, tail=tail, )
==================================================================================================
public static void main(String[] args) { if (args.length != 2) { System.err.println("Usage: StyleImport <url> <output_file>"); System.exit(0); } try { StyleImport si = new StyleImport(args[0]); FileOutputStream os = new FileOutputStream(args[1]); si.dumpTo(os); os.close(); System.out.println("Done."); } catch (Exception e) { System.err.println("Error: "+e.getMessage()); e.printStackTrace(); } }
Validates sortable list @param SS_List $list @throws Exception
public function validateSortField(SS_List $list) { $field = $this->getSortField(); // Check extra fields on many many relation types if ($list instanceof ManyManyList) { $extra = $list->getExtraFields(); if ($extra && array_key_exists($field, $extra)) { return; } } elseif ($list instanceof ManyManyThroughList) { $manipulator = $this->getManyManyInspector($list); $fieldTable = DataObject::getSchema()->tableForField($manipulator->getJoinClass(), $field); if ($fieldTable) { return; } } $classes = ClassInfo::dataClassesFor($list->dataClass()); foreach ($classes as $class) { if (singleton($class)->hasDataBaseField($field)) { return; } } throw new Exception("Couldn't find the sort field '" . $field . "'"); }
clean the given source from space, comments, etc... @private
function minify(src) { // remove comments src = src.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, "$1"); // Remove leading and trailing whitespace from lines src = src.replace(/(\\n\s+)|(\s+\\n)/g, ""); // Remove line breaks src = src.replace(/(\\r|\\n)+/g, ""); // Remove unnecessary whitespace src = src.replace(/\s*([;,[\](){}\\\/\-+*|^&!=<>?~%])\s*/g, "$1"); return src; }
=========================================================================
public function init() { parent::init(); self::$plugin = $this; $this->setComponents([ 'campaignmonitor' => \clearbold\cmservice\services\CampaignMonitorService::class, ]); Craft::info( Craft::t( 'cm-service', '{name} plugin loaded', ['name' => $this->name] ), __METHOD__ ); }
Internal implementation of adding a single model to the set, updating hash indexes for `id` and `cid` lookups. Returns the model, or 'false' if validation on a new model fails.
function(model, options) { options || (options = {}); model = this._prepareModel(model, options); if (!model) return false; var already = this.getByCid(model) || this.get(model); if (already) throw new Error(["Can't add the same model to a set twice", already.id]); this._byId[model.id] = model; this._byCid[model.cid] = model; var index = options.at != null ? options.at : this.comparator ? this.sortedIndex(model, this.comparator) : this.length; this.models.splice(index, 0, model); model.bind('all', this._onModelEvent); this.length++; if (!options.silent) model.trigger('add', model, this, options); return model; }
--------------------------------------------------------------------------------------------
public static DeploymentEntry create(Map<String, Object> config) { return new DeploymentEntry(ConfigUtil.normalizeYaml(config)); }
// GetSize will return the terminal window size. // // We prefer environ $LINES/$COLUMNS, then fall back to tty-held information. // We do not support use of termcap/terminfo to derive default size information.
func GetSize() (*Size, error) { envSize := GetEnvWindowSize() if envSize != nil && envSize.Lines != 0 && envSize.Columns != 0 { return envSize, nil } fh, err := os.Open("/dev/tty") if err != nil { // no tty, no point continuing; we only let the environ // avoid an error in this case because if someone has faked // up an environ with LINES/COLUMNS _both_ set, we should let // them return nil, err } size, err := GetTerminalWindowSize(fh) if err != nil { if envSize != nil { return envSize, nil } return nil, err } if envSize == nil { return size, err } if envSize.Lines == 0 { envSize.Lines = size.Lines } if envSize.Columns == 0 { envSize.Columns = size.Columns } return envSize, nil }
/* Settings related methods.
@Override protected void createSharedPreferences() { super.createSharedPreferences(); this.sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this); // problem that the first call to getAll() returns nothing, apparently the // following two calls have to be made to read all the values correctly // http://stackoverflow.com/questions/9310479/how-to-iterate-through-all-keys-of-shared-preferences this.sharedPreferences.edit().clear(); PreferenceManager.setDefaultValues(this, R.xml.preferences, true); this.sharedPreferences.registerOnSharedPreferenceChangeListener(this); }
Generate a single module that is produced by accumulating and overriding each module with the next. <pre> {@code Guice.createInjector(ModuleUtils.combineAndOverride(moduleA, moduleAOverrides, moduleB)); } </pre> @param modules @return
public static Module combineAndOverride(List<? extends Module> modules) { Iterator<? extends Module> iter = modules.iterator(); Module current = Modules.EMPTY_MODULE; if (iter.hasNext()) { current = iter.next(); if (iter.hasNext()) { current = Modules.override(current).with(iter.next()); } } return current; }
// Delete removes an item. It doesn't add it to the queue, because // this implementation assumes the consumer only cares about the objects, // not the order in which they were created/added.
func (f *FIFO) Delete(obj interface{}) error { id, err := f.keyFunc(obj) if err != nil { return KeyError{obj, err} } f.lock.Lock() defer f.lock.Unlock() f.populated = true delete(f.items, id) return err }