code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
๏ปฟnamespace Decent.Minecraft.Client.Blocks { /// <summary> /// <a href="http://minecraft.gamepedia.com/Fence">Gamepedia link</a>. /// </summary> public class Fence : IBlock { } }
Petermarcu/minecraft.client
Decent.Minecraft.Client/Blocks/Fence.cs
C#
mit
204
package jsock.enums; /** * Created by czifro on 6/5/15. */ public enum FunctionType { ONLY_NULLS, NON_ASCII, NON_UNICODE }
czifro-development/JSocket
jsocket/src/main/java/jsock/enums/FunctionType.java
Java
mit
138
import sys import pprint class Reference(object): def __init__(self, tb_index, varname, target): self.tb_index = tb_index self.varname = varname self.target = target def marker(self, xtb, tb_index, key): return Marker(self, xtb, tb_index, key) class Marker(object): def __init__(self, reference, xtb, tb_index, key): self.reference = reference self.xtb = xtb self.tb_index = tb_index self.key = key self.tb_offset = self.reference.tb_index - self.tb_index def __repr__(self): frame = sys._getframe(1) while frame: try: code = self.xtb._format_variable.func_code except AttributeError: # python 3 code = self.xtb._format_variable.__code__ if frame.f_code == code: indent = frame.f_locals["indent"] + 4 break frame = frame.f_back else: # pragma: no cover - defensive raise RuntimeError("Expecting to be called with " "XTraceback._format_variable in stack") pretty_repr = pprint.pformat(self.reference.target) if indent + len(self.key) + len(pretty_repr) > self.xtb.print_width \ or pretty_repr.find("\n") > 0: name = "" if self.reference.varname == self.key \ else " name=%s" % self.reference.varname pretty_repr = "<ref offset=%d%s>" % (self.tb_offset, name) return pretty_repr
Hypernode/xtraceback
xtraceback/reference.py
Python
mit
1,552
/******************************************************************************* * This file is part of the Twig eclipse plugin. * * (c) Robert Gruendler <r.gruendler@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. ******************************************************************************/ package com.dubture.twig.ui.editor.configuration; import org.eclipse.php.internal.ui.editor.configuration.PHPStructuredPresentationReconciler; @SuppressWarnings("restriction") public class TwigStructuredPresentationReconciler extends PHPStructuredPresentationReconciler { }
gencer/Twig-Eclipse-Plugin
com.dubture.twig.ui/src/com/dubture/twig/ui/editor/configuration/TwigStructuredPresentationReconciler.java
Java
mit
671
<html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" type="text/css" href="../assets/stylesheets/bootstrap.min.css" /> <link href='http://fonts.googleapis.com/css?family=Share+Tech' rel='stylesheet' type='text/css'> </head> <body class="container"> <br/> <nav class="navbar navbar-default" role="navigation"> <div class="navbar-header"> <a class="navbar-brand" href="#" style='font-family: "Share Tech"; color: #333; font-size: 24px; font-weight: bold;'>Lucie Framework</a> </div> </nav> <div class="row-fluid"> <div class="col-md-4"> <div class="list-group"> <a href="introduction.html" class="list-group-item active">Introduction</a> <a href="installation.html" class="list-group-item ">Installation</a> <a href="commands_helper.html" class="list-group-item ">Commands Helper</a> </div> </div> <div class="col-md-8" style="text-align: justify;"> <h1>Introduction</h1> <ul> <li> <a href="#toc_0">MVC</a> </li> <li> <a href="#toc_1">Directory structure</a> </li> </ul> <p>Lucie is a terminal application development framework written in Ruby. The aim of the framework is to make the terminal application development faster and easier with providing generators, plugins, components. With specifying a common framework, easier to share workflow management solutions among companies worldwide or creating application that doesn&#39;t require graphical user interface.</p> <h3 id="toc_0">MVC</h3> <p>Lucie based on Model, View, Contoller (MVC) design pattern. Using this principle data can be totally separated from business logic and from its representation. Models represent object that need to be permanent, controllers implement business logic and views help in representing models using templates to generate files or output.</p> <p>When a Lucie based application is executed, first it dispatches the request and finds the appropriate controller using the first command line attribute. If a second attribute is also defined, it calls the action on the controller with the same name as the attribute, otherwise it calls the index method. Each other attribute is stored in a <code>params</code> instance variable. Mandatory and optional parameters can be defined in controller if some additional information are required by the action.</p> <p>Controller implements the business logic, using models and templates for data source and representation. Model uses database to store and fetch data.</p> <h3 id="toc_1">Directory structure</h3> <table> <tr><td><code>/app/controllers</code></td><td> Controllers for business logic </td></tr> <tr><td><code>/app/models</code></td><td>Models which store permanent information</td></tr> </table> <p><code>/app/models:</code> Models which store permanent information<br> <code>/app/views: Template files</code><br> <code>/config: Configuration files</code><br> <code>/lib: Libraries for shared resources</code></p> </div> </div> </body> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-39736370-1', 'luc.ie'); ga('send', 'pageview'); </script> </html>
Nucc/luc
guides/public/introduction.html
HTML
mit
3,543
npm install pause
dmsovetov/necromancer.js
install.bat
Batchfile
mit
17
format MS COFF section '.text' code readable executable public _memset _memset: push edi mov edi, [esp+8] mov al, [esp+12] mov ecx, [esp+16] rep stosb pop edi ret
devlato/kolibrios-llvm
programs/other/graph/memset.asm
Assembly
mit
170
local AuthsCache = require 'apicast.policy.3scale_batcher.auths_cache' local Usage = require 'apicast.usage' local Transaction = require 'apicast.policy.3scale_batcher.transaction' local lrucache =require 'resty.lrucache' local storage local cache local usage local service_id = 's1' local auth_status = 200 describe('Auths cache', function() before_each(function() storage = lrucache.new(100) cache = AuthsCache.new(storage) usage = Usage.new() usage:add('m1', 1) end) it('caches auth with user key', function() local user_key = { user_key = 'uk' } local transaction = Transaction.new(service_id, user_key, usage) cache:set(transaction, auth_status) local cached = cache:get(transaction) assert.equals(auth_status, cached.status) end) it('caches auth with app id + app key', function() local app_id_and_key = { app_id = 'an_id', app_key = 'a_key' } local transaction = Transaction.new(service_id, app_id_and_key, usage) cache:set(transaction, auth_status) local cached = cache:get(transaction) assert.equals(auth_status, cached.status) end) it('caches auth with access token', function() local access_token = { access_token = 'a_token' } local transaction = Transaction.new(service_id, access_token, usage) cache:set(transaction, auth_status) local cached = cache:get(transaction) assert.equals(auth_status, cached.status) end) it('caches auths with same usages but different order in the same key', function() local usage_order_1 = Usage.new() usage_order_1:add('m1', 1) usage_order_1:add('m2', 1) local usage_order_2 = Usage.new() usage_order_2:add('m2', 1) usage_order_2:add('m1', 1) local user_key = { user_key = 'uk' } local transaction_with_order_1 = Transaction.new(service_id, user_key, usage_order_1) local transaction_with_order_2 = Transaction.new(service_id, user_key, usage_order_2) cache:set(transaction_with_order_1, auth_status) local cached = cache:get(transaction_with_order_2) assert.equals(auth_status, cached.status) end) it('caches a rejection reason when given', function() local rejection_reason = 'limits_exceeded' local app_id_and_key = { app_id = 'an_id', app_key = 'a_key' } local transaction = Transaction.new(service_id, app_id_and_key, usage) local not_authorized_status = 409 cache:set(transaction, not_authorized_status, rejection_reason) local cached = cache:get(transaction) assert.equals(not_authorized_status, cached.status) assert.equals(rejection_reason, cached.rejection_reason) end) it('returns nil when something is not cached', function() local user_key = { user_key = 'uk' } local transaction = Transaction.new(service_id, user_key, usage) assert.is_nil(cache:get(transaction)) end) end)
3scale/docker-gateway
spec/policy/3scale_batcher/auths_cache_spec.lua
Lua
mit
2,853
# React Table Docs This is source code to react-table.tanstack.com. It is forked from the [Formik](https://formik.org) docs and is built with: - Next.js - MDX - Tailwind - Algolia - Notion ## Running locally ```sh yarn install ``` At the moment, you need to signup for Notion, and [follow these instructions](https://github.com/ijjk/notion-blog#getting-blog-index-and-token) to get a token and create a blog in order to develop locally. Not ideal, but hopefully will fix soon. With tokens and page index in hand, rename `.sample.env` and `.sample.env.build` to just `.env` and `.env.build`. In each one, add respective parameters: ```diff -NOTION_TOKEN=XXXX +NOTION_TOKEN=<YOUR_TOKEN> -BLOG_INDEX_ID=XXXXX +BLOG_INDEX_ID=<YOUR_BLOG_INDEX_ID> ``` Now it will work. Run `yarn dev` to get going. If you get stuck or need help, [send a DM to Jared](https://twitter.com/jaredpalmer) on Twitter.
react-tools/react-table
docs/README.md
Markdown
mit
899
Flask-Multi-Session [![build status](https://travis-ci.org/nbob/flask-multi-session.svg?branch=master)](https://travis-ci.org/nbob/flask-multi-session) [![build status](https://img.shields.io/pypi/l/Flask-Multi-Session.svg)](https://pypi.python.org/pypi/Flask-Multi-Session) ============== __Flask-Multi-Session__ provides __Mongo__ session storage for __Flask__ apps. This module allows you to manage user sessions from different devices, thus you can logout user from all devices. __Flask-Multi-Session__ supports python>=3.5. Installation -------------- Install __Flask-Multi-Session__ from __pip__. `pip3 install flask-multi-session` Usage -------------- ~~~~~~~~~~~~~~ from flask import Flask, session, redirect, url_for import random app = Flask(__name__) @app.route('/') def index(): user_id = session.get('user_id') if user_id is not None: return """ Hello. This is index page. Your login is %s.<\br> <a href="/logout">Logout</a> <a href="/logout_all_devices">Logout from all devices</a> """ % user_id else: return 'Hello. This is index page. Please <a href="/login">login</a>.' @app.route('/login') def login(): session.login(random.randint(1, 10000)) return redirect(url_for('index')) @app.route('/logout') def logout(): session.logout() return redirect(url_for('index')) @app.route('/logout_all_devices') def logout_all_devices(): session.logout_all_devices() return redirect(url_for('index')) from flask_multisession import MongoSessionInterface app.session_interface = MongoSessionInterface() if __name__ == '__main__': app.run() ~~~~~~~~~~~~~~ **Important!** Use "user_id" as a key for unique user id and add one to session after successful login. **Important!** Added new method __clear_user_sessions__ to [Session class](http://flask.pocoo.org/docs/0.10/api/#sessions). Example: `session.clear_user_sessions()` delete all sessions for current user, but you can specify user_id: `session.clear_user_sessions(user_id=23)` delete all sessions for user with id=23. Set Mongo -------------- If you have a remote __Mongo__ you may specify one in __MongoSessionInterface__ constructor. ~~~~~~~~~~~~~~ mongo_config = dict( host='192.168.0.1', port=27017 ) from flask.ext.multisession import MongoSessionInterface app.session_interface = MongoSessionInterface(**mongo_config) ~~~~~~~~~~~~~~
atkin1450/flask-multi-session
README.md
Markdown
mit
2,367
--- title: Margaret Clark submitted: 2017-09-06 gender: female course: - Music graduated: 1977 contact_allowed: true --- Worked as Admin Assistant in touring theatre group in Cumbria called Stage 77 in Autumn 1977. Library Services roles 1978 - 2005. Sang in several local choirs and choral societies up to present day.
johnathan99j/history-project
_people/margaret_clark.md
Markdown
mit
323
require 'jquery-nested-rails/rails'
cisin/jquery-nested-rails-cis
lib/jquery-nested-rails.rb
Ruby
mit
35
<h2>Registration</h2> <?php include_partial('home/notice', array()) ?> <?php include_partial('home/error', array()) ?>
lebedta/christmedia
apps/frontend/modules/registration/templates/registrationProceedSuccess.php
PHP
mit
120
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_TXMEMPOOL_H #define BITCOIN_TXMEMPOOL_H #include <memory> #include <set> #include <map> #include <vector> #include <utility> #include <string> #include "amount.h" #include "coins.h" #include "indirectmap.h" #include "primitives/transaction.h" #include "sync.h" #include "random.h" #undef foreach #include "boost/multi_index_container.hpp" #include "boost/multi_index/ordered_index.hpp" #include "boost/multi_index/hashed_index.hpp" class CAutoFile; class CBlockIndex; inline double AllowFreeThreshold() { return COIN * 144 / 250; } inline bool AllowFree(double dPriority) { // Large (in bytes) low-priority (new, small-coin) transactions // need a fee. return dPriority > AllowFreeThreshold(); } /** Fake height value used in CCoins to signify they are only in the memory pool (since 0.8) */ static const unsigned int MEMPOOL_HEIGHT = 0x7FFFFFFF; struct LockPoints { // Will be set to the blockchain height and median time past // values that would be necessary to satisfy all relative locktime // constraints (BIP68) of this tx given our view of block chain history int height; int64_t time; // As long as the current chain descends from the highest height block // containing one of the inputs used in the calculation, then the cached // values are still valid even after a reorg. CBlockIndex* maxInputBlock; LockPoints() : height(0), time(0), maxInputBlock(NULL) { } }; class CTxMemPool; /** \class CTxMemPoolEntry * * CTxMemPoolEntry stores data about the corresponding transaction, as well * as data about all in-mempool transactions that depend on the transaction * ("descendant" transactions). * * When a new entry is added to the mempool, we update the descendant state * (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for * all ancestors of the newly added transaction. * * If updating the descendant state is skipped, we can mark the entry as * "dirty", and set nSizeWithDescendants/nModFeesWithDescendants to equal nTxSize/ * nFee+feeDelta. (This can potentially happen during a reorg, where we limit the * amount of work we're willing to do to avoid consuming too much CPU.) * */ class CTxMemPoolEntry { private: CTransactionRef tx; CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize()) size_t nModSize; //!< ... and modified size for priority size_t nUsageSize; //!< ... and total memory usage int64_t nTime; //!< Local time when entering the mempool double entryPriority; //!< Priority when entering the mempool unsigned int entryHeight; //!< Chain height when entering the mempool bool hadNoDependencies; //!< Not dependent on any other txs when it entered the mempool CAmount inChainInputValue; //!< Sum of all txin values that are already in blockchain bool spendsCoinbase; //!< keep track of transactions that spend a coinbase int64_t sigOpCost; //!< Total sigop cost int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block LockPoints lockPoints; //!< Track the height and time at which tx was final // Information about descendants of this transaction that are in the // mempool; if we remove this transaction we must remove all of these // descendants as well. if nCountWithDescendants is 0, treat this entry as // dirty, and nSizeWithDescendants and nModFeesWithDescendants will not be // correct. uint64_t nCountWithDescendants; //!< number of descendant transactions uint64_t nSizeWithDescendants; //!< ... and size CAmount nModFeesWithDescendants; //!< ... and total fees (all including us) // Analogous statistics for ancestor transactions uint64_t nCountWithAncestors; uint64_t nSizeWithAncestors; CAmount nModFeesWithAncestors; int64_t nSigOpCostWithAncestors; public: CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee, int64_t _nTime, double _entryPriority, unsigned int _entryHeight, bool poolHasNoInputsOf, CAmount _inChainInputValue, bool spendsCoinbase, int64_t nSigOpsCost, LockPoints lp); CTxMemPoolEntry(const CTxMemPoolEntry& other); const CTransaction& GetTx() const { return *this->tx; } CTransactionRef GetSharedTx() const { return this->tx; } /** * Fast calculation of lower bound of current priority as update * from entry priority. Only inputs that were originally in-chain will age. */ double GetPriority(unsigned int currentHeight) const; const CAmount& GetFee() const { return nFee; } size_t GetTxSize() const; size_t GetTxWeight() const { return nTxWeight; } int64_t GetTime() const { return nTime; } unsigned int GetHeight() const { return entryHeight; } bool WasClearAtEntry() const { return hadNoDependencies; } int64_t GetSigOpCost() const { return sigOpCost; } int64_t GetModifiedFee() const { return nFee + feeDelta; } size_t DynamicMemoryUsage() const { return nUsageSize; } const LockPoints& GetLockPoints() const { return lockPoints; } // Adjusts the descendant state, if this entry is not dirty. void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount); // Adjusts the ancestor state void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int modifySigOps); // Updates the fee delta used for mining priority score, and the // modified fees with descendants. void UpdateFeeDelta(int64_t feeDelta); // Update the LockPoints after a reorg void UpdateLockPoints(const LockPoints& lp); uint64_t GetCountWithDescendants() const { return nCountWithDescendants; } uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; } CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; } bool GetSpendsCoinbase() const { return spendsCoinbase; } uint64_t GetCountWithAncestors() const { return nCountWithAncestors; } uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; } CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; } int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; } mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes }; // Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index. struct update_descendant_state { update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) : modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount) {} void operator() (CTxMemPoolEntry &e) { e.UpdateDescendantState(modifySize, modifyFee, modifyCount); } private: int64_t modifySize; CAmount modifyFee; int64_t modifyCount; }; struct update_ancestor_state { update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) : modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost) {} void operator() (CTxMemPoolEntry &e) { e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); } private: int64_t modifySize; CAmount modifyFee; int64_t modifyCount; int64_t modifySigOpsCost; }; struct update_fee_delta { update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { } void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); } private: int64_t feeDelta; }; struct update_lock_points { update_lock_points(const LockPoints& _lp) : lp(_lp) { } void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); } private: const LockPoints& lp; }; // extracts a TxMemPoolEntry's transaction hash struct mempoolentry_txid { typedef uint256 result_type; result_type operator() (const CTxMemPoolEntry &entry) const { return entry.GetTx().GetHash(); } }; /** \class CompareTxMemPoolEntryByDescendantScore * * Sort an entry by max(score/size of entry's tx, score/size with all descendants). */ class CompareTxMemPoolEntryByDescendantScore { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) { bool fUseADescendants = UseDescendantScore(a); bool fUseBDescendants = UseDescendantScore(b); double aModFee = fUseADescendants ? a.GetModFeesWithDescendants() : a.GetModifiedFee(); double aSize = fUseADescendants ? a.GetSizeWithDescendants() : a.GetTxSize(); double bModFee = fUseBDescendants ? b.GetModFeesWithDescendants() : b.GetModifiedFee(); double bSize = fUseBDescendants ? b.GetSizeWithDescendants() : b.GetTxSize(); // Avoid division by rewriting (a/b > c/d) as (a*d > c*b). double f1 = aModFee * bSize; double f2 = aSize * bModFee; if (f1 == f2) { return a.GetTime() >= b.GetTime(); } return f1 < f2; } // Calculate which score to use for an entry (avoiding division). bool UseDescendantScore(const CTxMemPoolEntry &a) { double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants(); double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize(); return f2 > f1; } }; /** \class CompareTxMemPoolEntryByScore * * Sort by score of entry ((fee+delta)/size) in descending order */ class CompareTxMemPoolEntryByScore { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) { double f1 = (double)a.GetModifiedFee() * b.GetTxSize(); double f2 = (double)b.GetModifiedFee() * a.GetTxSize(); if (f1 == f2) { return b.GetTx().GetHash() < a.GetTx().GetHash(); } return f1 > f2; } }; class CompareTxMemPoolEntryByEntryTime { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) { return a.GetTime() < b.GetTime(); } }; class CompareTxMemPoolEntryByAncestorFee { public: bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) { double aFees = a.GetModFeesWithAncestors(); double aSize = a.GetSizeWithAncestors(); double bFees = b.GetModFeesWithAncestors(); double bSize = b.GetSizeWithAncestors(); // Avoid division by rewriting (a/b > c/d) as (a*d > c*b). double f1 = aFees * bSize; double f2 = aSize * bFees; if (f1 == f2) { return a.GetTx().GetHash() < b.GetTx().GetHash(); } return f1 > f2; } }; // Multi_index tag names struct descendant_score {}; struct entry_time {}; struct mining_score {}; struct ancestor_score {}; class CBlockPolicyEstimator; /** * Information about a mempool transaction. */ struct TxMempoolInfo { /** The transaction itself */ CTransactionRef tx; /** Time the transaction entered the mempool. */ int64_t nTime; /** Feerate of the transaction. */ CFeeRate feeRate; /** The fee delta. */ int64_t nFeeDelta; }; /** * CTxMemPool stores valid-according-to-the-current-best-chain transactions * that may be included in the next block. * * Transactions are added when they are seen on the network (or created by the * local node), but not all transactions seen are added to the pool. For * example, the following new transactions will not be added to the mempool: * - a transaction which doesn't make the mimimum fee requirements. * - a new transaction that double-spends an input of a transaction already in * the pool where the new transaction does not meet the Replace-By-Fee * requirements as defined in BIP 125. * - a non-standard transaction. * * CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping: * * mapTx is a boost::multi_index that sorts the mempool on 4 criteria: * - transaction hash * - feerate [we use max(feerate of tx, feerate of tx with all descendants)] * - time in mempool * - mining score (feerate modified by any fee deltas from PrioritiseTransaction) * * Note: the term "descendant" refers to in-mempool transactions that depend on * this one, while "ancestor" refers to in-mempool transactions that a given * transaction depends on. * * In order for the feerate sort to remain correct, we must update transactions * in the mempool when new descendants arrive. To facilitate this, we track * the set of in-mempool direct parents and direct children in mapLinks. Within * each CTxMemPoolEntry, we track the size and fees of all descendants. * * Usually when a new transaction is added to the mempool, it has no in-mempool * children (because any such children would be an orphan). So in * addUnchecked(), we: * - update a new entry's setMemPoolParents to include all in-mempool parents * - update the new entry's direct parents to include the new tx as a child * - update all ancestors of the transaction to include the new tx's size/fee * * When a transaction is removed from the mempool, we must: * - update all in-mempool parents to not track the tx in setMemPoolChildren * - update all ancestors to not include the tx's size/fees in descendant state * - update all in-mempool children to not include it as a parent * * These happen in UpdateForRemoveFromMempool(). (Note that when removing a * transaction along with its descendants, we must calculate that set of * transactions to be removed before doing the removal, or else the mempool can * be in an inconsistent state where it's impossible to walk the ancestors of * a transaction.) * * In the event of a reorg, the assumption that a newly added tx has no * in-mempool children is false. In particular, the mempool is in an * inconsistent state while new transactions are being added, because there may * be descendant transactions of a tx coming from a disconnected block that are * unreachable from just looking at transactions in the mempool (the linking * transactions may also be in the disconnected block, waiting to be added). * Because of this, there's not much benefit in trying to search for in-mempool * children in addUnchecked(). Instead, in the special case of transactions * being added from a disconnected block, we require the caller to clean up the * state, to account for in-mempool, out-of-block descendants for all the * in-block transactions by calling UpdateTransactionsFromBlock(). Note that * until this is called, the mempool state is not consistent, and in particular * mapLinks may not be correct (and therefore functions like * CalculateMemPoolAncestors() and CalculateDescendants() that rely * on them to walk the mempool are not generally safe to use). * * Computational limits: * * Updating all in-mempool ancestors of a newly added transaction can be slow, * if no bound exists on how many in-mempool ancestors there may be. * CalculateMemPoolAncestors() takes configurable limits that are designed to * prevent these calculations from being too CPU intensive. * * Adding transactions from a disconnected block can be very time consuming, * because we don't have a way to limit the number of in-mempool descendants. * To bound CPU processing, we limit the amount of work we're willing to do * to properly update the descendant information for a tx being added from * a disconnected block. If we would exceed the limit, then we instead mark * the entry as "dirty", and set the feerate for sorting purposes to be equal * the feerate of the transaction without any descendants. * */ class CTxMemPool { private: uint32_t nCheckFrequency; //!< Value n means that n times in 2^32 we check. unsigned int nTransactionsUpdated; CBlockPolicyEstimator* minerPolicyEstimator; uint64_t totalTxSize; //!< sum of all mempool tx' byte sizes uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves) CFeeRate minReasonableRelayFee; mutable int64_t lastRollingFeeUpdate; mutable bool blockSinceLastRollingFeeBump; mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially void trackPackageRemoved(const CFeeRate& rate); public: static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing typedef boost::multi_index_container< CTxMemPoolEntry, boost::multi_index::indexed_by< // sorted by txid boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>, // sorted by fee rate boost::multi_index::ordered_non_unique< boost::multi_index::tag<descendant_score>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByDescendantScore >, // sorted by entry time boost::multi_index::ordered_non_unique< boost::multi_index::tag<entry_time>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByEntryTime >, // sorted by score (for mining prioritization) boost::multi_index::ordered_unique< boost::multi_index::tag<mining_score>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByScore >, // sorted by fee rate with ancestors boost::multi_index::ordered_non_unique< boost::multi_index::tag<ancestor_score>, boost::multi_index::identity<CTxMemPoolEntry>, CompareTxMemPoolEntryByAncestorFee > > > indexed_transaction_set; mutable CCriticalSection cs; indexed_transaction_set mapTx; typedef indexed_transaction_set::nth_index<0>::type::iterator txiter; std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order struct CompareIteratorByHash { bool operator()(const txiter &a, const txiter &b) const { return a->GetTx().GetHash() < b->GetTx().GetHash(); } }; typedef std::set<txiter, CompareIteratorByHash> setEntries; const setEntries & GetMemPoolParents(txiter entry) const; const setEntries & GetMemPoolChildren(txiter entry) const; private: typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap; struct TxLinks { setEntries parents; setEntries children; }; typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap; txlinksMap mapLinks; void UpdateParent(txiter entry, txiter parent, bool add); void UpdateChild(txiter entry, txiter child, bool add); std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const; public: indirectmap<COutPoint, const CTransaction*> mapNextTx; std::map<uint256, std::pair<double, CAmount> > mapDeltas; /** Create a new CTxMemPool. * minReasonableRelayFee should be a feerate which is, roughly, somewhere * around what it "costs" to relay a transaction around the network and * below which we would reasonably say a transaction has 0-effective-fee. */ CTxMemPool(const CFeeRate& _minReasonableRelayFee); ~CTxMemPool(); /** * If sanity-checking is turned on, check makes sure the pool is * consistent (does not contain two transactions that spend the same inputs, * all inputs are in the mapNextTx array). If sanity-checking is turned off, * check does nothing. */ void check(const CCoinsViewCache *pcoins) const; void setSanityCheck(double dFrequency = 1.0) { nCheckFrequency = dFrequency * 4294967295.0; } // addUnchecked must updated state for all ancestors of a given transaction, // to track size/count of descendant transactions. First version of // addUnchecked can be used to have it call CalculateMemPoolAncestors(), and // then invoke the second version. bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, bool fCurrentEstimate = true); bool addUnchecked(const uint256& hash, const CTxMemPoolEntry &entry, setEntries &setAncestors, bool fCurrentEstimate = true); void removeRecursive(const CTransaction &tx); void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags); void removeConflicts(const CTransaction &tx); void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight, bool fCurrentEstimate = true); void clear(); void _clear(); //lock free bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb); void queryHashes(std::vector<uint256>& vtxid); void pruneSpent(const uint256& hash, CCoins &coins); unsigned int GetTransactionsUpdated() const; void AddTransactionsUpdated(unsigned int n); /** * Check that none of this transactions inputs are in the mempool, and thus * the tx is not dependent on other mempool transactions to be included in a block. */ bool HasNoInputsOf(const CTransaction& tx) const; /** Affect CreateNewBlock prioritisation of transactions */ void PrioritiseTransaction(const uint256 hash, const std::string strHash, double dPriorityDelta, const CAmount& nFeeDelta); void ApplyDeltas(const uint256 hash, double &dPriorityDelta, CAmount &nFeeDelta) const; void ClearPrioritisation(const uint256 hash); public: /** Remove a set of transactions from the mempool. * If a transaction is in this set, then all in-mempool descendants must * also be in the set, unless this transaction is being removed for being * in a block. * Set updateDescendants to true when removing a tx that was in a block, so * that any in-mempool descendants have their ancestor state updated. */ void RemoveStaged(setEntries &stage, bool updateDescendants); /** When adding transactions from a disconnected block back to the mempool, * new mempool entries may have children in the mempool (which is generally * not the case when otherwise adding transactions). * UpdateTransactionsFromBlock() will find child transactions and update the * descendant state for each transaction in hashesToUpdate (excluding any * child transactions present in hashesToUpdate, which are already accounted * for). Note: hashesToUpdate should be the set of transactions from the * disconnected block that have been accepted back into the mempool. */ void UpdateTransactionsFromBlock(const std::vector<uint256> &hashesToUpdate); /** Try to calculate all in-mempool ancestors of entry. * (these are all calculated including the tx itself) * limitAncestorCount = max number of ancestors * limitAncestorSize = max size of ancestors * limitDescendantCount = max number of descendants any ancestor can have * limitDescendantSize = max size of descendants any ancestor can have * errString = populated with error reason if any limits are hit * fSearchForParents = whether to search a tx's vin for in-mempool parents, or * look up parents from mapLinks. Must be true for entries not in the mempool */ bool CalculateMemPoolAncestors(const CTxMemPoolEntry &entry, setEntries &setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string &errString, bool fSearchForParents = true) const; /** Populate setDescendants with all in-mempool descendants of hash. * Assumes that setDescendants includes all in-mempool descendants of anything * already in it. */ void CalculateDescendants(txiter it, setEntries &setDescendants); /** The minimum fee to get into the mempool, which may itself not be enough * for larger-sized transactions. * The minReasonableRelayFee constructor arg is used to bound the time it * takes the fee rate to go back down all the way to 0. When the feerate * would otherwise be half of this, it is set to 0 instead. */ CFeeRate GetMinFee(size_t sizelimit) const; /** Remove transactions from the mempool until its dynamic size is <= sizelimit. * pvNoSpendsRemaining, if set, will be populated with the list of transactions * which are not in mempool which no longer have any spends in this mempool. */ void TrimToSize(size_t sizelimit, std::vector<uint256>* pvNoSpendsRemaining=NULL); /** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */ int Expire(int64_t time); /** Returns false if the transaction is in the mempool and not within the chain limit specified. */ bool TransactionWithinChainLimit(const uint256& txid, size_t chainLimit) const; unsigned long size() { LOCK(cs); return mapTx.size(); } uint64_t GetTotalTxSize() { LOCK(cs); return totalTxSize; } bool exists(uint256 hash) const { LOCK(cs); return (mapTx.count(hash) != 0); } CTransactionRef get(const uint256& hash) const; TxMempoolInfo info(const uint256& hash) const; std::vector<TxMempoolInfo> infoAll() const; /** Estimate fee rate needed to get into the next nBlocks * If no answer can be given at nBlocks, return an estimate * at the lowest number of blocks where one can be given */ CFeeRate estimateSmartFee(int nBlocks, int *answerFoundAtBlocks = NULL) const; /** Estimate fee rate needed to get into the next nBlocks */ CFeeRate estimateFee(int nBlocks) const; /** Estimate priority needed to get into the next nBlocks * If no answer can be given at nBlocks, return an estimate * at the lowest number of blocks where one can be given */ double estimateSmartPriority(int nBlocks, int *answerFoundAtBlocks = NULL) const; /** Estimate priority needed to get into the next nBlocks */ double estimatePriority(int nBlocks) const; /** Write/Read estimates to disk */ bool WriteFeeEstimates(CAutoFile& fileout) const; bool ReadFeeEstimates(CAutoFile& filein); size_t DynamicMemoryUsage() const; private: /** UpdateForDescendants is used by UpdateTransactionsFromBlock to update * the descendants for a single transaction that has been added to the * mempool but may have child transactions in the mempool, eg during a * chain reorg. setExclude is the set of descendant transactions in the * mempool that must not be accounted for (because any descendants in * setExclude were added to the mempool after the transaction being * updated and hence their state is already reflected in the parent * state). * * cachedDescendants will be updated with the descendants of the transaction * being updated, so that future invocations don't need to walk the * same transaction again, if encountered in another transaction chain. */ void UpdateForDescendants(txiter updateIt, cacheMap &cachedDescendants, const std::set<uint256> &setExclude); /** Update ancestors of hash to add/remove it as a descendant transaction. */ void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors); /** Set ancestor state for an entry */ void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors); /** For each transaction being removed, update ancestors and any direct children. * If updateDescendants is true, then also update in-mempool descendants' * ancestor state. */ void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants); /** Sever link between specified transaction and direct children. */ void UpdateChildrenForRemoval(txiter entry); /** Before calling removeUnchecked for a given transaction, * UpdateForRemoveFromMempool must be called on the entire (dependent) set * of transactions being removed at the same time. We use each * CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a * given transaction that is removed, so we can't remove intermediate * transactions in a chain before we've updated all the state for the * removal. */ void removeUnchecked(txiter entry); }; /** * CCoinsView that brings transactions from a memorypool into view. * It does not check for spendings by memory pool transactions. */ class CCoinsViewMemPool : public CCoinsViewBacked { protected: const CTxMemPool& mempool; public: CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn); bool GetCoins(const uint256 &txid, CCoins &coins) const; bool HaveCoins(const uint256 &txid) const; }; // We want to sort transactions by coin age priority typedef std::pair<double, CTxMemPool::txiter> TxCoinAgePriority; struct TxCoinAgePriorityCompare { bool operator()(const TxCoinAgePriority& a, const TxCoinAgePriority& b) { if (a.first == b.first) return CompareTxMemPoolEntryByScore()(*(b.second), *(a.second)); //Reverse order to make sort less than return a.first < b.first; } }; #endif // BITCOIN_TXMEMPOOL_H
ahmedbodi/temp_vert
src/txmempool.h
C
mit
29,791
# -*- coding: utf-8 -*- """ This scripts sets an initial layout for the ProEMOnline software. It uses the PyQtGraph dockarea system and was designed from the dockarea.py example. Contains: Left column: Observing Log Center column: Plots Right column: Images and Process Log Menu bar """ import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui import pyqtgraph.console import numpy as np import math import astropy.io.fits as fits from pyqtgraph.dockarea import * #This program operates in four stages. #Stage 0 - Program Initialized, waiting to open SPE file. #Stage 1 - SPE file open, stars are being selected #Stage 2 - Online data reduction and aperture photometry/plotting is done. #Stage 3 - End of data acquisition detected. Final data written to file. Timestamps verified. Log saved. Weather/time log data saved. # -> revert back to Stage 0. stage=0 #start at 0 #Keep track of the current frame: #One version that we do science on #One version for display purposes def newframe(fitsfile): """For given filename, return science and display images. """ img = fits.getdata(fitsfile)[0] displayimg = np.copy(img) #replace everything above 99%tile #don't do calulcations on this adjusted array!!! imgvals = displayimg.flatten() img99percentile = np.percentile(imgvals,99) displayimg[displayimg > img99percentile] = img99percentile #make color displayimg=np.array([displayimg,displayimg,displayimg]).transpose() return img,displayimg #Start with some initial example file fitsfile = 'ProEMExample.fits' #initial file img,displayimg = newframe(fitsfile) #Use a function to display a new image #Autoscaling levels optional def displayframe(displayimg,autoscale=False): """Display an RBG image Autoscale optional. Return nothing. """ if autoscale: w5.setImage(displayimg,autoRange=True,levels=[np.min(displayimg),np.max(displayimg)-1]) else: w5.setImage(displayimg,autoRange=False,autoLevels=False) #Set up a list to keep track of star positions starpos=[] #Open File functionality class WithMenu(QtGui.QMainWindow): def __init__(self): super(WithMenu, self).__init__() self.initUI() def initUI(self): #Note: Exit is protected on Mac. This may work on Windows. exitAction = QtGui.QAction('Exit', self) exitAction.setShortcut('Ctrl+Q') exitAction.setStatusTip('Exit application') exitAction.triggered.connect(self.showDialog) openFile = QtGui.QAction('Open', self) openFile.setShortcut('Ctrl+O') openFile.setStatusTip('Open new File') openFile.triggered.connect(self.showDialog) menubar = self.menuBar() fileMenu = menubar.addMenu('File') fileMenu.addAction(openFile) fileMenu.addAction(exitAction) def showDialog(self): fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home') #print str(fname) img = fits.getdata(str(fname))[0] w5.setImage(img) def closeEvent(self, event): reply = QtGui.QMessageBox.question(self, 'Message', "Really quit?", QtGui.QMessageBox.Yes | QtGui.QMessageBox.No, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() else: event.ignore() app = QtGui.QApplication([]) win = WithMenu() area = DockArea() win.setCentralWidget(area) win.resize(1200,600) win.setWindowTitle('ProEM Online Data Analysis Demo') ## Create docks, place them into the window one at a time. ## Note that size arguments are only a suggestion; docks will still have to ## fill the entire dock area and obey the limits of their internal widgets. d1 = Dock("Dock1 - Observing Log", size=(500,300)) d2 = Dock("Dock2 - Process Log", size=(500,300)) d3 = Dock("Dock3 - Fourier Transform", size=(500,400)) d4 = Dock("Dock4 (tabbed) - Smoothed", size=(500,200)) d5 = Dock("Dock5 - Image", size=(500,200)) d6 = Dock("Dock6 (tabbed) - Light Curve", size=(500,200)) d7 = Dock("Dock7 (tabbed) - Comparison Counts", size=(500,200)) d8 = Dock("Dock8 (tabbed) - Seeing", size=(500,200)) area.addDock(d1, 'left') ## place d1 at left edge of dock area (it will fill the whole space since there are no other docks yet) area.addDock(d2, 'right') ## place d2 at right edge of dock area area.addDock(d3, 'left', d2)## place d3 at the left edge of d2 area.addDock(d4, 'top',d3) ## place d4 on top d3 area.addDock(d5, 'top',d2) ## place d5 on top d2 area.addDock(d6, 'above', d4) ## place d6 above d4 area.addDock(d7, 'top', d3) area.addDock(d8, 'above', d7) ## Add widgets into each dock ## First dock holds the Observing Log w1 = pg.LayoutWidget() observer = QtGui.QLabel('Observer') target = QtGui.QLabel('Target') filt = QtGui.QLabel('Filter') log = QtGui.QLabel('Log') observerEdit = QtGui.QLineEdit() targetEdit = QtGui.QLineEdit() filtEdit = QtGui.QComboBox() filtEdit.addItems(["BG40","u'","g'","r'","i'","z'","Other"]) logEdit = QtGui.QTextEdit() w1.addWidget(observer, 1, 0) w1.addWidget(observerEdit, 1, 1) w1.addWidget(target, 2, 0) w1.addWidget(targetEdit, 2, 1) w1.addWidget(filt, 3, 0) w1.addWidget(filtEdit, 3, 1) w1.addWidget(log, 4, 0) w1.addWidget(logEdit, 4, 1, 6, 1) d1.addWidget(w1) ## Process Log w2 = pg.LayoutWidget() processLog = QtGui.QTextEdit() processLog.setReadOnly(True) #processLog.setTextBackgroundColor(QtGui.QColor("black")) w2.addWidget(processLog, 0, 0, 6, 1) d2.addWidget(w2) ## Fourier Transform - Just shows random updating noise for now w3 = pg.PlotWidget(title="Fourier Transform") curve = w3.plot(pen='y') data = np.random.normal(size=(10,1000)) ptr = 0 def update(): global curve, data, ptr, w3 curve.setData(data[ptr%10]) if ptr == 0: w3.enableAutoRange('xy', False) ## stop auto-scaling after the first data set is plotted ptr += 1 timer = QtCore.QTimer() timer.timeout.connect(update) timer.start(50) d3.addWidget(w3) ## Smoothed Light Curve w4 = pg.PlotWidget(title="Dock 4 plot") w4.plot(np.random.normal(size=100)) d4.addWidget(w4) ## Image w5 = pg.ImageView() w5.ui.roiBtn.hide() w5.ui.normBtn.hide() displayframe(displayimg,autoscale=True) def click(event): event.accept() pos = event.pos() #check if we're marking or unmarking a star #if pos. starpos.append([pos.x(),pos.y()]) #img[pos.x(),pos.y()]=[255,255-img[pos.x(),pos.y(),1],255-img[pos.x(),pos.y(),1]] #w5.setImage(img,autoRange=False) processLog.append("Star selected at "+str( (int(pos.x()),int(pos.y())) )) w5.getImageItem().mouseClickEvent = click d5.addWidget(w5) ## Light Curve w6 = pg.PlotWidget(title="Dock 6 plot") w6.plot(np.random.normal(size=100)) d6.addWidget(w6) ## Smoothed Light Curve w7 = pg.PlotWidget(title="Dock 7 plot") w7.plot(np.random.normal(size=100)) d7.addWidget(w7) ## Smoothed Light Curve w8 = pg.PlotWidget(title="Dock 8 plot") w8.plot(np.random.normal(size=100)) d8.addWidget(w8) win.show() ## Start Qt event loop unless running in interactive mode or using pyside. if __name__ == '__main__': import sys if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
ccd-utexas/ProEMOnline
layout.py
Python
mit
7,341
module Fog module Concerto class Compute class Mock def get_ssh_profile(id) Fog::Mock.not_implemented end end class Real def get_ssh_profile(id) request(path: "cloud/ssh_profiles/#{id}", expects: [200]) end end end end end
flexiant/fog-concerto
lib/fog-concerto/requests/compute/get_ssh_profile.rb
Ruby
mit
311
<?php namespace RybakDigital\Bundle\UserBundle\Tests\Entity\Traits; use \PHPUnit_Framework_TestCase as TestCase; use RybakDigital\Bundle\UserBundle\Entity\Traits\UserOrganisationRole; use RybakDigital\Bundle\UserBundle\Entity\Role; use RybakDigital\Bundle\UserBundle\Entity\User; use RybakDigital\Bundle\UserBundle\Entity\Organisation; use RybakDigital\Bundle\UserBundle\Entity\UserOrganisationRole as Uor; class UserOrganisationRoleTest extends TestCase { public function addUorProvider() { $data = array( array(new Role(), new Uor()), array(new User(), new Uor()), array(new Organisation(), new Uor()), ); return $data; } /** * @dataProvider addUorProvider */ public function testRemoveUor($parent, $uor) { $this->assertTrue(is_a($parent->removeUor($uor), get_class($parent))); $this->assertFalse($parent->getUors()->contains($uor)); } }
rybakdigital/UserBundle
Tests/Entity/Triats/UserOrganisationRoleTest.php
PHP
mit
959
<?php declare(strict_types=1); namespace BEAR\QueryRepository; use BEAR\Resource\ResourceObject; final class NullCacheControlHeaderSetter implements CdnCacheControlHeaderSetterInterface { public function __invoke(ResourceObject $ro, ?int $sMaxAge): void { } }
koriym/BEAR.QueryRepository
src/NullCacheControlHeaderSetter.php
PHP
mit
276
<?php header('Content-Type: application/xml; charset=utf-8'); // Necessary to do โ€œrealโ€ XHTML. ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>An XHTML 1.0 Strict standard template</title> </head> <body> <textarea /> <p><a href="xhtml.php">Load via instantclick.</a></p> <p>Hovering over the link gives an error. This XHTML business is <a href="https://github.com/dieulot/instantclick/issues/52">madness</a>, so this wonโ€™t get fixed.</p> <script src="instantclick.js.php" data-no-instant=""></script> <script data-no-instant="">InstantClick.init()</script> </body> </html>
nishant8BITS/instantclick
tests/xhtml.php
PHP
mit
743
'use strict'; describe('Service: Location', function () { // load the service's module beforeEach(module('treasuremapApp')); // instantiate service var Location; beforeEach(inject(function (_Location_) { Location = _Location_; })); it('should do something', function () { expect(!!Location).toBe(true); }); });
comvidnet/treasure-map-web
client/services/location/location.service.spec.js
JavaScript
mit
340
import _plotly_utils.basevalidators class PadValidator(_plotly_utils.basevalidators.CompoundValidator): def __init__(self, plotly_name="pad", parent_name="layout.title", **kwargs): super(PadValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, data_class_str=kwargs.pop("data_class_str", "Pad"), data_docs=kwargs.pop( "data_docs", """ b The amount of padding (in px) along the bottom of the component. l The amount of padding (in px) on the left side of the component. r The amount of padding (in px) on the right side of the component. t The amount of padding (in px) along the top of the component. """, ), **kwargs )
plotly/python-api
packages/python/plotly/plotly/validators/layout/title/_pad.py
Python
mit
945
void DynamicProgrammingQ2(double *Q1, double *T1, double *Q2, double *T2, int m1, int n1, int n2, double *tv1, double *tv2, int n1v, int n2v, double *G, double *T, double *size, double lam1);
JuliaPackageMirrors/ElasticFDA.jl
deps/src/fdasrsf/DynamicProgrammingQ2.h
C
mit
270
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using Umbraco.Core.Models; using Umbraco.Core.Models.Rdbms; using Umbraco.Tests.TestHelpers; namespace Umbraco.Tests.Services { /// <summary> /// Tests covering the DataTypeService /// </summary> [DatabaseTestBehavior(DatabaseBehavior.NewDbFileAndSchemaPerTest)] [TestFixture, RequiresSTA] public class DataTypeServiceTests : BaseServiceTest { [SetUp] public override void Initialize() { base.Initialize(); } [TearDown] public override void TearDown() { base.TearDown(); } [Test] public void DataTypeService_Can_Persist_New_DataTypeDefinition() { // Arrange var dataTypeService = ServiceContext.DataTypeService; // Act var dataTypeDefinition = new DataTypeDefinition(-1, "Test.TestEditor") { Name = "Testing Textfield", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.Save(dataTypeDefinition); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); Assert.That(dataTypeDefinition.HasIdentity, Is.True); } [Test] public void DataTypeService_Can_Delete_Textfield_DataType_And_Clear_Usages() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = "Umbraco.Textbox"; var dataTypeDefinitions = dataTypeService.GetDataTypeDefinitionByPropertyEditorAlias(textfieldId); // Act var definition = dataTypeDefinitions.First(); var definitionId = definition.Id; dataTypeService.Delete(definition); var deletedDefinition = dataTypeService.GetDataTypeDefinitionById(definitionId); // Assert Assert.That(deletedDefinition, Is.Null); //Further assertions against the ContentType that contains PropertyTypes based on the TextField var contentType = ServiceContext.ContentTypeService.GetContentType(NodeDto.NodeIdSeed); Assert.That(contentType.Alias, Is.EqualTo("umbTextpage")); Assert.That(contentType.PropertyTypes.Count(), Is.EqualTo(1)); } [Test] public void DataTypeService_Can_Persist_Dictionary_Based_Pre_Values() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea"); // Act IDataTypeDefinition dataTypeDefinition = new DataTypeDefinition(-1, textfieldId) { Name = "Testing prevals", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.Save(dataTypeDefinition); dataTypeService.SavePreValues(dataTypeDefinition, new Dictionary<string, PreValue> { {"preVal1", new PreValue("Hello")}, {"preVal2", new PreValue("World")} }); //re-get dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(dataTypeDefinition.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); Assert.That(dataTypeDefinition.HasIdentity, Is.True); Assert.AreEqual(true, preVals.IsDictionaryBased); Assert.AreEqual(2, preVals.PreValuesAsDictionary.Keys.Count); Assert.AreEqual("preVal1", preVals.PreValuesAsDictionary.Keys.First()); Assert.AreEqual("preVal2", preVals.PreValuesAsDictionary.Keys.Last()); Assert.AreEqual("Hello", preVals.PreValuesAsDictionary["preVal1"].Value); Assert.AreEqual("World", preVals.PreValuesAsDictionary["preVal2"].Value); } [Test] public void DataTypeService_Can_Persist_Dtd_And_Dictionary_Based_Pre_Values() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea"); // Act IDataTypeDefinition dataTypeDefinition = new DataTypeDefinition(-1, textfieldId) { Name = "Testing prevals", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.SaveDataTypeAndPreValues(dataTypeDefinition, new Dictionary<string, PreValue> { {"preVal1", new PreValue("Hello")}, {"preVal2", new PreValue("World")} }); //re-get dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(dataTypeDefinition.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); Assert.That(dataTypeDefinition.HasIdentity, Is.True); Assert.AreEqual(true, preVals.IsDictionaryBased); Assert.AreEqual(2, preVals.PreValuesAsDictionary.Keys.Count); Assert.AreEqual("preVal1", preVals.PreValuesAsDictionary.Keys.First()); Assert.AreEqual("preVal2", preVals.PreValuesAsDictionary.Keys.Last()); Assert.AreEqual("Hello", preVals.PreValuesAsDictionary["preVal1"].Value); Assert.AreEqual("World", preVals.PreValuesAsDictionary["preVal2"].Value); } [Test] public void DataTypeService_Can_Update_Pre_Values() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea"); // Act IDataTypeDefinition dataTypeDefinition = new DataTypeDefinition(-1, textfieldId) { Name = "Testing prevals", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.SaveDataTypeAndPreValues(dataTypeDefinition, new Dictionary<string, PreValue> { {"preVal1", new PreValue("Hello")}, {"preVal2", new PreValue("World")} }); //re-get dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(dataTypeDefinition.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); //update them (ensure Ids are there!) var asDictionary = preVals.FormatAsDictionary(); asDictionary["preVal1"].Value = "Hello2"; asDictionary["preVal2"].Value = "World2"; dataTypeService.SavePreValues(dataTypeDefinition, asDictionary); var preValsAgain = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); // Assert Assert.AreEqual(preVals.PreValuesAsDictionary.Values.First().Id, preValsAgain.PreValuesAsDictionary.Values.First().Id); Assert.AreEqual(preVals.PreValuesAsDictionary.Values.Last().Id, preValsAgain.PreValuesAsDictionary.Values.Last().Id); Assert.AreEqual("preVal1", preValsAgain.PreValuesAsDictionary.Keys.First()); Assert.AreEqual("preVal2", preValsAgain.PreValuesAsDictionary.Keys.Last()); Assert.AreEqual("Hello2", preValsAgain.PreValuesAsDictionary["preVal1"].Value); Assert.AreEqual("World2", preValsAgain.PreValuesAsDictionary["preVal2"].Value); } [Test] public void DataTypeService_Can_Remove_Pre_Value() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea"); // Act IDataTypeDefinition dataTypeDefinition = new DataTypeDefinition(-1, textfieldId) { Name = "Testing prevals", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.SaveDataTypeAndPreValues(dataTypeDefinition, new Dictionary<string, PreValue> { {"preVal1", new PreValue("Hello")}, {"preVal2", new PreValue("World")} }); //re-get dataTypeDefinition = dataTypeService.GetDataTypeDefinitionById(dataTypeDefinition.Id); var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); //update them (ensure Ids are there!) var asDictionary = preVals.FormatAsDictionary(); asDictionary.Remove("preVal2"); dataTypeService.SavePreValues(dataTypeDefinition, asDictionary); var preValsAgain = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); // Assert Assert.AreEqual(1, preValsAgain.FormatAsDictionary().Count); Assert.AreEqual(preVals.PreValuesAsDictionary.Values.First().Id, preValsAgain.PreValuesAsDictionary.Values.First().Id); Assert.AreEqual("preVal1", preValsAgain.PreValuesAsDictionary.Keys.First()); } [Test] public void DataTypeService_Can_Persist_Array_Based_Pre_Values() { // Arrange var dataTypeService = ServiceContext.DataTypeService; var textfieldId = new Guid("ec15c1e5-9d90-422a-aa52-4f7622c63bea"); // Act IDataTypeDefinition dataTypeDefinition = new DataTypeDefinition(-1, textfieldId) { Name = "Testing prevals", DatabaseType = DataTypeDatabaseType.Ntext }; dataTypeService.Save(dataTypeDefinition); dataTypeService.SavePreValues(dataTypeDefinition.Id, new[] {"preVal1", "preVal2"}); //re-get var preVals = dataTypeService.GetPreValuesCollectionByDataTypeId(dataTypeDefinition.Id); // Assert Assert.That(dataTypeDefinition, Is.Not.Null); Assert.That(dataTypeDefinition.HasIdentity, Is.True); Assert.AreEqual(false, preVals.IsDictionaryBased); Assert.AreEqual(2, preVals.PreValuesAsArray.Count()); Assert.AreEqual("preVal1", preVals.PreValuesAsArray.First().Value); Assert.AreEqual("preVal2", preVals.PreValuesAsArray.Last().Value); } [Test] public void Cannot_Save_DataType_With_Empty_Name() { // Arrange var dataTypeService = ServiceContext.DataTypeService; // Act var dataTypeDefinition = new DataTypeDefinition(-1, "Test.TestEditor") { Name = string.Empty, DatabaseType = DataTypeDatabaseType.Ntext }; // Act & Assert Assert.Throws<ArgumentException>(() => dataTypeService.Save(dataTypeDefinition)); } } }
gavinfaux/Umbraco-CMS
src/Umbraco.Tests/Services/DataTypeServiceTests.cs
C#
mit
11,042
<?php namespace Vda\Query\Key; class OneToOne extends OneToN { }
dmitry027/query
src/Key/OneToOne.php
PHP
mit
66
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /** * */ class Bootstrap_system { function ui_topbar(){ $html = ' <nav class="navbar navbar-fixed-top"> <div class="container-fluid inverse {_themes}"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false"> <span><i class="fa fa-th-large"></i> Menu</span> </button> <a class="navbar-brand navbar-button"><i class="fa fa-th-large"></i></a> <a class="navbar-brand" href="#">{_site_title}</a> </div> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav inverse"> {_searching_bar} </ul> <ul class="nav navbar-nav navbar-right inverse"> {_nav_topbar} <li> <a {href} class="item"><i class="{icon}"></i>&nbsp;{label}</a> </li> {/_nav_topbar} </ul> </div> </div> </nav> '; return $html; } function ui_sidebar(){ $html = ' <ul class="nav nav-sidebar inverse {_themes}" id="sidebar"> <li> <form action="'.site_url('cpanel/switch_ux').'"> <div class="input-group"> <span class="input-group-addon">Change UI</span> <select name="interface" class="input-control"> <option value="1">Semantic UI</option> <option value="2">Bootstrap</option> </select> </div> </form> </li> <li> <a href="'.site_url('cpanel').'"><i class="fa fa-dashboard"></i>&nbsp;Dashboard</a> </li> {_sidebar_menu} <li> {menus} </li> {/_sidebar_menu} </ul> '; return $html; } // ------------------------------------------------------------------------------------------------------------------------- // MEMBUAT NAVIGATION MENU // bentuk array // array( // "class"=>"", // "ui_menu"=>array( // array("menu_link"=>"","menu_class"=>"", "menu_icon"=>"","menu_title"=>"","menu_extra"=>"") // ) // ) // ------------------------------------------------------------------------------------------------------------------------- function ui_menu(){ $menus = '<div class="ui {class} menu">'; $menus .= '{ui_menu}'; $menus .= '<a {menu_link} class="item{menu_class}"{menu_extra}><i class="{menu_icon}"></i>&nbsp;{menu_title}</a>'; $menus .= '{/ui_menu}'; $menus .= '</div>'; return $menus; } // ------------------------------------------------------------------------------------------------------------------------- // MEMBUAT MENU LIST // bentuk array // array( // "class"=>"", // "ui_list"=>array( // array("list_link"=>"","list_class"=>"","list_title"=>"","list_extra"=>"") // ) // ) // ------------------------------------------------------------------------------------------------------------------------- function ui_list(){ $list = '<div class="ui {class} list">'; $list .= '{ui_list}'; $list .= '<a {list_link} class="item {list_class}" {list_extra}>{list_title}</a>'; $list .= '{/ui_list}'; $list .= '</div>'; return $list; } // ------------------------------------------------------------------------------------------------------------------------- // MEMBUAT UI DROPDOWN // bentuk array // array( // "class"=>"", // "extra"=>"", // "default_text"=>"", // "dropdown_list"=>array( // array("option"=>"","label"=>"","extra"=>"") // ) // ) // ------------------------------------------------------------------------------------------------------------------------- function ui_dropdown(){ $list = '<div class="ui {class} dropdown" {extra}>'; $list .= '<i class="dropdown icon"></i>'; $list .= '<span class="default text">{default_text}</span>'; $list .= '<div class="menu">'; $list .= '{dropdown_list}'; $list .= '<div class="item" data-option="{option}" {extra}>{label}</div>'; $list .= '{/dropdown_list}'; $list .= '</div>'; $list .= '</div>'; return $list; } function ui_field(){ $input = '<div class="field">'; $input .= '</div>'; } // ------------------------------------------------------------------------------------------------------------------------- // MEMBUAT UI CARD // bentuk array // array( // "class"=>"", // "card_list"=>array( // array("image_url"=>"","content_header"=>"","content_meta"=>"","extra_content"=>"","link_button"=>"","button_icon"=>"","button_title"=>"") // ) // ) // ------------------------------------------------------------------------------------------------------------------------- function ui_card(){ $card = '<div class="ui fluid {class} cards">'; $card .= '{card_list}'; $card .= '<div class="card">'; $card .= '<div class="image">'; $card .= '<img src="{image_url}" />'; $card .= '</div>'; $card .= '<div class="content">'; $card .= '<div class="header">{content_header}</div>'; $card .= '{content_meta}'; $card .= '</div>'; $card .= '{extra_content}'; $card .= '<a href="{link_button}" class="ui inverted {_themes} button">'; $card .= '{button_icon}'; $card .= '{button_title}'; $card .= '</a>'; $card .= '</div>'; $card .= '{/card_list}'; $card .= '</div>'; return $card; } }
kukuhsetiawan/lusara
application/libraries/Bootstrap_system.php
PHP
mit
5,355
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_191) on Sun Nov 11 20:31:29 CET 2018 --> <title>ImageUtils</title> <meta name="date" content="2018-11-11"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> <script type="text/javascript" src="../../../script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="ImageUtils"; } } catch(err) { } //--> var methods = {"i0":9,"i1":9,"i2":9,"i3":9,"i4":9,"i5":9,"i6":9,"i7":9,"i8":9,"i9":9}; var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]}; var altColor = "altColor"; var rowColor = "rowColor"; var tableTab = "tableTab"; var activeTableTab = "activeTableTab"; </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../ev3dev/hardware/display/DisplayInterface.html" title="class in ev3dev.hardware.display"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../ev3dev/hardware/display/JavaFramebuffer.html" title="interface in ev3dev.hardware.display"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?ev3dev/hardware/display/ImageUtils.html" target="_top">Frames</a></li> <li><a href="ImageUtils.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <!-- ======== START OF CLASS DATA ======== --> <div class="header"> <div class="subTitle">ev3dev.hardware.display</div> <h2 title="Class ImageUtils" class="title">Class ImageUtils</h2> <map id="G" name="G"> <area shape="rect" id="node1_0" href="./ImageUtils.html" title="ev3dev.hardware.display.ImageUtils" alt="" coords="16,11,596,243"/> <area shape="rect" id="node1" href="./ImageUtils.html" title="&lt;TABLE&gt;" alt="" coords="5,5,607,248"/> </map> <!-- UML diagram added by UMLGraph version R5_6-24-gf6e263 (http://www.umlgraph.org/) --> <div align="center"><img src="ImageUtils.png" alt="Package class diagram package ImageUtils" usemap="#G" border=0/></div> </div> <div class="contentContainer"> <ul class="inheritance"> <li>java.lang.Object</li> <li> <ul class="inheritance"> <li>ev3dev.hardware.display.ImageUtils</li> </ul> </li> </ul> <div class="description"> <ul class="blockList"> <li class="blockList"> <hr> <br> <pre>public class <span class="typeNameLabel">ImageUtils</span> extends java.lang.Object</pre> <div class="block">Common image utilities for framebuffer manipulation</div> <dl> <dt><span class="simpleTagLabel">Since:</span></dt> <dd>2.4.7</dd> </dl> </li> </ul> </div> <div class="summary"> <ul class="blockList"> <li class="blockList"> <!-- ======== CONSTRUCTOR SUMMARY ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.summary"> <!-- --> </a> <h3>Constructor Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation"> <caption><span>Constructors</span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colOne" scope="col">Constructor and Description</th> </tr> <tr class="altColor"> <td class="colOne"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#ImageUtils--">ImageUtils</a></span>()</code>&nbsp;</td> </tr> </table> </li> </ul> <!-- ========== METHOD SUMMARY =========== --> <ul class="blockList"> <li class="blockList"><a name="method.summary"> <!-- --> </a> <h3>Method Summary</h3> <table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation"> <caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd">&nbsp;</span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd">&nbsp;</span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd">&nbsp;</span></span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th class="colLast" scope="col">Method and Description</th> </tr> <tr id="i0" class="altColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createBWImage-int-int-boolean-">createBWImage</a></span>(int&nbsp;width, int&nbsp;height, boolean&nbsp;zeroBlack)</code> <div class="block">Create new BW image.</div> </td> </tr> <tr id="i1" class="rowColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createBWImage-int-int-boolean-byte:A-">createBWImage</a></span>(int&nbsp;width, int&nbsp;height, boolean&nbsp;zeroBlack, byte[]&nbsp;backed)</code> <div class="block">Create new BW image backed by existing data.</div> </td> </tr> <tr id="i2" class="altColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createBWImage-int-int-int-boolean-">createBWImage</a></span>(int&nbsp;width, int&nbsp;height, int&nbsp;stride, boolean&nbsp;zeroBlack)</code> <div class="block">Create new BW image.</div> </td> </tr> <tr id="i3" class="rowColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createBWImage-int-int-int-boolean-byte:A-">createBWImage</a></span>(int&nbsp;width, int&nbsp;height, int&nbsp;stride, boolean&nbsp;zeroBlack, byte[]&nbsp;backed)</code> <div class="block">Create new BW image backed by existing data.</div> </td> </tr> <tr id="i4" class="altColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createXRGBImage-int-int-">createXRGBImage</a></span>(int&nbsp;w, int&nbsp;h)</code> <div class="block">Create new ev3dev-compatible XRGB image.</div> </td> </tr> <tr id="i5" class="rowColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createXRGBImage-int-int-int-">createXRGBImage</a></span>(int&nbsp;w, int&nbsp;h, int&nbsp;stride)</code> <div class="block">Create new XRGB image.</div> </td> </tr> <tr id="i6" class="altColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createXRGBImage-int-int-int-byte:A-">createXRGBImage</a></span>(int&nbsp;width, int&nbsp;height, int&nbsp;stride, byte[]&nbsp;buffer)</code> <div class="block">Create new XRGB image.</div> </td> </tr> <tr id="i7" class="rowColor"> <td class="colFirst"><code>static java.awt.image.BufferedImage</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#createXRGBImage-int-int-int-int:A-byte:A-">createXRGBImage</a></span>(int&nbsp;width, int&nbsp;height, int&nbsp;stride, int[]&nbsp;offsets, byte[]&nbsp;buffer)</code> <div class="block">Create new XRGB image.</div> </td> </tr> <tr id="i8" class="altColor"> <td class="colFirst"><code>static int[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#getDefaultComponentOffsets--">getDefaultComponentOffsets</a></span>()</code> <div class="block">Get default XRGB component offsets.</div> </td> </tr> <tr id="i9" class="rowColor"> <td class="colFirst"><code>static byte[]</code></td> <td class="colLast"><code><span class="memberNameLink"><a href="../../../ev3dev/hardware/display/ImageUtils.html#getImageBytes-java.awt.image.BufferedImage-">getImageBytes</a></span>(java.awt.image.BufferedImage&nbsp;image)</code> <div class="block">Convert image to the underlying byte buffer.</div> </td> </tr> </table> <ul class="blockList"> <li class="blockList"><a name="methods.inherited.from.class.java.lang.Object"> <!-- --> </a> <h3>Methods inherited from class&nbsp;java.lang.Object</h3> <code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li> </ul> </li> </ul> </li> </ul> </div> <div class="details"> <ul class="blockList"> <li class="blockList"> <!-- ========= CONSTRUCTOR DETAIL ======== --> <ul class="blockList"> <li class="blockList"><a name="constructor.detail"> <!-- --> </a> <h3>Constructor Detail</h3> <a name="ImageUtils--"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>ImageUtils</h4> <pre>public&nbsp;ImageUtils()</pre> </li> </ul> </li> </ul> <!-- ============ METHOD DETAIL ========== --> <ul class="blockList"> <li class="blockList"><a name="method.detail"> <!-- --> </a> <h3>Method Detail</h3> <a name="createXRGBImage-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createXRGBImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createXRGBImage(int&nbsp;w, int&nbsp;h)</pre> <div class="block">Create new ev3dev-compatible XRGB image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>w</code> - Image width</dd> <dd><code>h</code> - Image height</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage</dd> </dl> </li> </ul> <a name="createXRGBImage-int-int-int-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createXRGBImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createXRGBImage(int&nbsp;w, int&nbsp;h, int&nbsp;stride)</pre> <div class="block">Create new XRGB image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>w</code> - Image width</dd> <dd><code>h</code> - Image height</dd> <dd><code>stride</code> - Image scanline stride, i.e. how long the row is in bytes.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage</dd> </dl> </li> </ul> <a name="createXRGBImage-int-int-int-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createXRGBImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createXRGBImage(int&nbsp;width, int&nbsp;height, int&nbsp;stride, byte[]&nbsp;buffer)</pre> <div class="block">Create new XRGB image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width</dd> <dd><code>height</code> - Image height</dd> <dd><code>stride</code> - Image scanline stride, i.e. how long the row is in bytes.</dd> <dd><code>buffer</code> - Backing buffer.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage</dd> </dl> </li> </ul> <a name="createXRGBImage-int-int-int-int:A-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createXRGBImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createXRGBImage(int&nbsp;width, int&nbsp;height, int&nbsp;stride, int[]&nbsp;offsets, byte[]&nbsp;buffer)</pre> <div class="block">Create new XRGB image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width</dd> <dd><code>height</code> - Image height</dd> <dd><code>stride</code> - Image scanline stride, i.e. how long the row is in bytes.</dd> <dd><code>offsets</code> - Array of size 4 describing the offsets of color bands: { R, G, B, A }</dd> <dd><code>buffer</code> - Backing buffer.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage</dd> </dl> </li> </ul> <a name="getDefaultComponentOffsets--"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>getDefaultComponentOffsets</h4> <pre>public static&nbsp;int[]&nbsp;getDefaultComponentOffsets()</pre> <div class="block">Get default XRGB component offsets.</div> <dl> <dt><span class="returnLabel">Returns:</span></dt> <dd>Offsets: { R, G, B, A }</dd> </dl> </li> </ul> <a name="createBWImage-int-int-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createBWImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createBWImage(int&nbsp;width, int&nbsp;height, boolean&nbsp;zeroBlack)</pre> <div class="block">Create new BW image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width.</dd> <dd><code>height</code> - Image height.</dd> <dd><code>zeroBlack</code> - Whether black color is represented by the 0 bit value.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage.</dd> </dl> </li> </ul> <a name="createBWImage-int-int-boolean-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createBWImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createBWImage(int&nbsp;width, int&nbsp;height, boolean&nbsp;zeroBlack, byte[]&nbsp;backed)</pre> <div class="block">Create new BW image backed by existing data.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width.</dd> <dd><code>height</code> - Image height.</dd> <dd><code>zeroBlack</code> - Whether black color is represented by the 0 bit value.</dd> <dd><code>backed</code> - Backing byte buffer.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage.</dd> </dl> </li> </ul> <a name="createBWImage-int-int-int-boolean-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createBWImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createBWImage(int&nbsp;width, int&nbsp;height, int&nbsp;stride, boolean&nbsp;zeroBlack)</pre> <div class="block">Create new BW image.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width.</dd> <dd><code>height</code> - Image height.</dd> <dd><code>stride</code> - Image scanline stride, i.e. how long the row is in bytes.</dd> <dd><code>zeroBlack</code> - Whether black color is represented by the 0 bit value.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage.</dd> </dl> </li> </ul> <a name="createBWImage-int-int-int-boolean-byte:A-"> <!-- --> </a> <ul class="blockList"> <li class="blockList"> <h4>createBWImage</h4> <pre>public static&nbsp;java.awt.image.BufferedImage&nbsp;createBWImage(int&nbsp;width, int&nbsp;height, int&nbsp;stride, boolean&nbsp;zeroBlack, byte[]&nbsp;backed)</pre> <div class="block">Create new BW image backed by existing data.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>width</code> - Image width.</dd> <dd><code>height</code> - Image height.</dd> <dd><code>stride</code> - Image scanline stride, i.e. how long the row is in bytes.</dd> <dd><code>zeroBlack</code> - Whether black color is represented by the 0 bit value.</dd> <dd><code>backed</code> - Backing byte buffer.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Configured BufferedImage.</dd> </dl> </li> </ul> <a name="getImageBytes-java.awt.image.BufferedImage-"> <!-- --> </a> <ul class="blockListLast"> <li class="blockList"> <h4>getImageBytes</h4> <pre>public static&nbsp;byte[]&nbsp;getImageBytes(java.awt.image.BufferedImage&nbsp;image)</pre> <div class="block">Convert image to the underlying byte buffer.</div> <dl> <dt><span class="paramLabel">Parameters:</span></dt> <dd><code>image</code> - Configured BufferedImage.</dd> <dt><span class="returnLabel">Returns:</span></dt> <dd>Byte array.</dd> </dl> </li> </ul> </li> </ul> </li> </ul> </div> </div> <!-- ========= END OF CLASS DATA ========= --> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li class="navBarCell1Rev">Class</li> <li><a href="package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../ev3dev/hardware/display/DisplayInterface.html" title="class in ev3dev.hardware.display"><span class="typeNameLink">Prev&nbsp;Class</span></a></li> <li><a href="../../../ev3dev/hardware/display/JavaFramebuffer.html" title="interface in ev3dev.hardware.display"><span class="typeNameLink">Next&nbsp;Class</span></a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?ev3dev/hardware/display/ImageUtils.html" target="_top">Frames</a></li> <li><a href="ImageUtils.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <div> <ul class="subNavList"> <li>Summary:&nbsp;</li> <li>Nested&nbsp;|&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.summary">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.summary">Method</a></li> </ul> <ul class="subNavList"> <li>Detail:&nbsp;</li> <li>Field&nbsp;|&nbsp;</li> <li><a href="#constructor.detail">Constr</a>&nbsp;|&nbsp;</li> <li><a href="#method.detail">Method</a></li> </ul> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
ev3dev-lang-java/ev3dev-lang-java.github.io
docs/api/v2.4.13/ev3dev-lang-java/ev3dev/hardware/display/ImageUtils.html
HTML
mit
21,473
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <React.Fragment><path fill="none" d="M0 0h24v24H0z" /><path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z" /></React.Fragment> , 'SignalWifiOff');
allanalexandre/material-ui
packages/material-ui-icons/src/SignalWifiOff.js
JavaScript
mit
415
๏ปฟusing System.Collections.Generic; namespace EasyNetQ.Topology { /// <summary> /// Represents an AMQP exchange /// </summary> public interface IExchange : IBindable { /// <summary> /// The exchange name. /// </summary> string Name { get; } /// <summary> /// The exchange type. /// </summary> string Type { get; } /// <summary> /// If set the exchange remains active when a server restarts. /// </summary> bool IsDurable { get; } /// <summary> /// If set the exchange is deleted when all consumers have finished using it. /// </summary> bool IsAutoDelete { get; } /// <summary> /// The exchange arguments. /// </summary> IDictionary<string, object> Arguments { get; } } }
zidad/EasyNetQ
Source/EasyNetQ/Topology/IExchange.cs
C#
mit
862
Copyright (c) 2014 Matthew Green Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
NerdGGuy/wai-middleware-oauth2
LICENSE.md
Markdown
mit
1,057
OBJS = \ bio.o\ console.o\ exec.o\ file.o\ fs.o\ ide.o\ ioapic.o\ kalloc.o\ kbd.o\ lapic.o\ log.o\ main.o\ mp.o\ picirq.o\ pipe.o\ proc.o\ spinlock.o\ string.o\ swtch.o\ syscall.o\ sysfile.o\ sysproc.o\ timer.o\ trapasm.o\ trap.o\ uart.o\ vectors.o\ vm.o\ semaphore.o\ # Cross-compiling (e.g., on Mac OS X) # TOOLPREFIX = i386-jos-elf # Using native tools (e.g., on X86 Linux) #TOOLPREFIX = # Try to infer the correct TOOLPREFIX if not set ifndef TOOLPREFIX TOOLPREFIX := $(shell if i386-jos-elf-objdump -i 2>&1 | grep '^elf32-i386$$' >/dev/null 2>&1; \ then echo 'i386-jos-elf-'; \ elif objdump -i 2>&1 | grep 'elf32-i386' >/dev/null 2>&1; \ then echo ''; \ else echo "***" 1>&2; \ echo "*** Error: Couldn't find an i386-*-elf version of GCC/binutils." 1>&2; \ echo "*** Is the directory with i386-jos-elf-gcc in your PATH?" 1>&2; \ echo "*** If your i386-*-elf toolchain is installed with a command" 1>&2; \ echo "*** prefix other than 'i386-jos-elf-', set your TOOLPREFIX" 1>&2; \ echo "*** environment variable to that prefix and run 'make' again." 1>&2; \ echo "*** To turn off this error, run 'gmake TOOLPREFIX= ...'." 1>&2; \ echo "***" 1>&2; exit 1; fi) endif # If the makefile can't find QEMU, specify its path here #QEMU = /ilab/users/wkatsak/qemu-1.7.0/i386-softmmu/qemu-system-i386 # Try to infer the correct QEMU ifndef QEMU QEMU = $(shell if which qemu > /dev/null; \ then echo qemu; exit; \ elif which qemu-system-i386 > /dev/null; \ then echo qemu-system-i386; exit; \ else \ qemu=/Applications/Q.app/Contents/MacOS/i386-softmmu.app/Contents/MacOS/i386-softmmu; \ if test -x $$qemu; then echo $$qemu; exit; fi; fi; \ echo "***" 1>&2; \ echo "*** Error: Couldn't find a working QEMU executable." 1>&2; \ echo "*** Is the directory containing the qemu binary in your PATH" 1>&2; \ echo "*** or have you tried setting the QEMU variable in Makefile?" 1>&2; \ echo "***" 1>&2; exit 1) endif CC = $(TOOLPREFIX)gcc AS = $(TOOLPREFIX)gas LD = $(TOOLPREFIX)ld OBJCOPY = $(TOOLPREFIX)objcopy OBJDUMP = $(TOOLPREFIX)objdump #CFLAGS = -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer CFLAGS = -fno-pic -static -fno-builtin -fno-strict-aliasing -fvar-tracking -fvar-tracking-assignments -O0 -g -Wall -MD -gdwarf-2 -m32 -Werror -fno-omit-frame-pointer CFLAGS += $(shell $(CC) -fno-stack-protector -E -x c /dev/null >/dev/null 2>&1 && echo -fno-stack-protector) ASFLAGS = -m32 -gdwarf-2 -Wa,-divide # FreeBSD ld wants ``elf_i386_fbsd'' LDFLAGS += -m $(shell $(LD) -V | grep elf_i386 2>/dev/null) xv6.img: bootblock kernel fs.img dd if=/dev/zero of=xv6.img count=10000 dd if=bootblock of=xv6.img conv=notrunc dd if=kernel of=xv6.img seek=1 conv=notrunc xv6memfs.img: bootblock kernelmemfs dd if=/dev/zero of=xv6memfs.img count=10000 dd if=bootblock of=xv6memfs.img conv=notrunc dd if=kernelmemfs of=xv6memfs.img seek=1 conv=notrunc bootblock: bootasm.S bootmain.c $(CC) $(CFLAGS) -fno-pic -O -nostdinc -I. -c bootmain.c $(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c bootasm.S $(LD) $(LDFLAGS) -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o $(OBJDUMP) -S bootblock.o > bootblock.asm $(OBJCOPY) -S -O binary -j .text bootblock.o bootblock ./sign.pl bootblock entryother: entryother.S $(CC) $(CFLAGS) -fno-pic -nostdinc -I. -c entryother.S $(LD) $(LDFLAGS) -N -e start -Ttext 0x7000 -o bootblockother.o entryother.o $(OBJCOPY) -S -O binary -j .text bootblockother.o entryother $(OBJDUMP) -S bootblockother.o > entryother.asm initcode: initcode.S $(CC) $(CFLAGS) -nostdinc -I. -c initcode.S $(LD) $(LDFLAGS) -N -e start -Ttext 0 -o initcode.out initcode.o $(OBJCOPY) -S -O binary initcode.out initcode $(OBJDUMP) -S initcode.o > initcode.asm kernel: $(OBJS) entry.o entryother initcode kernel.ld $(LD) $(LDFLAGS) -T kernel.ld -o kernel entry.o $(OBJS) -b binary initcode entryother $(OBJDUMP) -S kernel > kernel.asm $(OBJDUMP) -t kernel | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernel.sym # kernelmemfs is a copy of kernel that maintains the # disk image in memory instead of writing to a disk. # This is not so useful for testing persistent storage or # exploring disk buffering implementations, but it is # great for testing the kernel on real hardware without # needing a scratch disk. MEMFSOBJS = $(filter-out ide.o,$(OBJS)) memide.o kernelmemfs: $(MEMFSOBJS) entry.o entryother initcode kernel.ld fs.img $(LD) $(LDFLAGS) -T kernel.ld -o kernelmemfs entry.o $(MEMFSOBJS) -b binary initcode entryother fs.img $(OBJDUMP) -S kernelmemfs > kernelmemfs.asm $(OBJDUMP) -t kernelmemfs | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > kernelmemfs.sym tags: $(OBJS) entryother.S _init etags *.S *.c vectors.S: vectors.pl perl vectors.pl > vectors.S ULIB = ulib.o usys.o printf.o umalloc.o _%: %.o $(ULIB) $(LD) $(LDFLAGS) -N -e main -Ttext 0 -o $@ $^ $(OBJDUMP) -S $@ > $*.asm $(OBJDUMP) -t $@ | sed '1,/SYMBOL TABLE/d; s/ .* / /; /^$$/d' > $*.sym _forktest: forktest.o $(ULIB) # forktest has less library code linked in - needs to be small # in order to be able to max out the proc table. $(LD) $(LDFLAGS) -N -e main -Ttext 0 -o _forktest forktest.o ulib.o usys.o $(OBJDUMP) -S _forktest > forktest.asm mkfs: mkfs.c fs.h gcc -Werror -Wall -o mkfs mkfs.c # Prevent deletion of intermediate files, e.g. cat.o, after first build, so # that disk image changes after first build are persistent until clean. More # details: # http://www.gnu.org/software/make/manual/html_node/Chained-Rules.html .PRECIOUS: %.o UPROGS=\ _cat\ _echo\ _forktest\ _grep\ _init\ _kill\ _ln\ _ls\ _mkdir\ _rm\ _sh\ _stressfs\ _usertests\ _wc\ _zombie\ _shutdown\ _sem_test\ _thread_test\ fs.img: mkfs README $(UPROGS) ./mkfs fs.img README $(UPROGS) -include *.d clean: rm -f *.tex *.dvi *.idx *.aux *.log *.ind *.ilg \ *.o *.d *.asm *.sym vectors.S bootblock entryother \ initcode initcode.out kernel xv6.img fs.img kernelmemfs mkfs \ .gdbinit \ $(UPROGS) # make a printout FILES = $(shell grep -v '^\#' runoff.list) PRINT = runoff.list runoff.spec README toc.hdr toc.ftr $(FILES) xv6.pdf: $(PRINT) ./runoff ls -l xv6.pdf print: xv6.pdf # run in emulators bochs : fs.img xv6.img if [ ! -e .bochsrc ]; then ln -s dot-bochsrc .bochsrc; fi bochs -q # try to generate a unique GDB port GDBPORT = $(shell expr `id -u` % 5000 + 25000) # QEMU's gdb stub command line changed in 0.11 QEMUGDB = $(shell if $(QEMU) -help | grep -q '^-gdb'; \ then echo "-gdb tcp::$(GDBPORT)"; \ else echo "-s -p $(GDBPORT)"; fi) ifndef CPUS CPUS := 2 endif QEMUOPTS = -hdb fs.img xv6.img -smp $(CPUS) -m 512 $(QEMUEXTRA) qemu: fs.img xv6.img $(QEMU) -serial mon:stdio $(QEMUOPTS) qemu-memfs: xv6memfs.img $(QEMU) xv6memfs.img -smp $(CPUS) -m 256 qemu-nox: fs.img xv6.img $(QEMU) -nographic $(QEMUOPTS) .gdbinit: .gdbinit.tmpl sed "s/localhost:1234/localhost:$(GDBPORT)/" < $^ > $@ qemu-gdb: fs.img xv6.img .gdbinit @echo "*** Now run 'gdb'." 1>&2 $(QEMU) -serial mon:stdio $(QEMUOPTS) -S $(QEMUGDB) qemu-nox-gdb: fs.img xv6.img .gdbinit @echo "*** Now run 'gdb'." 1>&2 $(QEMU) -nographic $(QEMUOPTS) -S $(QEMUGDB) # CUT HERE # prepare dist for students # after running make dist, probably want to # rename it to rev0 or rev1 or so on and then # check in that version. EXTRA=\ mkfs.c ulib.c user.h cat.c echo.c forktest.c grep.c kill.c\ ln.c ls.c mkdir.c rm.c stressfs.c usertests.c wc.c zombie.c\ printf.c umalloc.c\ README dot-bochsrc *.pl toc.* runoff runoff1 runoff.list\ .gdbinit.tmpl gdbutil\ dist: rm -rf dist mkdir dist for i in $(FILES); \ do \ grep -v PAGEBREAK $$i >dist/$$i; \ done sed '/CUT HERE/,$$d' Makefile >dist/Makefile echo >dist/runoff.spec cp $(EXTRA) dist dist-test: rm -rf dist make dist rm -rf dist-test mkdir dist-test cp dist/* dist-test cd dist-test; $(MAKE) print cd dist-test; $(MAKE) bochs || true cd dist-test; $(MAKE) qemu # update this rule (change rev#) when it is time to # make a new revision. tar: rm -rf /tmp/xv6 mkdir -p /tmp/xv6 cp dist/* dist/.gdbinit.tmpl /tmp/xv6 (cd /tmp; tar cf - xv6) | gzip >xv6-rev5.tar.gz submit-help: @echo "This makefile target is used to convieniently package your modifications for grading" @echo "Type \"make submit netids=NETID1-NETID2 name=SECTION_NAME base=BASE_BRANCH\" to create a tarball." submit: ifndef netids @echo "You must specify your netids, please type \"make submit-help\" for more details" else ifndef name @echo "You must specify a name, please type \"make submit-help\" for more details" else ifndef base @echo "You must specify a base, please type \"make submit-help\" for more details" else @./package_patches.sh $(netids) $(name) $(base) endif endif endif .PHONY: dist-test dist
MrHohn/CS-OperatingSystem-hw2
Makefile
Makefile
mit
8,788
๏ปฟusing System; using System.Collections.Generic; using HoloToolkit.Unity; namespace HoloToolkit.Sharing { /// <summary> /// Keeps track of the users in the current session. /// Instance is created by Sharing Stage when a connection is found. /// </summary> public class SessionUsersTracker : IDisposable { /// <summary> /// UserJoined event notifies when a user joins the current session. /// </summary> public event Action<User> UserJoined; /// <summary> /// UserLeft event notifies when a user leaves the current session. /// </summary> public event Action<User> UserLeft; /// <summary> /// Local cached pointer to the sessions tracker.. /// </summary> private readonly ServerSessionsTracker serverSessionsTracker; /// <summary> /// List of users that are in the current session. /// </summary> public List<User> CurrentUsers { get; private set; } public SessionUsersTracker(ServerSessionsTracker sessionsTracker) { CurrentUsers = new List<User>(); serverSessionsTracker = sessionsTracker; serverSessionsTracker.CurrentUserJoined += OnCurrentUserJoinedSession; serverSessionsTracker.CurrentUserLeft += OnCurrentUserLeftSession; serverSessionsTracker.UserJoined += OnUserJoinedSession; serverSessionsTracker.UserLeft += OnUserLeftSession; } /// <summary> /// Finds and returns an object representing a user who has the supplied id number. Returns null if the user is not found. /// </summary> /// <param name="userId">The numerical id of the session User to find</param> /// <returns>The User with the specified id or null (if not found)</returns> public User GetUserById(int userId) { for (int u = 0; u < CurrentUsers.Count; u++) { User user = CurrentUsers[u]; if (user.GetID() == userId) { return user; } } return null; } #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposing) { serverSessionsTracker.CurrentUserJoined -= OnCurrentUserJoinedSession; serverSessionsTracker.CurrentUserLeft -= OnCurrentUserLeftSession; serverSessionsTracker.UserJoined -= OnUserJoinedSession; serverSessionsTracker.UserLeft -= OnUserLeftSession; } } #endregion private void OnCurrentUserJoinedSession(Session joinedSession) { //Debug.LogFormat("Joining session {0}.", joinedSession.GetName()); // If joining a new session, any user in the previous session (if any) have left ClearCurrentSession(); // Send a join event for every user currently in the session we joined for (int i = 0; i < joinedSession.GetUserCount(); i++) { User user = joinedSession.GetUser(i); CurrentUsers.Add(user); UserJoined.RaiseEvent(user); } } private void OnCurrentUserLeftSession(Session leftSession) { //Debug.Log("Left current session."); // If we leave a session, notify that every user has left the current session of this app ClearCurrentSession(); } private void OnUserJoinedSession(Session session, User user) { if (!session.IsJoined()) { return; } if (!CurrentUsers.Contains(user)) { // Remove any old users with the same ID for (int i = CurrentUsers.Count - 1; i >= 0; i--) { if (CurrentUsers[i].GetID() == user.GetID()) { CurrentUsers.RemoveAt(i); } } CurrentUsers.Add(user); UserJoined.RaiseEvent(user); // Debug.LogFormat("User {0} joined current session.", user.GetName()); } } private void OnUserLeftSession(Session session, User user) { if (!session.IsJoined()) { return; } for (int i = CurrentUsers.Count - 1; i >= 0; i--) { if (CurrentUsers[i].GetID() == user.GetID()) { CurrentUsers.RemoveAt(i); UserLeft.RaiseEvent(user); // Debug.LogFormat("User {0} left current session.", user.GetName()); } } } /// <summary> /// Clears the current session, removing any users being tracked. /// This should be called whenever the current session changes, to reset this class /// and handle a new curren session. /// </summary> private void ClearCurrentSession() { for (int i = 0; i < CurrentUsers.Count; i++) { UserLeft.RaiseEvent(CurrentUsers[i]); } CurrentUsers.Clear(); } } }
AllBecomesGood/Share-UpdateHolograms
ShareAndKeepSynced/Assets/HoloToolKit/Sharing/Scripts/SessionUsersTracker.cs
C#
mit
5,480
(function() { var checkVersion = Dagaz.Model.checkVersion; Dagaz.Model.checkVersion = function(design, name, value) { if (name != "magyar-no-pass") { checkVersion(design, name, value); } } var CheckInvariants = Dagaz.Model.CheckInvariants; Dagaz.Model.CheckInvariants = function(board) { var design = Dagaz.Model.design; _.each(board.moves, function(move) { if (move.isSimpleMove() && (move.actions[0][0][0] == move.actions[0][1][0])) { move.failed = true; } }); CheckInvariants(board); } })();
GlukKazan/Dagaz
src/debug/games/checkers/magyar-no-pass.js
JavaScript
mit
562
๏ปฟimport {ScopedStructure} from "./../../../../structures"; import {Scope} from "./../../../../definitions"; import {ScopedBinder} from "./../../../base"; export class StructureScopedBinder extends ScopedBinder { constructor(private readonly structure: ScopedStructure) { super(); } getScope() { return this.structure.scope || Scope.Public; } }
dsherret/type-info-ts
src/binders/structure/class/base/StructureScopedBinder.ts
TypeScript
mit
380
package com.firebase.androidchat; import android.app.ListActivity; import android.content.SharedPreferences; import android.database.DataSetObserver; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.inputmethod.EditorInfo; import android.widget.*; import com.firebase.client.DataSnapshot; import com.firebase.client.Firebase; import com.firebase.client.ValueEventListener; import java.util.Random; public class MainActivity extends ListActivity { // TODO: change this to your own Firebase URL private static final String FIREBASE_URL = "https://intense-fire-2747.firebaseio.com"; private String username; private Firebase ref; private ValueEventListener connectedListener; private ChatListAdapter chatListAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Make sure we have a username setupUsername(); setTitle("Chatting as " + username); // Setup our Firebase ref ref = new Firebase(FIREBASE_URL).child("chat"); // Setup our input methods. Enter key on the keyboard or pushing the send button EditText inputText = (EditText)findViewById(R.id.messageInput); inputText.setOnEditorActionListener(new TextView.OnEditorActionListener() { @Override public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) { if (actionId == EditorInfo.IME_NULL && keyEvent.getAction() == KeyEvent.ACTION_DOWN) { sendMessage(); } return true; } }); findViewById(R.id.sendButton).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { sendMessage(); } }); } @Override public void onStart() { super.onStart(); // Setup our view and list adapter. Ensure it scrolls to the bottom as data changes final ListView listView = getListView(); // Tell our list adapter that we only want 50 messages at a time chatListAdapter = new ChatListAdapter(ref.limit(50), this, R.layout.chat_message, username); listView.setAdapter(chatListAdapter); chatListAdapter.registerDataSetObserver(new DataSetObserver() { @Override public void onChanged() { super.onChanged(); listView.setSelection(chatListAdapter.getCount() - 1); } }); // Finally, a little indication of connection status connectedListener = ref.getRoot().child(".info/connected").addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { boolean connected = (Boolean)dataSnapshot.getValue(); if (connected) { Toast.makeText(MainActivity.this, "Connected to Firebase", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(MainActivity.this, "Disconnected from Firebase", Toast.LENGTH_SHORT).show(); } } @Override public void onCancelled() { // No-op } }); } @Override public void onStop() { super.onStop(); ref.getRoot().child(".info/connected").removeEventListener(connectedListener); chatListAdapter.cleanup(); } private void setupUsername() { SharedPreferences prefs = getApplication().getSharedPreferences("ChatPrefs", 0); username = prefs.getString("username", null); if (username == null) { Random r = new Random(); // Assign a random user name if we don't have one saved. username = "JavaUser" + r.nextInt(100000); prefs.edit().putString("username", username).commit(); } } private void sendMessage() { EditText inputText = (EditText)findViewById(R.id.messageInput); String input = inputText.getText().toString(); if (!input.equals("")) { // Create our 'model', a Chat object Chat chat = new Chat(input, username); // Create a new, auto-generated child of that chat location, and save our chat data there ref.push().setValue(chat); inputText.setText(""); } } }
Pankaj-Dream/MrMafia
src/com/firebase/androidchat/MainActivity.java
Java
mit
4,551
/* * UserLogin Messages * * This contains all the text for the UserLogin component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.containers.UserLogin.header', defaultMessage: 'This is UserLogin container !', }, usernameInput: { id: 'app.containers.login_page.username', defaultMessage: 'Username', }, passwordInput: { id: 'app.containers.login_page.password', defaultMessage: 'Password', }, rememberMe: { id: 'app.containers.login_page.rememberMe', defaultMessage: 'Remember Login', }, isPrivateComputer: { id: 'app.containers.login_page.computer_is_private', defaultMessage: 'if this is a private computer', }, logInButton: { id: 'app.containers.login_page.log_in', defaultMessage: 'Log In', }, // Eventually the backend should be returning a constant defaultLoginError: { id: 'app.containers.login_page.log_in', defaultMessage: 'Wrong username or password.', }, });
VeloCloud/website-ui
app/containers/UserLogin/messages.js
JavaScript
mit
1,013
<?php /** * @author Honza Cerny (http://honzacerny.com) */ namespace App\Model; class DuplicateEntryException extends \RuntimeException { }
matej21/planette-doctrine
app/model/exceptions.php
PHP
mit
144
# Problem A common genre of document across many publishers is a consumer review of products or media, such as movies, books, or gadgets. A consumer review is like any other article, but it often includes a formal rating of the item being reviewed. Rating values may be used: * to create renderable widgets on the site (Four gold star graphics and one gray star graphic for "4/5 stars") or * to sort content ("sort documents in this section by review score") There are further complications in a multi-tenant environment. Different publishers -- or even different desks or writers within a publisher -- may position the rating in different places within an article. Not all publishers or desks may use the same review system ("4/5 starts" vs "9.1 (out of 10)" vs "Recommended" or "Not Recommended") In some cases, like a round-up or a gift guide, a single article may also have multiple ratings for different items. This proposal attempts to address most of these cases by providing new content elements for these purposes. # Proposal Two new content elements that represent numeric and non-numeric ratings values. ## New 'Numeric Rating' element A new content element `numeric_rating` will be added to indicate a numeric rating, with the following fields: * `numeric_rating` -- a float indicating the item's value (required) * `min` -- a float the minimum possible value of rating * `max` -- a float indicating the maximum possible value of rating * `units` -- a string describing the rating units (e.g., "stars," "thumbs") ### Example ``` { "type": "numeric_rating", "numeric_rating": 4.5, "min": 0, "max": 5.0, "units": "stars" } ``` ## New 'Endorsement' element A new content element `endorsement` will be added to indicate text-only appraisals * `endorsement`: a string indicating the value (e.g. "Buy" or "Don't Buy") (required) ### Example ``` { "type": "endorsement", "endorsement": "Recommended" } ``` `endorsements` should be used primarily when there is no quantifiable relationship between the various possible values. The set of possible values for the `units` and `endorsement` fields are left deliberately undefined here. The only restrictions on `rating`, `min` and `max` are that `rating` is required and `min` < `rating` < `max`. Templates and App UIs may implement restrictions on new input as they see fit, but they *must be able to interpret any arbitrary values for these fields in a reasonable way.* ## Document Example ``` { "type": "story", "version": "0.5.9", "headlines": { "basic": "Not So Beastly" }, "content_elements": [ { "type": "text", "content": "Disney's <em>Beauty and the Beast</em> is pretty good, all things considered." }, { "type": "numeric_rating", "numeric_rating": 4.5, "min": 0, "max": 5, "units": "stars" }, { "type": "endorsement", "endorsement": "Watch" } ] } ``` ## Concerns ### Is this queryable? In general, yes. All the new fields here will be indexed. Organizations will need to sort content taxonomically to make the best use of the system. Documents with mutliple `numeric_rating` or `endorsement` elements will need to be carefully considered as well, since querying on `content_elements.numeric_rating:4.5` would match all documents that have *any* rating of 4.5 within content elements. ### Why floating points? Many star systems use half values. It's possible to represent that as something like: ``` { "numeric_rating": 9, "max": 10, "scale": 0.5 } ``` ... to indicate 4.5 / 5 stars, but this seemed like more overhead than it was worth. It is not expected that a lot of math is going to be done on these values, so the loss of precision when dealing with floating points is not expected to be a concern. ### Why two different element types? A text-only endorsement is semantically different -- it is closer to a label or a tag than a ranking or a value. As explained above, it's certainly possible to render specific units as text tags instead of numbers, and that is encouraged usage. But there will still be cases when a simple flag is all that is desired. ### Isn't this a little open-ended? I only want to mark items as "Buy" or "Don't Buy" but you're telling me I have to handle any possible value of endorsement? For UIs -- yes. The set of possibilities is too large and will change to rapidly to enumerate them all in the schema, so you will have to surface any values present and allow them to be edited, regardless of your own input validation logic. For templates, or other reader-facing renderers, checking for known values to render and ignoring the rest is perfectly appropriate.
washingtonpost/ans-schema
docs/proposals/2017-11-17_-_Ratings.md
Markdown
mit
4,728
<?php /** * This file is property of crakmedia (http://crakmedia.com) * * PHP Version 5.4 * * @copyright 2015 Crakmedia */ require_once __DIR__.'/../vendor/autoload.php'; $app = new Silex\Application(); require __DIR__ . '/../app/app.php'; $app->run();
CrakLabs/skeleton-service
web/index.php
PHP
mit
263
<div class="container"> <header></header> <div class="row col-xs-8"> <tabs> <tab tabTitle="Multi Result"> <table-bet typeBet="{{typeBetEnum.MultiResult}}"></table-bet> </tab> <tab tabTitle="Doble Chance"> <table-bet typeBet="{{typeBetEnum.DobleChance}}"></table-bet> </tab> <tab tabTitle="Correct Score"> <correct-Score></correct-Score> </tab> </tabs> </div> <div class="col-xs-4"> <result-Bets></result-Bets> </div> </div>
vicmator/Angular-Webpack
src/app/app.component.html
HTML
mit
506
from sentence import Sentence from textblob import TextBlob from itertools import chain from collections import Counter def findSubject(lines): sentences = [] if len(lines) == 0: print "messages are empty" return None for m in lines: sentences.append(Sentence(m).nouns) if len(sentences) != 0: maxNoun = Counter(list(chain(*sentences))).most_common()[0] else: print "No nouns" return None if maxNoun[1] >= 2: return maxNoun[0].replace(" ","_") else: return None
ZacharyJacobCollins/Fallen
tagger.py
Python
mit
554
"use babel"; // @flow export function filterAtomEnv(env: Object) { const filteredVars = ["ATOM_HOME", "NODE_PATH"]; return Object.entries(env).reduce((newEnv, [key, value]) => { if (filteredVars.find(v => v === key) != null) return newEnv; return { ...newEnv, [key]: value }; }, {}); }
alanzanattadev/atom-molecule-dev-environment
lib/ExecutionControlEpic/TerminalFeature/Model/utils.js
JavaScript
mit
302
/*************************************************************************** GanttProject.java - description ------------------- begin : dec 2002 copyright : (C) 2002 by Thomas Alexandre email : alexthomas(at)ganttproject.org ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ package net.sourceforge.ganttproject; import java.awt.BorderLayout; import java.awt.Color; import java.awt.ComponentOrientation; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.AccessControlException; import java.util.ArrayList; import java.util.Enumeration; import java.util.HashMap; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import javax.swing.AbstractAction; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFileChooser; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JSplitPane; import javax.swing.JTabbedPane; import javax.swing.JToolBar; import javax.swing.KeyStroke; import javax.swing.SwingUtilities; import javax.swing.UIManager; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.event.TreeModelEvent; import javax.swing.event.TreeModelListener; import javax.swing.filechooser.FileFilter; //import javax.swing.plaf.metal.MetalLookAndFeel; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.TreeModel; import net.sourceforge.ganttproject.action.DeleteHumanAction; import net.sourceforge.ganttproject.action.ImportResources; import net.sourceforge.ganttproject.action.NewArtefactAction; import net.sourceforge.ganttproject.action.NewHumanAction; import net.sourceforge.ganttproject.action.NewTaskAction; import net.sourceforge.ganttproject.action.ResourceActionSet; import net.sourceforge.ganttproject.document.AbstractURLDocument; import net.sourceforge.ganttproject.document.Document; import net.sourceforge.ganttproject.document.DocumentCreator; import net.sourceforge.ganttproject.document.DocumentsMRU; import net.sourceforge.ganttproject.document.FileDocument; import net.sourceforge.ganttproject.document.HttpDocument; import net.sourceforge.ganttproject.document.OpenDocumentAction; import net.sourceforge.ganttproject.filter.GanttCSVFilter; import net.sourceforge.ganttproject.filter.GanttHTMLFileFilter; import net.sourceforge.ganttproject.filter.GanttJPGFileFilter; import net.sourceforge.ganttproject.filter.GanttPDFFileFilter; import net.sourceforge.ganttproject.filter.GanttPNGFileFilter; import net.sourceforge.ganttproject.filter.GanttTXTFileFilter; import net.sourceforge.ganttproject.filter.GanttXFIGFileFilter; import net.sourceforge.ganttproject.filter.GanttXMLFileFilter; import net.sourceforge.ganttproject.gui.GanttDialogCalendar; import net.sourceforge.ganttproject.gui.GanttDialogInfo; import net.sourceforge.ganttproject.gui.GanttDialogProperties; import net.sourceforge.ganttproject.gui.GanttLookAndFeelInfo; import net.sourceforge.ganttproject.gui.GanttLookAndFeels; //import net.sourceforge.ganttproject.gui.GanttMetalTheme; import net.sourceforge.ganttproject.gui.GanttPreviewPrint; import net.sourceforge.ganttproject.gui.GanttStatusBar; import net.sourceforge.ganttproject.gui.GanttURLChooser; import net.sourceforge.ganttproject.gui.TestGanttRolloverButton; import net.sourceforge.ganttproject.gui.TipsDialog; import net.sourceforge.ganttproject.gui.UIConfiguration; import net.sourceforge.ganttproject.gui.about.AboutDialog; import net.sourceforge.ganttproject.gui.options.SettingsDialog; import net.sourceforge.ganttproject.gui.projectwizard.NewProjectWizard; import net.sourceforge.ganttproject.io.GanttCSVExport; import net.sourceforge.ganttproject.io.GanttHTMLExport; import net.sourceforge.ganttproject.io.GanttPDFExport; import net.sourceforge.ganttproject.io.GanttTXTOpen; import net.sourceforge.ganttproject.io.GanttXFIGSaver; import net.sourceforge.ganttproject.io.GanttXMLOpen; import net.sourceforge.ganttproject.io.GanttXMLSaver; import net.sourceforge.ganttproject.language.GanttLanguage; import net.sourceforge.ganttproject.parser.AllocationTagHandler; import net.sourceforge.ganttproject.parser.DependencyTagHandler; import net.sourceforge.ganttproject.parser.ResourceTagHandler; import net.sourceforge.ganttproject.parser.RoleTagHandler; import net.sourceforge.ganttproject.resource.HumanResourceManager; import net.sourceforge.ganttproject.resource.ProjectResource; import net.sourceforge.ganttproject.resource.ResourceContext; import net.sourceforge.ganttproject.resource.ResourceManager; import net.sourceforge.ganttproject.roles.RoleManager; import net.sourceforge.ganttproject.task.Task; import net.sourceforge.ganttproject.task.TaskContainmentHierarchyFacade; import net.sourceforge.ganttproject.task.TaskManager; import net.sourceforge.ganttproject.task.TaskManagerConfig; import net.sourceforge.ganttproject.task.algorithm.AdjustTaskBoundsAlgorithm; import net.sourceforge.ganttproject.task.algorithm.RecalculateTaskCompletionPercentageAlgorithm; import net.sourceforge.ganttproject.task.dependency.TaskDependencyException; import net.sourceforge.ganttproject.util.BrowserControl; /** * Main frame of the project */ public class GanttProject extends JFrame implements ActionListener, IGanttProject { /** The current version of ganttproject */ public static final String version = "1.10"; /* List of calendar for the project */ private ArrayList listOfCalendar = new ArrayList(); /** Command line creation or gui creation */ public static boolean byCommandLine = false; /** The language use */ private GanttLanguage language = GanttLanguage.getInstance(); /** The JTree part. */ private GanttTree tree; /** GanttGraphicArea for the calendar with Gantt */ private GanttGraphicArea area; /** GanttPeoplePanel to edit person that work on the project */ private GanttResourcePanel resp; /** The differents menus */ public JMenu mProject, mMRU, mEdit, mTask, mHuman, mHelp, mServer, mCalendar; /** The differetns menuitem */ public JMenuItem miNew, miOpen, miOpenURL, miSave, miSaveAs, miSaveAsURL, miExport,miImport,/*miOpenDB,miSaveAsDB,*/ miPrint, miPreview, miQuit, miCut, miCopy, miPaste,miOptions, miDeleteTask, miPropertiesTask, miUp, miDown, miDelHuman, miPropHuman, miSendMailHuman, miEditCalendar, miPrjCal, miWebPage, miTips, miAbout, miManual; private static final int maxSizeMRU = 8; private DocumentsMRU documentsMRU = new DocumentsMRU(maxSizeMRU); /** The differents button of toolbar */ public TestGanttRolloverButton bNew, bOpen, bSave, bSaveAs, bExport, bImport, bPrint, bNewTask, bDelete, bProperties, bUnlink, bLink, bInd, bUnind, bUp, bDown, bPrev, bNext, bZoomIn, bZoomOut, bZoomFit; /** The project filename */ public Document projectDocument = null; /** The tabbed pane with the differents parts of the project */ public JTabbedPane tabpane; /** Informations for the current project. */ public PrjInfos prjInfos = new PrjInfos(); /** Boolean to know if the file has been modify */ public boolean askForSave = false; /** The info for the look'n'feel */ public GanttLookAndFeelInfo lookAndFeel; /** The list of all managers installed in this project */ private Hashtable managerHash = new Hashtable(); private ResourceActionSet myResourceActions; private boolean isApplet; /** Frame for the help Viewer */ private JFrame helpFrame = null; private final TaskManager myTaskManager; private FacadeInvalidator myFacadeInvalidator; private UIConfiguration myUIConfiguration; private static class TaskContainmentHierarchyFacadeImpl implements TaskContainmentHierarchyFacade { private Map myTask2treeNode = new HashMap(); private Task myRootTask; public TaskContainmentHierarchyFacadeImpl(GanttTree tree) { ArrayList allTasks = tree.getAllTasks(); //comboBox.addItem("no set"); //for (int i = 0; i < allTasks.size(); i++) { //DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) allTasks.get(i); for (Iterator it = allTasks.iterator(); it.hasNext();) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) it.next(); Task task = (Task) treeNode.getUserObject(); if (treeNode.isRoot()) { myRootTask = task; } myTask2treeNode.put(task, treeNode); } } public Task[] getNestedTasks(Task container) { Task[] result = null; DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode.get(container); if (treeNode != null) { ArrayList list = new ArrayList(); for (Enumeration children = treeNode.children(); children.hasMoreElements();) { DefaultMutableTreeNode next = (DefaultMutableTreeNode) children.nextElement(); list.add(next.getUserObject()); } result = (Task[]) list.toArray(new Task[0]); } return result == null ? new Task[0] : result; } public Task getRoot() { return myRootTask; } public Task getContainer(Task nestedTask) { DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode) myTask2treeNode.get(nestedTask); if (treeNode == null) { return null; } DefaultMutableTreeNode containerNode = (DefaultMutableTreeNode) treeNode.getParent(); return containerNode == null ? null : (Task) containerNode.getUserObject(); } } private static class FacadeInvalidator implements TreeModelListener { private boolean isValid; public FacadeInvalidator(TreeModel treeModel) { isValid = false; treeModel.addTreeModelListener(this); } boolean isValid() { return isValid; } void reset() { isValid = true; } public void treeNodesChanged(TreeModelEvent e) { isValid = false; } public void treeNodesInserted(TreeModelEvent e) { isValid = false; } public void treeNodesRemoved(TreeModelEvent e) { isValid = false; } public void treeStructureChanged(TreeModelEvent e) { isValid = false; } } private final GanttOptions options; //! Toolbar of ui private JToolBar toolBar; //! a status bar on the main frame private GanttStatusBar statusBar; private NewTaskAction myNewTaskAction; private NewHumanAction myNewHumanAction; private NewArtefactAction myNewArtefactAction; /** Constructor */ public GanttProject(String filename, boolean isApplet) { super("Gantt Chart"); setTitle(language.getText("appliTitle")); lookAndFeel = GanttLookAndFeels.getGanttLookAndFeels().getDefaultInfo(); options = new GanttOptions(getRoleManager()); //Color color = GanttGraphicArea.taskDefaultColor; options.setUIConfiguration(myUIConfiguration); options.setDocumentsMRU(documentsMRU); options.setLookAndFeel(lookAndFeel); if (options.load()) { language = options.getLanguage(); GanttGraphicArea.taskDefaultColor = options.getDefaultColor(); lookAndFeel = options.getLnfInfos(); HttpDocument.setLockDAVMinutes(options.getLockDAVMinutes()); } myUIConfiguration = options.getUIConfiguration(); TaskManagerConfig taskConfig = new TaskManagerConfig() { public Color getDefaultColor() { return myUIConfiguration.getTaskColor(); } }; myTaskManager = TaskManager.Access.newInstance(new TaskContainmentHierarchyFacade.Factory() { public TaskContainmentHierarchyFacade createFacede() { if (!GanttProject.this.myFacadeInvalidator.isValid() || myCachedFacade==null) { myCachedFacade = new TaskContainmentHierarchyFacadeImpl(tree); GanttProject.this.myFacadeInvalidator.reset(); } return myCachedFacade; } private TaskContainmentHierarchyFacadeImpl myCachedFacade; }, taskConfig); this.isApplet = isApplet; ImageIcon icon = new ImageIcon(getClass().getResource( "/icons/ganttproject.png")); setIconImage(icon.getImage()); //Create each objects tree = new GanttTree(this, myTaskManager); myFacadeInvalidator = new FacadeInvalidator(tree.getJTree().getModel()); area = new GanttGraphicArea(this, tree, getTaskManager(), myUIConfiguration); GanttImagePanel but = new GanttImagePanel("big.png", "tasks.png",300, 42); tree.setGraphicArea(area); //Create the menus JMenuBar bar = new JMenuBar(); setJMenuBar(bar); //Allocation of the menus mProject = new JMenu(); mMRU = new JMenu(); mMRU.setIcon(new ImageIcon(getClass().getResource("/icons/recent_16.gif"))); mEdit = new JMenu(); mTask = new JMenu(); mHuman = new JMenu(); mHelp = new JMenu(); mCalendar = new JMenu(); mServer = new JMenu(); mServer.setIcon(new ImageIcon(getClass().getResource("/icons/server_16.gif"))); miNew = createNewItem("/icons/new_16.gif"); mProject.add(miNew); miOpen = createNewItem("/icons/open_16.gif"); mProject.add(miOpen); mProject.add(mMRU); updateMenuMRU(); mProject.addSeparator(); miSave = createNewItem("/icons/save_16.gif"); miSave.setEnabled(false); mProject.add(miSave); miSaveAs = createNewItem("/icons/saveas_16.gif"); mProject.add(miSaveAs); mProject.addSeparator(); miImport = createNewItem("/icons/import_16.gif"); mProject.add(miImport); miExport = createNewItem("/icons/export_16.gif"); mProject.add(miExport); mProject.addSeparator(); miOpenURL = createNewItem(""); miSaveAsURL = createNewItem(""); mServer.add(miOpenURL); mServer.add(miSaveAsURL); mProject.add(mServer); mProject.addSeparator(); miPrint = createNewItem("/icons/print_16.gif"); mProject.add(miPrint); miPreview = createNewItem("/icons/preview_16.gif"); mProject.add(miPreview); mProject.addSeparator(); miQuit = createNewItem(""/*"/icons/exit_16.gif"*/); mProject.add(miQuit); miCut = createNewItem("/icons/cut_16.gif"); mEdit.add(miCut); miCopy = createNewItem("/icons/copy_16.gif"); mEdit.add(miCopy); miPaste = createNewItem("/icons/paste_16.gif"); mEdit.add(miPaste); mEdit.addSeparator(); miOptions = createNewItem("/icons/settings_16.gif"); mEdit.add(miOptions); myNewTaskAction = new NewTaskAction((IGanttProject)this); mTask.add(myNewTaskAction); miDeleteTask = createNewItem("/icons/delete_16.gif"); mTask.add(miDeleteTask); miPropertiesTask = createNewItem("/icons/properties_16.gif"); mTask.add(miPropertiesTask); // // myNewHumanAction = new NewHumanAction(getHumanResourceManager(), getRoleManager(), this); mHuman.add(myNewHumanAction); miDelHuman = new JMenuItem(new DeleteHumanAction(getHumanResourceManager(), (ResourceContext) getResourcePanel(), this)); mHuman.add(miDelHuman); miPropHuman = createNewItem("/icons/properties_16.gif"); mHuman.add(miPropHuman); miSendMailHuman = createNewItem("/icons/send_mail_16.gif"); mHuman.add(miSendMailHuman); mHuman.add(new ImportResources(getHumanResourceManager(), getTaskManager(), getRoleManager(), this)); miEditCalendar = createNewItem("/icons/clock_16.gif"); mCalendar.add(miEditCalendar); miPrjCal = createNewItem("/icons/default_calendar_16.gif"); mCalendar.add(miPrjCal); miWebPage = createNewItem("/icons/home_16.gif"); mHelp.add(miWebPage); miManual = createNewItem("/icons/help_16.gif"); try { //See if helpgui library is on the classpath Class.forName("net.sourceforge.helpgui.gui.MainFrame").newInstance(); mHelp.add(miManual); miManual.setAccelerator(KeyStroke.getKeyStroke("F1")); } catch (Exception ex) { //Not add the help button on the ui } miTips = createNewItem("/icons/about_16.gif"); mHelp.add(miTips); miAbout = createNewItem("/icons/manual_16.gif"); mHelp.add(miAbout); if (!isApplet) { bar.add(mProject); //for a applet veiwer, Project menu is not neccessary By CL } bar.add(mEdit); bar.add(mTask); bar.add(mHuman); //bar.add(mCalendar); bar.add(mHelp); setMemonic(); //to create a default project //createDefaultTree(tree); JPanel left = new JPanel(new BorderLayout()); left.add(but, BorderLayout.NORTH); left.add(tree, BorderLayout.CENTER); left.setPreferredSize(new Dimension(250, 600)); left.setBackground(Color.white); //A splitpane is use JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); if (language.getComponentOrientation() == ComponentOrientation.LEFT_TO_RIGHT) { splitPane.setLeftComponent(left); splitPane.setRightComponent(area); splitPane.applyComponentOrientation(ComponentOrientation.LEFT_TO_RIGHT); } else { splitPane.setRightComponent(left); splitPane.setLeftComponent(area); splitPane.setDividerLocation((int)(Toolkit.getDefaultToolkit() .getScreenSize().getWidth() - left.getPreferredSize().getWidth())); splitPane.applyComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT); } splitPane.setOneTouchExpandable(true); splitPane.setPreferredSize(new Dimension(800, 500)); //Add Gantt Panel, Human resource pannel and RESOURCE panel tabpane = new JTabbedPane(); tabpane.addTab(language.getText("gantt"), new ImageIcon(getClass().getResource("/icons/tasks_16.gif")), splitPane); tabpane.addTab(language.getText("human"), new ImageIcon(getClass().getResource("/icons/res_16.gif")), getResourcePanel()); tabpane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT); tabpane.addChangeListener(new ChangeListener() { public void stateChanged(ChangeEvent e) { bUnlink.setEnabled(tabpane.getSelectedIndex() == 0); bLink.setEnabled(tabpane.getSelectedIndex() == 0); bInd.setEnabled(tabpane.getSelectedIndex() == 0); bUnind.setEnabled(tabpane.getSelectedIndex() == 0); if (tabpane.getSelectedIndex() == 0) { //Gantt Chart bNewTask.setToolTipText(getToolTip(correctLabel(language.getText("createTask")))); bDelete.setToolTipText(getToolTip(correctLabel(language.getText("deleteTask")))); bProperties.setToolTipText(getToolTip(correctLabel(language.getText("propertiesTask")))); if(options.getButtonShow()!=GanttOptions.ICONS) { bNewTask.setText(correctLabel(language.getText("createTask"))); bDelete.setText(correctLabel(language.getText("deleteTask"))); bProperties.setText(correctLabel(language.getText("propertiesTask"))); } } else if (tabpane.getSelectedIndex() == 1) { //Resources Chart bNewTask.setToolTipText(getToolTip(correctLabel(language.getText("newHuman")))); bDelete.setToolTipText(getToolTip(correctLabel(language.getText("deleteHuman")))); bProperties.setToolTipText(getToolTip(correctLabel(language.getText("propertiesHuman")))); if(options.getButtonShow()!=GanttOptions.ICONS) { bNewTask.setText(correctLabel(language.getText("newHuman"))); bDelete.setText(correctLabel(language.getText("deleteHuman"))); bProperties.setText(correctLabel(language.getText("propertiesHuman"))); } } } }); //Add tabpan on the content pane getContentPane().add(tabpane, BorderLayout.CENTER); //Add toolbar toolBar = new JToolBar("GanttProject", options.getToolBarPosition()); toolBar.setBorderPainted(true); toolBar.setRollover(true); toolBar.setFloatable(true); this.addButtons(toolBar); getContentPane().add(toolBar, (toolBar.getOrientation()==JToolBar.HORIZONTAL)?BorderLayout.NORTH:BorderLayout.WEST); //add the status bar statusBar = new GanttStatusBar(); getContentPane().add(statusBar,BorderLayout.SOUTH); statusBar.setVisible(options.getShowStatusBar()); //Open the the project passed in argument if (filename != null) { Document document = DocumentCreator.createDocument(filename); try { openDocument(document); } catch (IOException ex) { System.err.println(language.getText("msg2") + "\n" + filename); System.err.println(ex.getMessage()); } } // update 18-03-2003 addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); // update 18-03-2003 setDefaultCloseOperation(DO_NOTHING_ON_CLOSE); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension windowSize = getPreferredSize(); // Put the frame at the middle of the screen setLocation(screenSize.width / 2 - (windowSize.width / 2), screenSize.height / 2 - (windowSize.height / 2)); this.pack(); changeLanguage(); changeLookAndFeel(lookAndFeel); changeLookAndFeel(lookAndFeel); //Twice call for update font on menu if (options.isLoaded()) { setBounds(options.getX(), options.getY(), options.getWidth(), options.getHeight()); } if (options.getOpenTips() && !byCommandLine) { TipsDialog tips = new TipsDialog(this, options.getOpenTips()); tips.show(); tips.toFront(); // somehow assure, that the TipsDialog is the top window an MacOS } applyComponentOrientation(GanttLanguage.getInstance() .getComponentOrientation()); } public GanttProject(String filename) { this(filename, false); } /** * Updates the last open file menu items. */ private void updateMenuMRU() { mMRU.removeAll(); int index = 0; Iterator iterator = documentsMRU.iterator(); while (iterator.hasNext()) { index++; Document document = (Document) iterator.next(); JMenuItem mi = new JMenuItem( new OpenDocumentAction(index, document, this)); mMRU.add(mi); } } public String getXslDir() { return options.getXslDir(); } /** @return the options of ganttproject. */ public GanttOptions getOptions(){ return options; } public void restoreOptions(){ options.initByDefault(); //options by default myUIConfiguration = options.getUIConfiguration(); GanttGraphicArea.taskDefaultColor = new Color( 140, 182, 206); area.repaint(); } /** @return the status Bar of the main frame. */ public GanttStatusBar getStatusBar() { return statusBar; } public String getXslFo() { if (new File(options.getXslFo()).exists()) return options.getXslFo(); return GanttProject.class.getResource("/xslfo/ganttproject.xsl") .toString(); } /** Create memonic for keyboard */ public void setMemonic() { final int MENU_MASK = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask(); //--NEW---------------------------------- //miNew.setMnemonic(KeyEvent.VK_N); miNew.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N, MENU_MASK)); //--OPEN---------------------------------- miOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_O, MENU_MASK)); //Open from the web //miOpenURL.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_I, MENU_MASK)); //--SAVE---------------------------------- miSave.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, MENU_MASK)); //--EXPORT---------------------------------- miExport.setAccelerator(KeyStroke .getKeyStroke(KeyEvent.VK_E, MENU_MASK)); // --IMPORT---------------------------------- miImport.setAccelerator(KeyStroke .getKeyStroke(KeyEvent.VK_I, MENU_MASK)); //--PRINT---------------------------------- miPrint .setAccelerator(KeyStroke .getKeyStroke(KeyEvent.VK_P, MENU_MASK)); //--QUIT---------------------------------- miQuit.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_Q, MENU_MASK)); //--CUT---------------------------------- //miCut.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, // MENU_MASK)); //--COPY---------------------------------- //miCopy.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_C, // MENU_MASK)); //--PASTE---------------------------------- //miPaste.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_V, // MENU_MASK)); //--OPTIONS---------------------------------- miOptions.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_G, MENU_MASK)); //--NEW TASK---------------------------------- // miNewTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T, // MENU_MASK)); //--PROPERTIES TASK---------------------------------- miPropertiesTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_R, MENU_MASK)); //--DELETE TASK---------------------------------- miDeleteTask.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_D, MENU_MASK)); //--NEW HUMAN---------------------------------- //miNewHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_H, MENU_MASK)); //miDelHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_J, MENU_MASK)); miPropHuman.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_L, MENU_MASK)); } /** Create an item with a label */ public JMenuItem createNewItemText(String label) { JMenuItem item = new JMenuItem(label); item.addActionListener(this); return item; } /** Create an item with an icon */ public JMenuItem createNewItem(String icon) { JMenuItem item = new JMenuItem(new ImageIcon(getClass().getResource( icon))); item.addActionListener(this); return item; } /** Create an item with a label and an icon */ public JMenuItem createNewItem(String label, String icon) { JMenuItem item = new JMenuItem(label, new ImageIcon(getClass().getResource(icon))); item.addActionListener(this); return item; } /** Function to change language of the project */ public void changeLanguage() { applyComponentOrientation(language.getComponentOrientation()); changeLanguageOfMenu(); area.repaint(); getResourcePanel().area.repaint(); getResourcePanel().refresh(language); applyComponentOrientation(language.getComponentOrientation()); } /** Change the style of the application */ public void changeLookAndFeel(GanttLookAndFeelInfo lookAndFeel) { try { UIManager.setLookAndFeel(lookAndFeel.getClassName()); SwingUtilities.updateComponentTreeUI(this); this.lookAndFeel = lookAndFeel; } catch (Exception e) { GanttLookAndFeelInfo info = GanttLookAndFeels .getGanttLookAndFeels().getDefaultInfo(); System.out.println("Can't find the LookAndFeel\n" + lookAndFeel.getClassName() + "\n" + lookAndFeel.getName() + "\nSetting the default Look'n'Feel" + info.getName()); try { UIManager.setLookAndFeel(info.getClassName()); SwingUtilities.updateComponentTreeUI(this); this.lookAndFeel = info; } catch (Exception ex) { } } //MetalLookAndFeel.setCurrentTheme(new GanttMetalTheme()); //must force to do that instead of the task on tree are not in // continuity of the calendar tree.getJTree().setRowHeight(20); } //Correct the label of menu without '$' character public static String correctLabel(String label) { int index = label.indexOf('$'); if (index != -1 && label.length() - index > 1) label = label.substring(0, index).concat(label.substring(++index)); return label; } /** Change the label for menu, in fact check in the label contains a mnemonic */ public JMenu changeMenuLabel(JMenu menu, String label) { int index = label.indexOf('$'); if (index != -1 && label.length() - index > 1) { menu.setText(label.substring(0, index).concat(label.substring(++index))); menu.setMnemonic(Character.toLowerCase(label.charAt(index))); } else { menu.setText(label); //menu.setMnemonic(''); } return menu; } /** Change the label for menuItem, in fact check in the label contains a mnemonic */ public JMenuItem changeMenuLabel(JMenuItem menu, String label) { int index = label.indexOf('$'); if (index != -1 && label.length() - index > 1) { menu.setText(label.substring(0, index).concat(label.substring(++index))); menu.setMnemonic(Character.toLowerCase(label.charAt(index))); } else { menu.setText(label); //menu.setMnemonic(''); } return menu; } /** Set the menus language after the user select a different language */ private void changeLanguageOfMenu() { mProject = changeMenuLabel(mProject, language.getText("project")); mEdit = changeMenuLabel(mEdit, language.getText("edit")); mTask = changeMenuLabel(mTask, language.getText("task")); mHuman = changeMenuLabel(mHuman, language.getText("human")); mHelp = changeMenuLabel(mHelp, language.getText("help")); mCalendar = changeMenuLabel(mCalendar, language.getText("calendars")); miNew = changeMenuLabel(miNew, language.getText("newProject")); miOpen = changeMenuLabel(miOpen, language.getText("openProject")); mMRU = changeMenuLabel(mMRU, language.getText("lastOpen")); miSave = changeMenuLabel(miSave, language.getText("saveProject")); miSaveAs = changeMenuLabel(miSaveAs, language.getText("saveAsProject")); mServer = changeMenuLabel(mServer, language.getText("webServer")); miOpenURL = changeMenuLabel(miOpenURL, language.getText("openFromServer")); miSaveAsURL = changeMenuLabel(miSaveAsURL, language.getText("saveToServer")); miExport = changeMenuLabel(miExport, language.getText("export")); miImport = changeMenuLabel(miImport, language.getText("import")); miPrint = changeMenuLabel(miPrint, language.getText("printProject")); miPreview = changeMenuLabel(miPreview, language.getText("preview")); miQuit = changeMenuLabel(miQuit, language.getText("quit")); miCut = changeMenuLabel(miCut, language.getText("cut")); miCopy = changeMenuLabel(miCopy, language.getText("copy")); miPaste = changeMenuLabel(miPaste, language.getText("paste")); miOptions = changeMenuLabel(miOptions, language.getText("settings")); //miNewTask = changeMenuLabel(miNewTask, language.getText("createTask")); miDeleteTask = changeMenuLabel(miDeleteTask, language.getText("deleteTask")); miPropertiesTask = changeMenuLabel(miPropertiesTask, language.getText("propertiesTask")); mHuman.insert(changeMenuLabel(mHuman.getItem(0), language.getText("newHuman")), 0); miDelHuman = changeMenuLabel(miDelHuman, language.getText("deleteHuman")); miPropHuman = changeMenuLabel(miPropHuman, language.getText("propertiesHuman")); mHuman.insert(changeMenuLabel(mHuman.getItem(3), language.getText("importResources")), 3); miSendMailHuman = changeMenuLabel(miSendMailHuman, language.getText("sendMail")); miEditCalendar = changeMenuLabel(miEditCalendar, language.getText("editCalendars")); miPrjCal = changeMenuLabel(miPrjCal, language.getText("projectCalendar")); miWebPage = changeMenuLabel(miWebPage, language.getText("webPage")); miAbout = changeMenuLabel(miAbout, language.getText("about")); miTips = changeMenuLabel(miTips, language.getText("tipsOfTheDay")); miManual = changeMenuLabel(miManual, language.getText("manual")); //////////////////////////////////////////// bNew.setToolTipText(getToolTip(correctLabel(language.getText("newProject")))); bOpen.setToolTipText(getToolTip(correctLabel(language.getText("openProject")))); bSave.setToolTipText(getToolTip(correctLabel(language.getText("saveProject")))); bSaveAs.setToolTipText(getToolTip(correctLabel(language.getText("saveAsProject")))); bPrint.setToolTipText(getToolTip(correctLabel(language.getText("printProject")))); bExport.setToolTipText(getToolTip(correctLabel(language.getText("export")))); bImport.setToolTipText(getToolTip(correctLabel(language.getText("import")))); bNewTask.setToolTipText(getToolTip(correctLabel(language.getText("createTask")))); bDelete.setToolTipText(getToolTip(correctLabel(language.getText("deleteTask")))); bProperties.setToolTipText(getToolTip(correctLabel(language.getText("propertiesTask")))); bUnlink.setToolTipText(getToolTip(correctLabel(language.getText("unlink")))); bLink.setToolTipText(getToolTip(correctLabel(language.getText("link")))); bInd.setToolTipText(getToolTip(correctLabel(language.getText("indentTask")))); bUnind.setToolTipText(getToolTip(correctLabel(language.getText("dedentTask")))); bUp.setToolTipText(getToolTip(correctLabel(language.getText("upTask")))); bDown.setToolTipText(getToolTip(correctLabel(language.getText("downTask")))); bPrev.setToolTipText(getToolTip(correctLabel(language.getText("backDate")))); bNext.setToolTipText(getToolTip(correctLabel(language.getText("forwardDate")))); bZoomIn.setToolTipText(getToolTip(correctLabel(language.getText("zoomIn")))); bZoomOut.setToolTipText(getToolTip(correctLabel(language.getText("zoomOut")))); //bZoomFit.setToolTipText(getToolTip(language.zoomFit())); tabpane.setTitleAt(1, correctLabel(language.getText("human"))); setButtonText(); } /** Return the tooltip in html (with yello bgcolor */ public static String getToolTip(String msg) { return "<html><body bgcolor=#EAEAEA>" + msg + "</body></html>"; } /** Set the text on the buttons.*/ public void setButtonText() { if(options.getButtonShow()==GanttOptions.ICONS) { bNew.setText(""); bOpen.setText(""); bSave.setText(""); bSaveAs.setText(""); bNewTask.setText(""); bImport.setText(""); bExport.setText(""); bPrint.setText(""); bDelete.setText(""); bProperties.setText(""); bUnlink.setText(""); bLink.setText(""); bInd.setText(""); bUnind.setText(""); bUp.setText(""); bDown.setText(""); bPrev.setText(""); bNext.setText(""); bZoomOut.setText(""); bZoomIn.setText(""); } else { bNew.setText(correctLabel(language.getText("newProject"))); bOpen.setText(correctLabel(language.getText("openProject"))); bSave.setText(correctLabel(language.getText("saveProject"))); bSaveAs.setText(correctLabel(language.getText("saveAsProject"))); bImport.setText(correctLabel(language.getText("import"))); bExport.setText(correctLabel(language.getText("export"))); bPrint.setText(correctLabel(language.getText("printProject"))); bNewTask.setText(correctLabel(language.getText( tabpane.getSelectedIndex() == 0?"createTask":"newHuman"))); bDelete.setText(correctLabel(language.getText( tabpane.getSelectedIndex() == 0?"deleteTask":"deleteHuman"))); bProperties.setText(correctLabel(language.getText( tabpane.getSelectedIndex() == 0?"propertiesTask":"propertiesHuman"))); bUnlink.setText(correctLabel(language.getText("unlink"))); bLink.setText(correctLabel(language.getText("link"))); bInd.setText(correctLabel(language.getText("indentTask"))); bUnind.setText(correctLabel(language.getText("dedentTask"))); bUp.setText(correctLabel(language.getText("upTask"))); bDown.setText(correctLabel(language.getText("downTask"))); bPrev.setText(correctLabel(language.getText("backDate"))); bNext.setText(correctLabel(language.getText("forwardDate"))); bZoomOut.setText(correctLabel(language.getText("zoomOut"))); bZoomIn.setText(correctLabel(language.getText("zoomIn"))); } } /** Apply Buttons options. */ public void applyButtonOptions() { setButtonText(); if(options.getButtonShow()==GanttOptions.TEXT){ //remove the icons bNew.setDefaultIcon(null); bOpen.setDefaultIcon(null);bSave.setDefaultIcon(null); bSaveAs.setDefaultIcon(null);bImport.setDefaultIcon(null);bExport.setDefaultIcon(null); bPrint.setDefaultIcon(null);bNewTask.setDefaultIcon(null);bDelete.setDefaultIcon(null); bProperties.setDefaultIcon(null);bUnlink.setDefaultIcon(null); bLink.setDefaultIcon(null);bInd.setDefaultIcon(null); bUnind.setDefaultIcon(null);bUp.setDefaultIcon(null);bDown.setDefaultIcon(null); bPrint.setDefaultIcon(null);bPrev.setDefaultIcon(null);bNext.setDefaultIcon(null); bZoomOut.setDefaultIcon(null);bZoomIn.setDefaultIcon(null); } else { //set the approrpiate icons bNew.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/new_"+options.getIconSize()+".gif"))); bOpen.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/open_"+options.getIconSize()+".gif"))); bSave.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/save_"+options.getIconSize()+".gif"))); bSaveAs.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/saveas_"+options.getIconSize()+".gif"))); bImport.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/import_"+options.getIconSize()+".gif"))); bExport.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/export_"+options.getIconSize()+".gif"))); bPrint.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/print_"+options.getIconSize()+".gif"))); bNewTask.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/insert_"+options.getIconSize()+".gif"))); bDelete.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/delete_"+options.getIconSize()+".gif"))); bProperties.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/properties_"+options.getIconSize()+".gif"))); bUnlink.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/unlink_"+options.getIconSize()+".gif"))); bLink.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/link_"+options.getIconSize()+".gif"))); bInd.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/indent_"+options.getIconSize()+".gif"))); bUnind.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/unindent_"+options.getIconSize()+".gif"))); bUp.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/up_"+options.getIconSize()+".gif"))); bDown.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/down_"+options.getIconSize()+".gif"))); bPrev.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/prev_"+options.getIconSize()+".gif"))); bNext.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/next_"+options.getIconSize()+".gif"))); bZoomOut.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/zoomm_"+options.getIconSize()+".gif"))); bZoomIn.setDefaultIcon(new ImageIcon(getClass().getResource("/icons/zoomp_"+options.getIconSize()+".gif"))); } } /** Create the button on toolbar */ public void addButtons(JToolBar toolBar) { //toolBar.addSeparator(new Dimension(20,0)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bNew = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/new_"+options.getIconSize()+".gif"))); bNew.addActionListener(this); toolBar.add(bNew); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bOpen = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/open_"+options.getIconSize()+".gif"))); bOpen.addActionListener(this); toolBar.add(bOpen); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bSave = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/save_"+options.getIconSize()+".gif"))); bSave.setEnabled(false); bSave.addActionListener(this); toolBar.add(bSave); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bSaveAs = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/saveas_"+options.getIconSize()+".gif"))); bSaveAs.addActionListener(this); toolBar.add(bSaveAs); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bImport = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/import_"+options.getIconSize()+".gif"))); bImport.addActionListener(this); toolBar.add(bImport); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bExport = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/export_"+options.getIconSize()+".gif"))); bExport.addActionListener(this); toolBar.add(bExport); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bPrint = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/print_"+options.getIconSize()+".gif"))); bPrint.addActionListener(this); toolBar.add(bPrint); /////////////////////////////////////////////////////////////////////////////////////////////////////////// toolBar.addSeparator(new Dimension(20,0)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// //bNewTask = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/insert_"+options.getIconSize()+".gif"))); myNewArtefactAction = new NewArtefactAction(new NewArtefactAction.ActiveActionProvider() { public AbstractAction getActiveAction() { return tabpane.getSelectedIndex()==0 ? (AbstractAction)myNewTaskAction : (AbstractAction)myNewHumanAction; } }, options.getIconSize()); bNewTask = new TestGanttRolloverButton(myNewArtefactAction); // bNewTask.addActionListener(new ActionListener() { // public void actionPerformed(ActionEvent e) { // if (tabpane.getSelectedIndex() == 0) {//Gantt Chart // newTask(); // } else if (tabpane.getSelectedIndex() == 1) { //Resource chart // HumanResource people = new HumanResource(); // GanttDialogPerson dp = new GanttDialogPerson( // GanttProject.this, getLanguage(), people); // dp.show(); // if (dp.result()) { // getHumanResourceManager().add(people); // setAskForSave(true); // } // } // } // }); toolBar.add(bNewTask); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bDelete = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/delete_"+options.getIconSize()+".gif"))); bDelete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //deleteTask(); deleteTasks(); } else if (tabpane.getSelectedIndex() == 1) { //Resource chart ProjectResource[] context = getResourcePanel().getContext() .getResources(); if (context.length > 0) { GanttDialogInfo gdi = new GanttDialogInfo( GanttProject.this, GanttDialogInfo.QUESTION, GanttDialogInfo.YES_NO_OPTION, getLanguage() .getText("msg6") + getDisplayName(context) + "??", getLanguage().getText("question")); gdi.show(); if (gdi.res == GanttDialogInfo.YES) { for (int i = 0; i < context.length; i++) { getHumanResourceManager().remove(context[i]); refreshProjectInfos(); } } } } } }); toolBar.add(bDelete); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bProperties = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/properties_"+options.getIconSize()+".gif"))); bProperties.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart propertiesTask(); } else if (tabpane.getSelectedIndex() == 1) { //Resource chart getResourcePanel().propertiesHuman(GanttProject.this); } } }); toolBar.add(bProperties); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bUnlink = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/unlink_"+options.getIconSize()+".gif"))); bUnlink.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart unlinkRelationships(); } } }); toolBar.add(bUnlink); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bLink = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/link_"+options.getIconSize()+".gif"))); bLink.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart linkRelationships(); } } }); toolBar.add(bLink); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bInd = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/indent_"+options.getIconSize()+".gif"))); bInd.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //tree.indentCurrentNode(); tree.indentCurrentNodes(); setAskForSave(true); } } }); toolBar.add(bInd); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bUnind = new TestGanttRolloverButton(new ImageIcon(getClass() .getResource("/icons/unindent_"+options.getIconSize()+".gif"))); bUnind.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //tree.dedentCurrentNode(); tree.dedentCurrentNodes(); setAskForSave(true); } } }); toolBar.add(bUnind); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bUp = new TestGanttRolloverButton(new ImageIcon(getClass().getResource( "/icons/up_"+options.getIconSize()+".gif"))); bUp.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //tree.upCurrentNode(); tree.upCurrentNodes(); setAskForSave(true); } else if (tabpane.getSelectedIndex() == 1) { //Resource chart getResourcePanel().upResource(); setAskForSave(true); getResourcePanel().setPeople(getResourcePanel().getPeople()); getResourcePanel().area.repaint(); } } }); toolBar.add(bUp); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bDown = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/down_"+options.getIconSize()+".gif"))); bDown.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (tabpane.getSelectedIndex() == 0) { //Gantt Chart //tree.downCurrentNode(); tree.downCurrentNodes(); setAskForSave(true); } else if (tabpane.getSelectedIndex() == 1) { //Resource chart getResourcePanel().downResource(); setAskForSave(true); getResourcePanel() .setPeople(getResourcePanel().getPeople()); getResourcePanel().area.repaint(); } } }); toolBar.add(bDown); toolBar.addSeparator(new Dimension(20,0)); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bPrev = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/prev_"+options.getIconSize()+".gif"))); bPrev.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { area.changeDate(false); area.repaint(); getResourcePanel().area.changeDate(false); getResourcePanel().area.repaint(); } }); toolBar.add(bPrev); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bNext = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/next_"+options.getIconSize()+".gif"))); bNext.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { area.changeDate(true); area.repaint(); getResourcePanel().area.changeDate(true); getResourcePanel().area.repaint(); } }); toolBar.add(bNext); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bZoomOut = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/zoomm_"+options.getIconSize()+".gif"))); bZoomOut.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (area.getZoom() < 9) { area.zoomMore(); getResourcePanel().area.zoomMore(); } area.zoomToBegin(); getResourcePanel().area.zoomToBegin(); area.repaint(); getResourcePanel().area.repaint(); bZoomIn.setEnabled(true); bZoomOut.setEnabled(true); if (area.getZoom() == 9) { bZoomOut.setEnabled(false); } } }); toolBar.add(bZoomOut); /////////////////////////////////////////////////////////////////////////////////////////////////////////// bZoomIn = new TestGanttRolloverButton(new ImageIcon(getClass().getResource("/icons/zoomp_"+options.getIconSize()+".gif"))); bZoomIn.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if (area.getZoom() > 0) { area.zoomLess(); getResourcePanel().area.zoomLess(); } area.zoomToBegin(); getResourcePanel().area.zoomToBegin(); area.repaint(); getResourcePanel().area.repaint(); bZoomIn.setEnabled(true); bZoomOut.setEnabled(true); if (area.getZoom() == 0) { bZoomIn.setEnabled(false); } } }); toolBar.add(bZoomIn); /////////////////////////////////////////////////////////////////////////////////////////////////////////// /* * bZoomFit = new JButton (new * ImageIcon(getClass().getResource("/icons/zoomf.gif"))); * bZoomFit.addActionListener(new ActionListener() { public void * actionPerformed(ActionEvent e) { area.fitWholeProject(false); * area.repaint(); } }); toolBar.add(bZoomFit); */ applyButtonOptions(); } private String getDisplayName(ProjectResource[] resources) { if (resources.length == 1) { return resources[0].toString(); } StringBuffer result = new StringBuffer(); for (int i = 0; i < resources.length; i++) { result.append(resources[i].toString()); if (i < resources.length - 1) { result.append(", "); } } return result.toString(); } /** Exit the Application */ private void exitForm(java.awt.event.WindowEvent evt) { quitApplication(); } /** * Check if the project has been modified, before creating a new one or open * another */ private boolean checkCurrentProject() { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_CANCEL_OPTION, language.getText("msg1"), language.getText("warning")); GanttDialogInfo gdiSaveError = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_NO_CANCEL_OPTION, language.getText("msg12"), language.getText("error")); if (askForSave == true) { gdi.show(); if (gdi.res == GanttDialogInfo.CANCEL) return false; if (gdi.res == GanttDialogInfo.YES) { boolean trySave = true; do { try { trySave = false; saveProject(); } catch (Exception e) { System.err.println(e); gdiSaveError.show(); if (gdiSaveError.res == GanttDialogInfo.CANCEL) return false; trySave = (gdiSaveError.res == GanttDialogInfo.YES); } } while (trySave); } } return true; } /** A menu has been activate */ public void actionPerformed(ActionEvent evt) { if (evt.getSource() instanceof JMenuItem) { String arg = evt.getActionCommand(); /////////////////////////////////////////////////////////////////////////////////////////////////////////// if (arg.equals(correctLabel(language.getText("newProject")))) { newProject(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("openProject")))) { try { if (checkCurrentProject()) { openFile(); } } catch (Exception e) { e.printStackTrace(); if (isVisible()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg8"), language .getText("error")); gdi.show(); } else System.out.println("\n====" + language.getText("error") + "====\n" + language.getText("msg8") + "\n"); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("openFromServer")))) { if (checkCurrentProject()) { openURL(); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("saveProject")))) { try { saveProject(); } catch (Exception e) { System.err.println(e); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg .equals(correctLabel(language.getText("saveAsProject")))) { try { saveAsProject(); } catch (Exception e) { System.err.println(e); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("saveToServer")))) { try { saveAsURLProject(); } catch (Exception e) { System.err.println(e); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("export")))) { export(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("import")))) { importcbk(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("printProject")))) { printProject(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("preview")))) { previewPrint(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("quit")))) { quitApplication(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("deleteTask")))) { deleteTasks(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg .equals(correctLabel(language.getText("propertiesTask")))) { propertiesTask(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("upTask")))) { tree.upCurrentNodes(); setAskForSave(true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("downTask")))) { tree.downCurrentNodes(); setAskForSave(true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("indentTask")))) { tree.indentCurrentNodes(); setAskForSave(true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("dedentTask")))) { tree.dedentCurrentNodes(); setAskForSave(true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("unlink")))) { unlinkRelationships(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("link")))) { linkRelationships(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language .getText("propertiesHuman")))) { tabpane.setSelectedIndex(1); getResourcePanel().propertiesHuman(this); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg .equals(correctLabel(language.getText("editCalendars")))) { GanttDialogCalendar dialogCalendar = new GanttDialogCalendar( this); dialogCalendar.show(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language .getText("projectCalendar")))) { System.out.println("Project calendar"); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("webPage")))) { try { openWebPage(); } catch (Exception e) { System.err.println(e); } } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("tipsOfTheDay")))) { TipsDialog tips = new TipsDialog(this, options.getOpenTips()); tips.show(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("manual")))) { if (helpFrame == null) { try { helpFrame = new net.sourceforge.helpgui.gui.MainFrame( "/docs/help/", "eclipse"); helpFrame.setTitle("GanttProject Manual"); ImageIcon icon = new ImageIcon(getClass().getResource( "/icons/ganttproject.png")); helpFrame.setIconImage(icon.getImage()); } catch (Exception e) { } } helpFrame.setVisible(true); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("about")))) { //old dialog box /*AboutGanttProject agp = new AboutGanttProject(this); agp.show();*/ //new dialog box AboutDialog agp = new AboutDialog(this); agp.show(); } /////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("sendMail")))) { tabpane.setSelectedIndex(1); getResourcePanel().sendMail(this); } //Newly added code /CL //////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("cut")))) { Task t = tree.getSelectedTask(); if (t != null) { tree.cutSelectedNode(); setAskForSave(true); } } //////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("copy")))) { tree.copySelectedNode(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("paste")))) { tree.pasteNode(); setAskForSave(true); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// else if (arg.equals(correctLabel(language.getText("settings")))) { launchOptionsDialog(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //Test if it's a file name } else if (evt.getSource() instanceof Document) { if (checkCurrentProject()) openStartupDocument((Document) evt.getSource()); } //////////////////////////////////////////////////////////////////////////////////////////////////////////// //Test if it's buttons actions else if( evt.getSource() instanceof JButton) { if(evt.getSource() == bNew) //new newProject(); else if(evt.getSource() == bOpen) { //open try { if (checkCurrentProject()) openFile(); } catch (Exception ex) { System.err.println(ex); } } else if(evt.getSource() == bSave) { //save try { saveProject(); } catch (Exception ex) { System.err.println(ex); } } else if(evt.getSource() == bSaveAs) { //saveas try { saveAsProject(); } catch (Exception ex) { System.err.println(ex); } } else if(evt.getSource() == bImport) { //import importcbk(); } else if(evt.getSource() == bExport) { //export export(); } else if(evt.getSource() == bPrint) { //print printProject(); } } } /** Launch the options dialog */ public void launchOptionsDialog() { // old options dialog box /*GanttDialogOptions dialogOptions = new GanttDialogOptions(this, myUIConfiguration); dialogOptions.show(); if (dialogOptions.change) { setAskForSave(true); }*/ // new options dialog box statusBar.setFirstText(language.getText("settingsPreferences"),2000); SettingsDialog dialogOptions = new SettingsDialog(this); dialogOptions.show(); area.repaint(); } /** Create a new task */ public Task newTask() { tabpane.setSelectedIndex(0); GanttTask current = tree.getSelectedTask(); GanttCalendar cal = new GanttCalendar(); if (tree.hasTasks()) cal = new GanttCalendar(area.beg); DefaultMutableTreeNode node = null; GanttLanguage lang = GanttLanguage.getInstance(); String nameOfTask = options.getTaskNamePrefix(); //language.getText("newTask"); if (current != null) { current.setMilestone(false); node = tree.getSelectedNode(); cal = current.getStart(); nameOfTask = current.toString(); } GanttTask task = getTaskManager().createTask(); task.setStart(cal); task.setLength(1); getTaskManager().registerTask(task);//create a new task in the tab // paneneed to register it task.setName(nameOfTask + "_" + task.getTaskID()); task.setColor(area.getTaskColor()); if (current != null) { if (current.colorDefined()) { task.setColor(current.getColor()); } if (current.shapeDefined()) task.setShape(current.getShape()); } DefaultMutableTreeNode taskNode = tree.addObject(task, node); AdjustTaskBoundsAlgorithm alg = getTaskManager() .getAlgorithmCollection().getAdjustTaskBoundsAlgorithm(); alg.run(task); RecalculateTaskCompletionPercentageAlgorithm alg2 = getTaskManager() .getAlgorithmCollection() .getRecalculateTaskCompletionPercentageAlgorithm(); alg2.run(task); //refresh the differents tasks if (current != null) { tree.refreshAllChild(nameOfTask); // DefaultMutableTreeNode father = tree.getSelectedNode(); // GanttTask taskFather = null; //For refresh all the parent task // while (tree.getNode(task.getTaskID()).isRoot() == false) { // father = tree.getFatherNode(task); // tree.refreshAllChild(father.toString()); // taskFather = (GanttTask) father.getUserObject(); // taskFather.refreshDateAndAdvancement(tree); // father.setUserObject(taskFather); // task = taskFather; // } } area.repaint(); setAskForSave(true); statusBar.setFirstText(language.getText("createNewTask"),1000); if (options.getAutomatic()) { propertiesTask(taskNode); } return task; } /** Delete the currant task */ public void deleteTasks() { tabpane.setSelectedIndex(0); DefaultMutableTreeNode [] cdmtn = tree.getSelectedNodes(); if(cdmtn==null || cdmtn.length==0) { statusBar.setFirstText(language.getText("msg21"),2000); return; } GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.QUESTION, GanttDialogInfo.YES_NO_OPTION, language.getText("msg19"), language.getText("question")); gdi.show(); if (gdi.res == GanttDialogInfo.YES) { for(int i=0;i<cdmtn.length; i++) { if(cdmtn[i] != null) { Task ttask = (Task)(cdmtn[i].getUserObject()); DefaultMutableTreeNode father = tree.getFatherNode(ttask); tree.removeCurrentNode(); if(father!=null) { GanttTask taskFather = (GanttTask) father.getUserObject(); AdjustTaskBoundsAlgorithm alg = getTaskManager() .getAlgorithmCollection().getAdjustTaskBoundsAlgorithm(); alg.run(taskFather); // taskFather.refreshDateAndAdvancement(tree); father.setUserObject(taskFather); } } } refreshProjectInfos(); area.repaint(); getResourcePanel().area.repaint(); setAskForSave(true); } } /** Edit task parameters */ public void propertiesTask() { tabpane.setSelectedIndex(0); propertiesTask(tree.getSelectedNode()); } /** Edit task parameters */ public void propertiesTask(DefaultMutableTreeNode node) { if (node == null || node.isRoot()) { statusBar.setFirstText(language.getText("msg21"),2000); return; } else { statusBar.setFirstText(language.getText("editingParameters"),2000); GanttTask t = (GanttTask) (node.getUserObject()); GanttDialogProperties pd = new GanttDialogProperties(this, tree, managerHash, t, area); pd.show(); if (pd.change) { setAskForSave(true); } } } /** Unlink the relationships of the selected task */ public void unlinkRelationships() { tabpane.setSelectedIndex(0); DefaultMutableTreeNode [] cdmtn = tree.getSelectedNodes(); if(cdmtn==null) { statusBar.setFirstText(language.getText("msg21"),2000); return; } for(int i=0;i<cdmtn.length;i++) { if (cdmtn[i] != null && !cdmtn[i].isRoot()) { GanttTask t = (GanttTask)(cdmtn[i].getUserObject()); t.unlink(); } } area.repaint(); setAskForSave(true); } /** Link the selected Tasks */ public void linkRelationships() { tabpane.setSelectedIndex(0); DefaultMutableTreeNode [] cdmtn = tree.getSelectedNodes(); if(cdmtn==null) { statusBar.setFirstText(language.getText("msg21"),2000); return; } if(cdmtn.length<2) { statusBar.setFirstText(language.getText("msg22"),2000); return; } for(int i=0;i<cdmtn.length-1;i++) { if (cdmtn[i]!=null && cdmtn[i+1]!=null) { GanttTask firstTask = (GanttTask)(cdmtn[i].getUserObject());; GanttTask secondTask = (GanttTask)(cdmtn[i+1].getUserObject()); try { getTaskManager().getDependencyCollection().createDependency(secondTask, firstTask); } catch (TaskDependencyException e1) { //e1.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } } area.repaint(); setAskForSave(true); } /** Export the calendar on a png file */ public void export() { ExportFileInfo info = selectExportFile(null); if (!info.equals(ExportFileInfo.EMPTY)) { doExport(info); } } /** Execute the export functions. */ private void doExport(ExportFileInfo info) { switch (info.myFormat) { case ExportFileInfo.FORMAT_HTML : { statusBar.setFirstText(language.getText("htmlexport"),2000); GanttHTMLExport.save(info.myFile, prjInfos, this, tree, area, getResourcePanel().area, info.myStorageOptions); break; } case ExportFileInfo.FORMAT_PNG : { statusBar.setFirstText(language.getText("pnglexport"),2000); String filename = info.myFile.toString(); if (!filename.toUpperCase().endsWith(".PNG")) filename += ".png"; if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //area.fitWholeProject(true); GanttExportSettings bool = info.myStorageOptions; area.export(new File(filename), bool, "png"); } else if (tabpane.getSelectedIndex() == 1) {//Resources GanttExportSettings bool = info.myStorageOptions; // Chart getResourcePanel().area.export(new File(filename), "png", bool); } break; } case ExportFileInfo.FORMAT_JPG : { statusBar.setFirstText(language.getText("jpgexport"),2000); String filename = info.myFile.toString(); if (!filename.toUpperCase().endsWith(".JPG") && !filename.toUpperCase().endsWith(".JPEG")) filename += ".jpg"; if (tabpane.getSelectedIndex() == 0) {//Gantt Chart //area.fitWholeProject(true); GanttExportSettings bool = info.myStorageOptions; area.export(new File(filename), bool, "jpg"); } else if (tabpane.getSelectedIndex() == 1) {//Resources GanttExportSettings bool = info.myStorageOptions; // Chart getResourcePanel().area.export(new File(filename), "jpg", bool); } break; } case ExportFileInfo.FORMAT_PDF : { try { Class.forName("org.apache.fop.apps.Driver") .newInstance(); statusBar.setFirstText(language.getText("pdfexport"),2000); String filename = info.myFile.toString(); if (!filename.toUpperCase().endsWith(".PDF")) filename += ".pdf"; GanttPDFExport.save(new File(filename), prjInfos, this, tree, area, getResourcePanel().area, info.myStorageOptions, getXslFo()); } catch (Exception e) { //If not run in console mode if (isVisible()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg15"), language .getText("error")); gdi.show(); } //Just show the message into console else System.out.println("\n====" + language.getText("error") + "====\n" + language.getText("msg15") + "\n"); } break; } case ExportFileInfo.FORMAT_XFIG : { // show a message on the status bar statusBar.setFirstText(language.getText("xfigexport"),2000); String filename = info.myFile.toString(); if (!filename.toUpperCase().endsWith(".FIG")) filename += ".fig"; GanttXFIGSaver saver = new GanttXFIGSaver(prjInfos, tree, getResourcePanel(), area); try { saver.save(new FileOutputStream(new File(filename)), version); //saver.save(System.out,version); //temporary write the file on standard output } catch (Exception e){} break; } case ExportFileInfo.FORMAT_CSV : { //show a message on the status bar statusBar.setFirstText(language.getText("csvexport"),2000); String filename = info.myFile.toString(); if (!filename.toUpperCase().endsWith(".CSV")) filename += ".csv"; GanttCSVExport saver = new GanttCSVExport(prjInfos, tree, getResourcePanel(), options.getCSVOptions()); try { saver.save(new FileOutputStream(new File(filename))); //saver.save(System.out); } catch (Exception e){} break; } } } /** Refresh the informations of the project on the status bar. */ public void refreshProjectInfos() { if(tree.nbTasks==0 && resp.nbPeople()==0) statusBar.setSecondText(""); else statusBar.setSecondText(correctLabel(language.getText("task"))+" : "+tree.nbTasks+" "+ correctLabel(language.getText("resources"))+" "+resp.nbPeople()); } private ExportFileInfo selectExportFile(FileFilter currentFilter) { ExportFileInfo result = ExportFileInfo.EMPTY; FileFilter figFilter = new GanttXFIGFileFilter(); FileFilter pngFilter = new GanttPNGFileFilter(); FileFilter jpgFilter = new GanttJPGFileFilter(); FileFilter csvFilter = new GanttCSVFilter(); FileFilter pdfFilter = new GanttPDFFileFilter(); FileFilter htmlFilter = new GanttHTMLFileFilter(); JFileChooser fc = new JFileChooser(options.getWorkingDir()); fc.addChoosableFileFilter(figFilter); fc.addChoosableFileFilter(pngFilter); fc.addChoosableFileFilter(jpgFilter); fc.addChoosableFileFilter(csvFilter); fc.addChoosableFileFilter(pdfFilter); fc.addChoosableFileFilter(htmlFilter); if(currentFilter!=null) fc.setFileFilter(currentFilter); //Remove the possibility to use a file filter for all files FileFilter[] filefilters = fc.getChoosableFileFilters(); for(int i=0;i<filefilters.length;i++){ if(filefilters[i]!=figFilter && filefilters[i]!=pngFilter && filefilters[i]!=jpgFilter && filefilters[i]!=csvFilter && filefilters[i]!=pdfFilter && filefilters[i]!=htmlFilter) System.out.println(fc.removeChoosableFileFilter(filefilters[i])); } int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { String filename = fc.getSelectedFile().toString(); FileFilter selectedFilter = fc.getFileFilter(); //if( the file exists, ask for overwriting if(new File(filename).exists()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION, filename+"\n"+language .getText("msg18"), language.getText("warning")); gdi.show(); if (gdi.res == GanttDialogInfo.NO) return selectExportFile(selectedFilter); } int type = -1; if (selectedFilter.equals(htmlFilter)) { type = ExportFileInfo.FORMAT_HTML; if (!fc.getFileFilter().accept(new File(filename))) { filename += ".html"; } } else if (selectedFilter.equals(pngFilter)) { type = ExportFileInfo.FORMAT_PNG; } else if (selectedFilter.equals(jpgFilter)) { type = ExportFileInfo.FORMAT_JPG; } else if (selectedFilter.equals(pdfFilter)) { type = ExportFileInfo.FORMAT_PDF; } else if (selectedFilter.equals(figFilter)) { type = ExportFileInfo.FORMAT_XFIG; } else if (selectedFilter.equals(csvFilter)) { type = ExportFileInfo.FORMAT_CSV; } else { statusBar.setFirstText("Unknown file filter has been selected : "+selectedFilter,2000); throw new RuntimeException( "Unknown file filter has been selected: " + selectedFilter); } changeWorkingDirectory(new File(filename).getParent()); File file = new File(filename); result = new ExportFileInfo(file, type, options.getExportSettings()); } return result; } /** Import function. */ public void importcbk() { // Create a filechooser JFileChooser fc = new JFileChooser(options.getWorkingDir()); FileFilter txtFilter = new GanttTXTFileFilter(); FileFilter ganFilter = new GanttXMLFileFilter(); fc.addChoosableFileFilter(ganFilter); fc.addChoosableFileFilter(txtFilter); // Remove the possibility to use a file filter for all files FileFilter[] filefilters = fc.getChoosableFileFilters(); for(int i=0;i<filefilters.length;i++){ if(filefilters[i]!=txtFilter && filefilters[i]!=ganFilter) fc.removeChoosableFileFilter(filefilters[i]); } int returnVal = fc.showOpenDialog(GanttProject.this); if (returnVal == JFileChooser.APPROVE_OPTION) { //openDocument(new FileDocument(fc.getSelectedFile())); FileFilter selectedFilter = fc.getFileFilter(); //Choose a list of tasks from a txtFile. if (selectedFilter.equals(txtFilter)) { GanttTXTOpen opener = new GanttTXTOpen(tree, this, area, getTaskManager()); boolean bMerge = true; if(projectDocument!=null || askForSave==true) { GanttDialogInfo gdi = new GanttDialogInfo( GanttProject.this, GanttDialogInfo.QUESTION, GanttDialogInfo.YES_NO_OPTION, getLanguage().getText("msg17"), getLanguage().getText("question")); gdi.show(); bMerge = (gdi.res == GanttDialogInfo.YES); } if (bMerge || (!bMerge && checkCurrentProject())) { if(!bMerge) closeProject(); // Open the tasks opener.load(fc.getSelectedFile()); changeWorkingDirectory(fc.getSelectedFile().getParent()); setAskForSave(true); } } else if (selectedFilter.equals(ganFilter)) { //import an entire project inside the current Document document = new FileDocument(fc.getSelectedFile()); try { GanttXMLOpen opener = new GanttXMLOpen(tree, this, getResourcePanel(), area, getTaskManager(),true); ResourceManager hrManager = getHumanResourceManager(); RoleManager roleManager = getRoleManager(); ResourceTagHandler resourceHandler = new ResourceTagHandler( hrManager, roleManager); DependencyTagHandler dependencyHandler = new DependencyTagHandler( opener.getContext(), getTaskManager()); AllocationTagHandler allocationHandler = new AllocationTagHandler( hrManager, getTaskManager()); opener.addTagHandler(opener.getDefaultTagHandler()); //opener.addTagHandler(resourceHandler); //opener.addTagHandler(dependencyHandler); //opener.addTagHandler(allocationHandler); //opener.addParsingListener(dependencyHandler); opener.load(document.getInputStream()); } catch (IOException e) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language.getText("msg2") + "\n" + document.getDescription(), language .getText("error")); gdi.show(); } } } } /** Print the project */ public void printProject() { if (tabpane.getSelectedIndex() == 0) {//Gantt Chart GanttExportSettings bool = new GanttExportSettings(); //GanttDialogExport gde = new GanttDialogExport(this, bool, language); //gde.show(); //if (bool.ok) // area.printProject(bool.name, bool.percent, bool.depend); area.printProject(options.getExportSettings()); } else if (tabpane.getSelectedIndex() == 1) {//Resources Chart getResourcePanel().area.printProject(options.getExportSettings()); } } /** Preview the project before print */ public void previewPrint() { GanttPreviewPrint preview = null; if (tabpane.getSelectedIndex() == 0) {//Gantt Chart preview = new GanttPreviewPrint(this, area.getChart( new GanttExportSettings())); } else if (tabpane.getSelectedIndex() == 1) {//Resources Chart preview = new GanttPreviewPrint(this, getResourcePanel().area .getChart(new GanttExportSettings())); } if (preview != null) preview.setVisible(true); } /** Create a new project */ public void newProject() { if (checkCurrentProject()) { closeProject(); statusBar.setFirstText(language.getText("newProject2"),1500); refreshProjectInfos(); } prjInfos = new PrjInfos(); showNewProjectWizard(); } private void showNewProjectWizard() { NewProjectWizard wizard = new NewProjectWizard(this); wizard.createNewProject(this); } /** * Closes a project. Make sure you have already called checkCurrentProject() * before. * * @see #checkCurrentProject() */ private void closeProject() { //Clear the jtree //refresh graphic area area.repaint(); area.setProjectLevelTaskColor(null); getResourcePanel().area.repaint(); //reset people getResourcePanel().reset(); getHumanResourceManager().clear(); prjInfos = new PrjInfos(); //GanttTask.resetMaxID(); RoleManager.Access.getInstance().clear(); if (null != projectDocument) projectDocument.releaseLock(); projectDocument = null; //change title of the frame this.setTitle(language.getText("appliTitle")); setAskForSave(false); getTaskManager().clear(); tree.clearTree(); } /** Copy GanttGraphicArea parameters to Resource panel area */ public void setResourcePanelToGraphicArea() { getResourcePanel().area.setZoom(area.getZoom()); getResourcePanel().area.setDate(area.getDate()); getResourcePanel().area.repaint(); } /** Open a local project file with dialog box (JFileChooser) */ public void openFile() throws IOException { //Create a filechooser JFileChooser fc = new JFileChooser(options.getWorkingDir()); FileFilter ganttFilter = new GanttXMLFileFilter(); fc.addChoosableFileFilter(ganttFilter); //Remove the possibility to use a file filter for all files FileFilter[] filefilters = fc.getChoosableFileFilters(); for(int i=0;i<filefilters.length;i++){ if(filefilters[i]!=ganttFilter) System.out.println(fc.removeChoosableFileFilter(filefilters[i])); } int returnVal = fc.showOpenDialog(GanttProject.this); if (returnVal == JFileChooser.APPROVE_OPTION) { openDocument(new FileDocument(fc.getSelectedFile())); changeWorkingDirectory(fc.getSelectedFile().getParent()); } } /** Open a remote project file with dialog box (GanttURLChooser) */ public void openURL() { openURL(projectDocument); } /** Open a remote project file with dialog box (GanttURLChooser) */ public void openURL(Document lastDocument) { GanttURLChooser uc = new GanttURLChooser(this, true, (null != lastDocument) ? lastDocument.getURLPath() : null, (null != lastDocument) ? lastDocument.getUsername() : null, (null != lastDocument) ? lastDocument.getPassword() : null); uc.show(); if (uc.change) { Document openDoc; if ((lastDocument instanceof AbstractURLDocument) && uc.fileurl.equals(lastDocument.getURLPath())) { lastDocument.setUserInfo(uc.userName, uc.password); openDoc = lastDocument; } else { openDoc = DocumentCreator.createDocument(uc.fileurl, uc.userName, uc.password); } try { openDocument(openDoc); } catch (IOException e) { if (isVisible()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language.getText("msg11"), language .getText("error")); gdi.show(); } else System.out.println("\n====" + language.getText("error") + "====\n" + language.getText("msg11") + "\n"); openURL(openDoc); } } } private void openDocument(Document document) throws IOException { if (document.getDescription().endsWith(".xml") || document.getDescription().endsWith(".gan")) { InputStream inputStream = document.getInputStream(); closeProject(); boolean locked = document.acquireLock(); if (!locked) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION, language.getText("msg13"), language.getText("warning")); gdi.show(); if (gdi.res == GanttDialogInfo.NO) return; } GanttXMLOpen opener = new GanttXMLOpen(tree, this, getResourcePanel(), area, getTaskManager(),false); ResourceManager hrManager = getHumanResourceManager(); RoleManager roleManager = getRoleManager(); TaskManager taskManager = getTaskManager(); ResourceTagHandler resourceHandler = new ResourceTagHandler( hrManager, roleManager); DependencyTagHandler dependencyHandler = new DependencyTagHandler( opener.getContext(), taskManager); AllocationTagHandler allocationHandler = new AllocationTagHandler( hrManager, getTaskManager()); RoleTagHandler rolesHandler = new RoleTagHandler(roleManager); opener.addTagHandler(opener.getDefaultTagHandler()); opener.addTagHandler(resourceHandler); opener.addTagHandler(dependencyHandler); opener.addTagHandler(allocationHandler); opener.addTagHandler(rolesHandler); opener.addParsingListener(dependencyHandler); opener.addParsingListener(resourceHandler); if (opener.load(document.getInputStream())) { //Add this project to the last opened project if (documentsMRU.add(document)) updateMenuMRU(); if (locked) { projectDocument = document; this.setTitle(language.getText("appliTitle") + " [" + document.getDescription() + "]"); } bZoomIn.setEnabled(area.getZoom() == 0 ? false : true); bZoomOut.setEnabled(area.getZoom() == 9 ? false : true); setResourcePanelToGraphicArea(); setAskForSave(false); statusBar.setFirstText(language.getText("opening") + " "+ document.getPath(),2000); } } else { if (isVisible()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language.getText("msg2") + "\n" + document.getDescription(), language .getText("error")); gdi.show(); } else{ System.out.println("\n====" + language.getText("error") + "====\n" + language.getText("msg2") + "\n"); } } } public void openStartupDocument(String path) { if (path != null) { Document document = DocumentCreator.createDocument(path); openStartupDocument(document); } } public void openStartupDocument(Document document) { try { openDocument(document); } catch (IOException ex) { if (document instanceof AbstractURLDocument) { // if there are problems opening an AbstractURLDocument // (possibly because of bad authentication), // give the user a chance, to enter correct credentials openURL(document); } else { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language.getText("msg2") + "\n" + document.getDescription(), language .getText("error")); gdi.show(); } } } /** * Open a XML stream that represent the file //By CL !@# * * @param ins */ public void openXMLStream(InputStream ins, String path) { try { tree.clearTree(); getResourcePanel().reset(); getHumanResourceManager().clear(); //GanttTask.resetMaxID(); getTaskManager().clear(); RoleManager.Access.getInstance().clear(); GanttXMLOpen opener = new GanttXMLOpen(tree, this, getResourcePanel(), area, getTaskManager(),false); ResourceManager hrManager = getHumanResourceManager(); RoleManager roleManager = getRoleManager(); ResourceTagHandler resourceHandler = new ResourceTagHandler( hrManager, roleManager); DependencyTagHandler dependencyHandler = new DependencyTagHandler( opener.getContext(), getTaskManager()); AllocationTagHandler allocationHandler = new AllocationTagHandler( hrManager, getTaskManager()); opener.addTagHandler(opener.getDefaultTagHandler()); opener.addTagHandler(resourceHandler); opener.addTagHandler(dependencyHandler); opener.addTagHandler(allocationHandler); opener.addParsingListener(dependencyHandler); opener.load(ins); //addProjectFileToLastOpen(projectfile); } catch (Exception ex) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg2") + "\n" + path, language.getText("error")); gdi.show(); } setAskForSave(false); } /** Save the project as (with a dialog file chooser) */ public boolean saveAsProject() throws IOException { JFileChooser fc = new JFileChooser(options.getWorkingDir()); FileFilter ganttFilter = new GanttXMLFileFilter(); fc.addChoosableFileFilter(ganttFilter); //Remove the possibility to use a file filter for all files FileFilter[] filefilters = fc.getChoosableFileFilters(); for(int i=0;i<filefilters.length;i++){ if(filefilters[i]!=ganttFilter) fc.removeChoosableFileFilter(filefilters[i]); } int returnVal = fc.showSaveDialog(GanttProject.this); if (returnVal == JFileChooser.APPROVE_OPTION) { String projectfile = fc.getSelectedFile().toString(); if (!fc.getFileFilter().accept(new File(projectfile))) { if (fc.getFileFilter().accept(new File(projectfile + ".gan"))) { projectfile += ".gan"; } } //if( the file exists, ask for overwriting if(new File(projectfile).exists()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.WARNING, GanttDialogInfo.YES_NO_OPTION, projectfile+"\n"+language .getText("msg18"), language.getText("warning")); gdi.show(); if (gdi.res == GanttDialogInfo.NO) saveAsProject(); } saveProject(new FileDocument(new File(projectfile))); return true; } return false; } /** Save the project on a server (with a GanttURLChooser) */ public boolean saveAsURLProject() throws IOException { return saveAsURLProject(projectDocument); } /** Save the project on a server (with a GanttURLChooser) */ public boolean saveAsURLProject(Document document) throws IOException { GanttURLChooser uc = new GanttURLChooser(this, false, (null != document) ? document.getURLPath() : null, (null != document) ? document.getUsername() : null, (null != document) ? document.getPassword() : null); uc.show(); if (uc.change) { Document saveDocument = null; if (null != document) if (uc.fileurl.equals(document.getURLPath()) && uc.userName.equals(document.getUsername()) && uc.password.equals(document.getPassword())) saveDocument = document; if (null == saveDocument) saveDocument = DocumentCreator.createDocument(uc.fileurl, uc.userName, uc.password); saveProject(saveDocument); return true; } return false; /*ServerDialog sd = new ServerDialog(this); sd.show(); return false;*/ } /** Save the project on a file */ public void saveProject() throws IOException { saveProject(projectDocument); } /** Save the project to the given document, if possible */ public void saveProject(Document document) throws IOException { if (null == document) { saveAsProject(); return; } if (!document.canWrite()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg10"), language.getText("error")); gdi.show(); if (document instanceof AbstractURLDocument) { saveAsURLProject(document); } else { saveAsProject(); } return; } if (!document.acquireLock()) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg14"), language.getText("error")); gdi.show(); if (document instanceof AbstractURLDocument) { saveAsURLProject(document); } else { saveAsProject(); } return; } if (document.getDescription().endsWith(".xml") || document.getDescription().endsWith(".gan")) { GanttXMLSaver saver = new GanttXMLSaver((IGanttProject)this, tree, getResourcePanel(), area); saver.save(document.getOutputStream(), version); statusBar.setFirstText(GanttLanguage.getInstance().getText("saving")+" "+ document.getPath(), 2000); //Add this project to the last opened projects if (documentsMRU.add(document)) updateMenuMRU(); if (projectDocument != document) { if(projectDocument!= null) projectDocument.releaseLock(); projectDocument = document; } } //change title of the window this.setTitle(language.getText("appliTitle") + " [" + document.getDescription() + "]"); String filepath = document.getFilePath(); if (null != filepath) { changeWorkingDirectory(new File(filepath).getParent()); } setAskForSave(false); } public void changeWorkingDirectory(String newWorkDir) { if (null != newWorkDir) options.setWorkingDirectory(newWorkDir); } /** @return the uiconfiguration. */ public UIConfiguration getUIConfiguration() { return myUIConfiguration; } /** Function that launch the dialog to edit project properties */ /* * public void editSettings() { GanttDialogSettings ds = new * GanttDialogSettings(this, language); ds.show(); if (ds.change) { * setAskForSave(ds.change); } } */ /** Quit the application */ public void quitApplication() { options.setWindowPosition(getX(), getY()); options.setWindowSize(getWidth(), getHeight()); options.setUIConfiguration(myUIConfiguration); options.setDocumentsMRU(documentsMRU); options.setLookAndFeel(lookAndFeel); options.setToolBarPosition(toolBar.getOrientation()); options.save(); if (checkCurrentProject()) { closeProject(); setVisible(false); dispose(); System.exit(0); } else { setVisible(true); } } /** Open the web page */ public void openWebPage() throws IOException { if (!BrowserControl.displayURL("http://ganttproject.org/")) { GanttDialogInfo gdi = new GanttDialogInfo(this, GanttDialogInfo.ERROR, GanttDialogInfo.YES_OPTION, language .getText("msg4"), language.getText("error")); gdi.show(); return; } statusBar.setFirstText(GanttLanguage.getInstance().getText("opening")+ " www.ganttproject.org", 2000); } //change by G. Herrmann public void setAskForSave(boolean afs) { String title = getTitle(); //String last = title.substring(title.length() - 11, title.length()); bSave.setEnabled(afs); miSave.setEnabled(afs); askForSave = afs; try { if (System.getProperty("mrj.version") != null) { rootPane.putClientProperty("windowModified", Boolean .valueOf(afs)); // see http://developer.apple.com/qa/qa2001/qa1146.html } else { if (askForSave) { /*if (!last.equals(" (modified)")) { setTitle(getTitle() + " (modified)"); }*/ if (!title.endsWith(" *")) { setTitle(getTitle() + " *"); } } } } catch (AccessControlException e) { // This can happen when running in a sandbox (Java WebStart) System.err.println(e + ": " + e.getMessage()); } } /** Print the help for ganttproject on the system.out */ private static void usage() { System.out.println(); System.out .println("GanttProject usage : java -jar ganttproject-(VERSION).jar <OPTIONS>"); System.out.println(); System.out.println(" Here are the possible options:"); System.out.println(" -h, --help : Print this message"); System.out .println(" [project_file_name] a XML file based on ganttproject format to directly open (project.xml or project.gan)"); System.out .println(" -html [project_file_name] [export_directory_name], export directly a ganttproject file to web pages"); System.out .println(" -xsl-dir [xsl_directory] localisation of the xsl directory for html export"); System.out .println(" -pdf [project_file_name] [pdf_file_name], export directly a ganttproject file to web pages"); System.out .println(" -xsl-fo [xsl_fo_file] localisation of the xsl-fo file for pdf export"); System.out .println(" -csv [project_file_name] [csv_image_filename], export directly a ganttproject file to csv document compatible with spreadsheets"); System.out .println(" -png [project_file_name] [png_image_filename], export directly a ganttproject file to png image"); System.out .println(" -jpg [project_file_name] [jpg_image_filename], export directly a ganttproject file to jpg image"); System.out .println(" -fig/-xfig [project_file_name] [fig_image_filename], export directly a ganttproject file to xfig image"); System.out.println(); System.out .println(" In all these cases the project_file_name can either be a file on local disk or an URL."); System.out .println(" If the URL is password-protected, you can give credentials this way:"); System.out .println(" http://username:password@example.com/filename"); System.out.println(" "); } public GanttResourcePanel getResourcePanel() { if (this.resp == null) { this.resp = new GanttResourcePanel(this, getTree()); this.resp.setResourceActions(getResourceActions()); //TODO pass // resource // actions // created with // resource // panel as // context } return this.resp; } private GanttLanguage getLanguage() { return this.language; } public GanttGraphicArea getArea() { return this.area; } private GanttTree getTree() { return this.tree; } private ResourceActionSet getResourceActions() { if (myResourceActions == null) { myResourceActions = new ResourceActionSet( (IGanttProject)this, (ResourceContext) getResourcePanel(), this); } return myResourceActions; } /** The main */ public static void main(String[] arg) { if (arg.length > 0 && ("-h".equals(arg[0]) || "--help".equals(arg[0]))) { //Help for the command line usage(); System.exit(0); } /* * If -xsl-dir with directory has been provided, use the xsls in this * dir instead of the ones from .ganttproject Can be used in both * interacive and -html/-export modes From Pawel Lipinski. * And set the new path as default. */ GanttOptions options = new GanttOptions(null); for (int i = 0; i < arg.length; i++) { if (arg[i].equals("-xsl-dir") && (arg.length > i + 1)) { options.setXslDir(arg[i + 1]); break; } } for (int i = 0; i < arg.length; i++) { if (arg[i].equals("-xsl-fo") && (arg.length > i + 1)) { options.setXslFo(arg[i + 1]); break; } } if (arg.length > 0 && ("-html".equals(arg[0]) || "-htm".equals(arg[0]) || "-export".equals(arg[0]))) { if (checkProjectFile(arg)) exportProject(arg); System.exit(0); } else if (arg.length > 0 && "-pdf".equals(arg[0])) { if (checkProjectFile(arg)) exportPDF(arg); System.exit(0); } else if (arg.length > 0 && "-png".equals(arg[0])) { if (checkProjectFile(arg)) exportPNG(arg); System.exit(0); } else if (arg.length > 0 && "-jpg".equals(arg[0])) { if (checkProjectFile(arg)) exportJPG(arg); System.exit(0); } else if (arg.length > 0 && ("-fig".equals(arg[0]) || "-xfig".equals(arg[0]))) { if (checkProjectFile(arg)) exportXFIG(arg); System.exit(0); } else if (arg.length > 0 && ("-csv".equals(arg[0]))) { if (checkProjectFile(arg)) exportCSV(arg); System.exit(0); } /* Splash image */ GanttSplash splash = new GanttSplash(); splash.setVisible(true); /** Create main frame */ GanttProject ganttFrame = new GanttProject(null); ganttFrame.setVisible(true); if (arg.length > 0) { ganttFrame.openStartupDocument(arg[0]); } else { //ganttFrame.showNewProjectWizard(); } splash.close(); } static boolean checkProjectFile(String[] arg) { if (!(arg.length > 1)) { System.out.println("ERROR...\nMust pass a project file"); return false; } return true; } /** * Possibility to export the project into HTML directly by command Line From * Dmitry Barashev */ private static void exportProject(String[] args) { try { byCommandLine = true; GanttProject project = new GanttProject(args[1]); String exportPath; if (args.length > 2) exportPath = args[2]; else exportPath = "htmlExport"; File targetDir = new File(exportPath); if (!targetDir.exists()) { targetDir.mkdir(); } else { if (!targetDir.isDirectory()) { throw new RuntimeException("File " + args[2] + " must be directory"); } } System.out.println(targetDir.getAbsolutePath()); String index = project.getProjectName(); if (index == null || index.length() == 0) { index = new String("ganttproject"); } else { index = project.getProjectName().toLowerCase(); } File targetFile = new File(targetDir, index + ".html"); System.err.println(targetFile.getAbsolutePath()); if (!targetFile.exists()) { targetFile.createNewFile(); } ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_HTML, new GanttExportSettings()); project.doExport(info); } catch (IOException e) { throw new RuntimeException("IO error", e); } } /** Possibility to export the project into PDF directly by command Line */ private static void exportPDF(String[] args) { byCommandLine = true; GanttProject project = new GanttProject(args[1]); String exportFile; if (args.length > 2) exportFile = args[2]; else exportFile = "ganttproject.pdf"; File targetFile = new File(exportFile); ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_PDF, new GanttExportSettings()); project.doExport(info); } /** Export directly in PNG image */ private static void exportPNG(String[] args) { byCommandLine = true; GanttProject project = new GanttProject(args[1]); File targetFile = null; if (args.length > 2) targetFile = new File(args[2]); ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_PNG, new GanttExportSettings()); project.doExport(info); } /** Export directly in XFIG image */ private static void exportXFIG(String[] args) { byCommandLine = true; GanttProject project = new GanttProject(args[1]); File targetFile = null; if (args.length > 2) targetFile = new File(args[2]); ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_XFIG, new GanttExportSettings()); project.doExport(info); } /** Export directly in CSV image */ private static void exportCSV(String[] args) { byCommandLine = true; GanttProject project = new GanttProject(args[1]); File targetFile = null; if (args.length > 2) targetFile = new File(args[2]); ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_CSV, new GanttExportSettings()); project.doExport(info); } /** Export directly in JPG image */ private static void exportJPG(String[] args) { byCommandLine = true; GanttProject project = new GanttProject(args[1]); File targetFile = null; if (args.length > 2) targetFile = new File(args[2]); ExportFileInfo info = new ExportFileInfo(targetFile, ExportFileInfo.FORMAT_JPG, new GanttExportSettings()); project.doExport(info); } /** * The class able to export directly by command line From Dmitry Barashev */ private static class ExportFileInfo { public final File myFile; public final int myFormat; public final GanttExportSettings myStorageOptions; public static final int FORMAT_HTML = 1; public static final int FORMAT_PNG = 2; public static final int FORMAT_JPG = 3; public static final int FORMAT_PDF = 4; public static final int FORMAT_XFIG = 5; public static final int FORMAT_CSV = 6; public static final ExportFileInfo EMPTY = new ExportFileInfo(null, -1, null); public ExportFileInfo(File file, int format, GanttExportSettings options) { myFile = file; myFormat = format; myStorageOptions = options; } } private static final String HUMAN_RESOURCE_MANAGER_ID = "HUMAN_RESOURCE"; ///////////////////////////////////////////////////////// // IGanttProject implementation public String getProjectName() { return prjInfos._sProjectName; } public void setProjectName(String projectName) { prjInfos._sProjectName = projectName; setAskForSave(true); } public String getDescription() { return prjInfos.getDescription(); } public void setDescription(String description) { prjInfos._sDescription = description; setAskForSave(true); } public String getOrganization() { return prjInfos.getOrganization(); } public void setOrganization(String organization) { prjInfos._sOrganization = organization; setAskForSave(true); } public String getWebLink() { return prjInfos.getWebLink(); } public void setWebLink(String webLink) { prjInfos._sWebLink = webLink; setAskForSave(true); } public ResourceManager getHumanResourceManager() { ResourceManager result = (ResourceManager) managerHash .get(HUMAN_RESOURCE_MANAGER_ID); if (result == null) { result = new HumanResourceManager(); //result.addView(getPeople()); result.addView(getResourcePanel()); managerHash.put(HUMAN_RESOURCE_MANAGER_ID, result); } return result; } public TaskManager getTaskManager() { return myTaskManager; } public RoleManager getRoleManager() { return RoleManager.Access.getInstance(); } /* (non-Javadoc) * @see net.sourceforge.ganttproject.IGanttProject#getI18n() */ public GanttLanguage getI18n() { return getLanguage(); } }
mmohan01/ReFactory
data/ganttproject/ganttproject-1.10/net/sourceforge/ganttproject/GanttProject.java
Java
mit
104,947
package app import ( "os" "strings" ) type Environment struct { Env string Port string } func (this *App) defaultEnv() Environment { return Environment{ Env: "development", Port: "5000", } } func envMap() map[string]string { environ := os.Environ() env := make(map[string]string) for _, v := range environ { pair := strings.SplitN(v, "=", 2) env[pair[0]] = pair[1] } return env }
chocolat-team/chocolat
app/env.go
GO
mit
407
package play_us.server.resources; import java.net.URLEncoder; import java.util.Arrays; import java.util.List; import org.restlet.resource.ClientResource; import play_us.shared.domain.Track; public class SoundcloudResource { private static final String CLIENT_ID = "3989c2f241c8e4776d091b30d658a6a8"; private static final String CLIENT_SECRET = "1ca36b3d14f05e0e89ddd7da02b090e5"; private static final String uri = "https://api.soundcloud.com"; public List<Track> getTracks(String filter, Integer pagina, Integer canciones) { @SuppressWarnings("deprecation") ClientResource cr = null; Track[] lista = null; cr = new ClientResource(uri + "/tracks.json?client_id="+CLIENT_ID+ "&limit="+canciones+ "offset="+canciones*pagina +"&q="+URLEncoder.encode(filter) +"&filter=downloadable"); lista = cr.get(Track[].class); return Arrays.asList(lista); } }
JuanLSanchez/Play-US
Play-US/Play_US/src/play_us/server/resources/SoundcloudResource.java
Java
mit
896
import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { CemeteryComponent } from './cemetery.component'; describe('CemeteryComponent', () => { let component: CemeteryComponent; let fixture: ComponentFixture<CemeteryComponent>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ CemeteryComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(CemeteryComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should be created', () => { expect(component).toBeTruthy(); }); });
the-reincarnation/tr-recode-ng2
src/app/6soothsayer/cemetery/cemetery.component.spec.ts
TypeScript
mit
646
/* Will change */ .wc-scrollPosition { will-change: scroll-position; } .wc-contents { will-change: contents; } .wc-transform { will-change: transform; } .wc-opacity { will-change: opacity; } .wc-top { will-change: top; } .wc-left { will-change: left; } .wc-bottom { will-change: bottom; } .wc-right { will-change: right; } @media (--breakpoint-1) { .bp1-wc-scrollPosition { will-change: scroll-position; } .bp1-wc-contents { will-change: contents; } .bp1-wc-transform { will-change: transform; } .bp1-wc-opacity { will-change: opacity; } .bp1-wc-top { will-change: top; } .bp1-wc-left { will-change: left; } .bp1-wc-bottom { will-change: bottom; } .bp1-wc-right { will-change: right; } } @media (--breakpoint-2) { .bp2-wc-scrollPosition { will-change: scroll-position; } .bp2-wc-contents { will-change: contents; } .bp2-wc-transform { will-change: transform; } .bp2-wc-opacity { will-change: opacity; } .bp2-wc-top { will-change: top; } .bp2-wc-left { will-change: left; } .bp2-wc-bottom { will-change: bottom; } .bp2-wc-right { will-change: right; } } @media (--breakpoint-3) { .bp3-wc-scrollPosition { will-change: scroll-position; } .bp3-wc-contents { will-change: contents; } .bp3-wc-transform { will-change: transform; } .bp3-wc-opacity { will-change: opacity; } .bp3-wc-top { will-change: top; } .bp3-wc-left { will-change: left; } .bp3-wc-bottom { will-change: bottom; } .bp3-wc-right { will-change: right; } } @media (--breakpoint-4) { .bp4-wc-scrollPosition { will-change: scroll-position; } .bp4-wc-contents { will-change: contents; } .bp4-wc-transform { will-change: transform; } .bp4-wc-opacity { will-change: opacity; } .bp4-wc-top { will-change: top; } .bp4-wc-left { will-change: left; } .bp4-wc-bottom { will-change: bottom; } .bp4-wc-right { will-change: right; } }
modulz/modulz-css
src/css/utilities/will-change.css
CSS
mit
2,236
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = clean; var _path = require('path'); var _del = require('del'); var _del2 = _interopRequireDefault(_del); var _config = require('../config'); var _config2 = _interopRequireDefault(_config); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function clean(dir) { var dist = (0, _config2.default)(dir).distDir; return (0, _del2.default)((0, _path.resolve)(dir, dist), { force: true }); }
hsavit1/gosofi_webpage
node_modules/next/dist/server/build/clean.js
JavaScript
mit
539
// Code generated by mockery 2.9.4. DO NOT EDIT. package mocks import mock "github.com/stretchr/testify/mock" // XcconfigWriter is an autogenerated mock type for the Writer type type XcconfigWriter struct { mock.Mock } // Write provides a mock function with given fields: content func (_m *XcconfigWriter) Write(content string) (string, error) { ret := _m.Called(content) var r0 string if rf, ok := ret.Get(0).(func(string) string); ok { r0 = rf(content) } else { r0 = ret.Get(0).(string) } var r1 error if rf, ok := ret.Get(1).(func(string) error); ok { r1 = rf(content) } else { r1 = ret.Error(1) } return r0, r1 }
bitrise-io/steps-xcode-test
xcodebuild/mocks/XcconfigWriter.go
GO
mit
643
package wallet import ( "errors" "github.com/NebulousLabs/Sia/crypto" "github.com/NebulousLabs/Sia/encoding" "github.com/NebulousLabs/Sia/modules" "github.com/NebulousLabs/Sia/types" "github.com/NebulousLabs/fastrand" ) const ( // SiagFileExtension is the file extension to be used for siag files SiagFileExtension = ".siakey" // SiagFileHeader is the header for all siag files. Do not change. Because siag was created // early in development, compatibility with siag requires manually handling // the headers and version instead of using the persist package. SiagFileHeader = "siag" // SiagFileVersion is the version number to be used for siag files SiagFileVersion = "1.0" ) var ( errAllDuplicates = errors.New("old wallet has no new seeds") errDuplicateSpendableKey = errors.New("key has already been loaded into the wallet") // ErrInconsistentKeys is the error when keyfiles provided are for different addresses ErrInconsistentKeys = errors.New("keyfiles provided that are for different addresses") // ErrInsufficientKeys is the error when there's not enough keys provided to spend the siafunds ErrInsufficientKeys = errors.New("not enough keys provided to spend the siafunds") // ErrNoKeyfile is the error when no keyfile has been presented ErrNoKeyfile = errors.New("no keyfile has been presented") // ErrUnknownHeader is the error when file contains wrong header ErrUnknownHeader = errors.New("file contains the wrong header") // ErrUnknownVersion is the error when the file has an unknown version number ErrUnknownVersion = errors.New("file has an unknown version number") ) // A siagKeyPair is the struct representation of the bytes that get saved to // disk by siag when a new keyfile is created. type siagKeyPair struct { Header string Version string Index int // should be uint64 - too late now SecretKey crypto.SecretKey UnlockConditions types.UnlockConditions } // savedKey033x is the persist structure that was used to save and load private // keys in versions v0.3.3.x for siad. type savedKey033x struct { SecretKey crypto.SecretKey UnlockConditions types.UnlockConditions Visible bool } // decryptSpendableKeyFile decrypts a spendableKeyFile, returning a // spendableKey. func decryptSpendableKeyFile(masterKey crypto.TwofishKey, uk spendableKeyFile) (sk spendableKey, err error) { // Verify that the decryption key is correct. decryptionKey := uidEncryptionKey(masterKey, uk.UID) err = verifyEncryption(decryptionKey, uk.EncryptionVerification) if err != nil { return } // Decrypt the spendable key and add it to the wallet. encodedKey, err := decryptionKey.DecryptBytes(uk.SpendableKey) if err != nil { return } err = encoding.Unmarshal(encodedKey, &sk) return } // integrateSpendableKey loads a spendableKey into the wallet. func (w *Wallet) integrateSpendableKey(masterKey crypto.TwofishKey, sk spendableKey) { w.keys[sk.UnlockConditions.UnlockHash()] = sk } // loadSpendableKey loads a spendable key into the wallet database. func (w *Wallet) loadSpendableKey(masterKey crypto.TwofishKey, sk spendableKey) error { // Duplication is detected by looking at the set of unlock conditions. If // the wallet is locked, correct deduplication is uncertain. if !w.unlocked { return modules.ErrLockedWallet } // Check for duplicates. _, exists := w.keys[sk.UnlockConditions.UnlockHash()] if exists { return errDuplicateSpendableKey } // TODO: Check that the key is actually spendable. // Create a UID and encryption verification. var skf spendableKeyFile fastrand.Read(skf.UID[:]) encryptionKey := uidEncryptionKey(masterKey, skf.UID) skf.EncryptionVerification = encryptionKey.EncryptBytes(verificationPlaintext) // Encrypt and save the key. skf.SpendableKey = encryptionKey.EncryptBytes(encoding.Marshal(sk)) err := checkMasterKey(w.dbTx, masterKey) if err != nil { return err } var current []spendableKeyFile err = encoding.Unmarshal(w.dbTx.Bucket(bucketWallet).Get(keySpendableKeyFiles), &current) if err != nil { return err } return w.dbTx.Bucket(bucketWallet).Put(keySpendableKeyFiles, encoding.Marshal(append(current, skf))) // w.keys[sk.UnlockConditions.UnlockHash()] = sk -> aids with duplicate // detection, but causes db inconsistency. Rescanning is probably the // solution. } // loadSiagKeys loads a set of siag keyfiles into the wallet, so that the // wallet may spend the siafunds. func (w *Wallet) loadSiagKeys(masterKey crypto.TwofishKey, keyfiles []string) error { // Load the keyfiles from disk. if len(keyfiles) < 1 { return ErrNoKeyfile } skps := make([]siagKeyPair, len(keyfiles)) for i, keyfile := range keyfiles { err := encoding.ReadFile(keyfile, &skps[i]) if err != nil { return err } if skps[i].Header != SiagFileHeader { return ErrUnknownHeader } if skps[i].Version != SiagFileVersion { return ErrUnknownVersion } } // Check that all of the loaded files have the same address, and that there // are enough to create the transaction. baseUnlockHash := skps[0].UnlockConditions.UnlockHash() for _, skp := range skps { if skp.UnlockConditions.UnlockHash() != baseUnlockHash { return ErrInconsistentKeys } } if uint64(len(skps)) < skps[0].UnlockConditions.SignaturesRequired { return ErrInsufficientKeys } // Drop all unneeded keys. skps = skps[0:skps[0].UnlockConditions.SignaturesRequired] // Merge the keys into a single spendableKey and save it to the wallet. var sk spendableKey sk.UnlockConditions = skps[0].UnlockConditions for _, skp := range skps { sk.SecretKeys = append(sk.SecretKeys, skp.SecretKey) } err := w.loadSpendableKey(masterKey, sk) if err != nil { return err } w.integrateSpendableKey(masterKey, sk) return nil } // LoadSiagKeys loads a set of siag-generated keys into the wallet. func (w *Wallet) LoadSiagKeys(masterKey crypto.TwofishKey, keyfiles []string) error { if err := w.tg.Add(); err != nil { return err } defer w.tg.Done() // load the keys and reset the consensus change ID and height in preparation for rescan err := func() error { w.mu.Lock() defer w.mu.Unlock() err := w.loadSiagKeys(masterKey, keyfiles) if err != nil { return err } if err = w.dbTx.DeleteBucket(bucketProcessedTransactions); err != nil { return err } if _, err = w.dbTx.CreateBucket(bucketProcessedTransactions); err != nil { return err } w.unconfirmedProcessedTransactions = nil err = dbPutConsensusChangeID(w.dbTx, modules.ConsensusChangeBeginning) if err != nil { return err } return dbPutConsensusHeight(w.dbTx, 0) }() if err != nil { return err } // rescan the blockchain w.cs.Unsubscribe(w) w.tpool.Unsubscribe(w) done := make(chan struct{}) go w.rescanMessage(done) defer close(done) err = w.cs.ConsensusSetSubscribe(w, modules.ConsensusChangeBeginning, w.tg.StopChan()) if err != nil { return err } w.tpool.TransactionPoolSubscribe(w) return nil } // Load033xWallet loads a v0.3.3.x wallet as an unseeded key, such that the // funds become spendable to the current wallet. func (w *Wallet) Load033xWallet(masterKey crypto.TwofishKey, filepath033x string) error { if err := w.tg.Add(); err != nil { return err } defer w.tg.Done() // load the keys and reset the consensus change ID and height in preparation for rescan err := func() error { w.mu.Lock() defer w.mu.Unlock() var savedKeys []savedKey033x err := encoding.ReadFile(filepath033x, &savedKeys) if err != nil { return err } var seedsLoaded int for _, savedKey := range savedKeys { spendKey := spendableKey{ UnlockConditions: savedKey.UnlockConditions, SecretKeys: []crypto.SecretKey{savedKey.SecretKey}, } err = w.loadSpendableKey(masterKey, spendKey) if err != nil && err != errDuplicateSpendableKey { return err } if err == nil { seedsLoaded++ } w.integrateSpendableKey(masterKey, spendKey) } if seedsLoaded == 0 { return errAllDuplicates } if err = w.dbTx.DeleteBucket(bucketProcessedTransactions); err != nil { return err } if _, err = w.dbTx.CreateBucket(bucketProcessedTransactions); err != nil { return err } w.unconfirmedProcessedTransactions = nil err = dbPutConsensusChangeID(w.dbTx, modules.ConsensusChangeBeginning) if err != nil { return err } return dbPutConsensusHeight(w.dbTx, 0) }() if err != nil { return err } // rescan the blockchain w.cs.Unsubscribe(w) w.tpool.Unsubscribe(w) done := make(chan struct{}) go w.rescanMessage(done) defer close(done) err = w.cs.ConsensusSetSubscribe(w, modules.ConsensusChangeBeginning, w.tg.StopChan()) if err != nil { return err } w.tpool.TransactionPoolSubscribe(w) return nil }
mharkus/Sia
modules/wallet/unseeded.go
GO
mit
8,773
package April2021Leetcode; public class _1328BreakAPalindrome { public static void main(String[] args) { System.out.println(breakPalindrome("abccba")); System.out.println(breakPalindrome("a")); } public static String breakPalindrome(String palindrome) { } }
darshanhs90/Java-InterviewPrep
src/April2021Leetcode/_1328BreakAPalindrome.java
Java
mit
272
<?php /** * Bluz Framework Component * * @copyright Bluz PHP Team * @link https://github.com/bluzphp/framework */ /** * @namespace */ namespace Bluz\View\Helper; use Bluz\Application\Application; use Bluz\Proxy\Layout; return /** * Set or generate <script> code for <head> * * @var Layout $this * @param string $script * @return string|null */ function ($script = null) { if (Application::getInstance()->hasLayout()) { return Layout::headScript($script); } else { // it's just alias to script() call return $this->script($script); } };
9618211/framework
src/View/Helper/HeadScript.php
PHP
mit
648
/* lsSnpPdb.c was originally generated by the autoSql program, which also * generated lsSnpPdb.h and lsSnpPdb.sql. This module links the database and * the RAM representation of objects. */ /* Copyright (C) 2014 The Regents of the University of California * See README in this or parent directory for licensing information. */ #include "common.h" #include "linefile.h" #include "dystring.h" #include "jksql.h" #include "lsSnpPdb.h" /* definitions for structType column */ static char *values_structType[] = {"XRay", "NMR", NULL}; static struct hash *valhash_structType = NULL; void lsSnpPdbStaticLoad(char **row, struct lsSnpPdb *ret) /* Load a row from lsSnpPdb table into ret. The contents of ret will * be replaced at the next call to this function. */ { ret->protId = row[0]; ret->pdbId = row[1]; ret->structType = sqlEnumParse(row[2], values_structType, &valhash_structType); ret->chain = row[3][0]; ret->snpId = row[4]; ret->snpPdbLoc = sqlSigned(row[5]); } struct lsSnpPdb *lsSnpPdbLoad(char **row) /* Load a lsSnpPdb from row fetched with select * from lsSnpPdb * from database. Dispose of this with lsSnpPdbFree(). */ { struct lsSnpPdb *ret; AllocVar(ret); ret->protId = cloneString(row[0]); ret->pdbId = cloneString(row[1]); ret->structType = sqlEnumParse(row[2], values_structType, &valhash_structType); ret->chain = row[3][0]; ret->snpId = cloneString(row[4]); ret->snpPdbLoc = sqlSigned(row[5]); return ret; } struct lsSnpPdb *lsSnpPdbLoadAll(char *fileName) /* Load all lsSnpPdb from a whitespace-separated file. * Dispose of this with lsSnpPdbFreeList(). */ { struct lsSnpPdb *list = NULL, *el; struct lineFile *lf = lineFileOpen(fileName, TRUE); char *row[6]; while (lineFileRow(lf, row)) { el = lsSnpPdbLoad(row); slAddHead(&list, el); } lineFileClose(&lf); slReverse(&list); return list; } struct lsSnpPdb *lsSnpPdbLoadAllByChar(char *fileName, char chopper) /* Load all lsSnpPdb from a chopper separated file. * Dispose of this with lsSnpPdbFreeList(). */ { struct lsSnpPdb *list = NULL, *el; struct lineFile *lf = lineFileOpen(fileName, TRUE); char *row[6]; while (lineFileNextCharRow(lf, chopper, row, ArraySize(row))) { el = lsSnpPdbLoad(row); slAddHead(&list, el); } lineFileClose(&lf); slReverse(&list); return list; } struct lsSnpPdb *lsSnpPdbCommaIn(char **pS, struct lsSnpPdb *ret) /* Create a lsSnpPdb out of a comma separated string. * This will fill in ret if non-null, otherwise will * return a new lsSnpPdb */ { char *s = *pS; if (ret == NULL) AllocVar(ret); ret->protId = sqlStringComma(&s); ret->pdbId = sqlStringComma(&s); ret->structType = sqlEnumComma(&s, values_structType, &valhash_structType); sqlFixedStringComma(&s, &(ret->chain), sizeof(ret->chain)); ret->snpId = sqlStringComma(&s); ret->snpPdbLoc = sqlSignedComma(&s); *pS = s; return ret; } void lsSnpPdbFree(struct lsSnpPdb **pEl) /* Free a single dynamically allocated lsSnpPdb such as created * with lsSnpPdbLoad(). */ { struct lsSnpPdb *el; if ((el = *pEl) == NULL) return; freeMem(el->protId); freeMem(el->pdbId); freeMem(el->snpId); freez(pEl); } void lsSnpPdbFreeList(struct lsSnpPdb **pList) /* Free a list of dynamically allocated lsSnpPdb's */ { struct lsSnpPdb *el, *next; for (el = *pList; el != NULL; el = next) { next = el->next; lsSnpPdbFree(&el); } *pList = NULL; } void lsSnpPdbOutput(struct lsSnpPdb *el, FILE *f, char sep, char lastSep) /* Print out lsSnpPdb. Separate fields with sep. Follow last field with lastSep. */ { if (sep == ',') fputc('"',f); fprintf(f, "%s", el->protId); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->pdbId); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); sqlEnumPrint(f, el->structType, values_structType); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%c", el->chain); if (sep == ',') fputc('"',f); fputc(sep,f); if (sep == ',') fputc('"',f); fprintf(f, "%s", el->snpId); if (sep == ',') fputc('"',f); fputc(sep,f); fprintf(f, "%d", el->snpPdbLoc); fputc(lastSep,f); } /* -------------------------------- End autoSql Generated Code -------------------------------- */
hillerlab/GenomeAlignmentTools
kent/src/hg/lib/lsSnpPdb.c
C
mit
4,222
This document was moved to a [new location](../../user/project/import/index.md).
t-zuehlsdorff/gitlabhq
doc/workflow/importing/README.md
Markdown
mit
82
package br.com.project.checkskills.test.repositories; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import org.apache.log4j.Logger; import org.junit.Test; import br.com.project.checkskills.entities.avaliacao.AvaliacaoCompetenciaEntity; import br.com.project.checkskills.entities.avaliacao.AvaliacaoEntity; import br.com.project.checkskills.entities.dadosbasicos.FuncionarioEntity; import br.com.project.checkskills.repositories.avaliacao.IAvaliacaoRepository; import br.com.project.checkskills.repositories.dadosbasicos.ICompetenciaRepository; import br.com.project.checkskills.repositories.dadosbasicos.IEscalaRepository; import br.com.project.checkskills.repositories.dadosbasicos.IFuncionarioRepository; public class AvalicaoRepositoryTest { private static final Logger LOGGER = Logger .getLogger(AvalicaoRepositoryTest.class); @Inject private IAvaliacaoRepository avaliacaoRepository; @SuppressWarnings("unused") @Inject private ICompetenciaRepository competenciaRepository; @Inject private IEscalaRepository escalaRepository; @Inject private IFuncionarioRepository funcionarioRepository; @Test public void saveAvaliacaoTest(){ List<AvaliacaoCompetenciaEntity> avaliacaoCompetencia = new ArrayList<>(); // avaliacaoCompetencia.add(a1); // avaliacaoCompetencia.add(a2); // avaliacaoCompetencia.add(a3); // avaliacaoCompetencia.add(a4); // avaliacaoCompetencia.add(a5); // avaliacaoCompetencia.add(a6); // FuncionarioEntity avaliado = new FuncionarioEntity(); avaliado = this.funcionarioRepository.findOne(1L); FuncionarioEntity lider = new FuncionarioEntity(); lider = this.funcionarioRepository.findOne(2L); List<FuncionarioEntity> funcionarios = new ArrayList<>(); funcionarios.add(avaliado); funcionarios.add(lider); AvaliacaoEntity entity = new AvaliacaoEntity(); entity.setAvaliacaoCompetencias(avaliacaoCompetencia); this.avaliacaoRepository.save(entity); LOGGER.info(entity); } public IEscalaRepository getEscalaRepository() { return escalaRepository; } public void setEscalaRepository(IEscalaRepository escalaRepository) { this.escalaRepository = escalaRepository; } }
luan-analiseinfo/sistema-avaliacao-competencia
src/test/java/br/com/project/checkskills/test/repositories/AvalicaoRepositoryTest.java
Java
mit
2,331
import { expect } from 'chai'; import { Promise } from 'es6-promise'; import { Db } from 'mongodb'; import { Factory } from '../src/index'; import { hooks } from '../src/hooks'; describe('API spec', function() { const Adapter = Factory(); it('Adapter object API', function() { expect(Adapter).to.have.all.keys('connect', 'close', 'query'); [ Adapter.connect, Adapter.close, Adapter.query, ].forEach(function(func) { expect(func).to.be.ok.and.to.be.a('function'); }); }); it('Query object API', function() { const Query = Factory().query(); expect(Query).to.have.all.keys('insert', 'find', 'findOne', 'deleteOne', 'deleteMany', 'updateOne', 'updateMany'); [ Query.insert, Query.find, Query.findOne, Query.updateOne, Query.updateMany, Query.deleteOne, Query.deleteMany, ].forEach(function(func) { expect(func).to.be.ok.and.to.be.a('function'); }); }); }); describe('Connection behavior', function() { it('should be connected and disconnected', function(done) { const connectedFactory = Factory({ database: 'test', }); connectedFactory.connect().catch(done).then(function(adapter) { expect(adapter.getDatabase()).to.be.instanceof(Db); adapter.close().catch(done).then(done); }); }); }); describe('Create documents', function() { const Adapter = Factory({ database: 'test', }); before(function(done) { Adapter.connect().catch(done).then(function() { done(); }); }); it('should return Promise', function() { const Query = Adapter.query('orm_test'); expect(Query.insert({ key: 'value' }).exec()).to.be.instanceof(Promise); expect(Query.insert([{ key: 'value' }, { key: 'value' }]).exec()).to.be.instanceof(Promise); }); }); describe('Read documents', function() { const Adapter = Factory({ database: 'test', }); before(function(done) { Adapter.connect().catch(done).then(function() { done(); }); }); it('should return Promise and be equal inserted data', function(done) { const Query = Adapter.query('orm_test'); Promise.resolve(null) .then(function() { return Query.find({ key: 'value' }).exec().then(function(data) { expect(data.slice).to.be.ok.and.to.be.a('function'); expect(data[0].key).to.be.ok.and.to.be.eql('value'); }); }) .then(function() { Query.findOne({ key: 'value' }).exec().then(function(data) { expect(data.key).to.be.ok.and.to.be.eql('value'); Adapter.close(); done(); }); }); }); }); describe('Update documents', function(done) { const Adapter = Factory({ database: 'test', }); before(function(done) { Adapter.connect().catch(done).then(function() { done(); }); }); it('should return Promise and data must be updated', function(done) { const Query = Adapter.query('orm_test'); Promise.resolve(null).then(function() { return Query.updateMany({ key: 'value', }, { $set: { param: 'value', } }).exec().then(function(data) { expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0); }); }).then(function() { return Query.updateOne({ key: 'value', }, { $set: { only: 'value', } }).exec().then(function(data) { expect(data.modifiedCount).to.be.ok.and.to.be.not.equal(0); Adapter.close(); done(); }); }); }); }); describe('Delete documents', function(done) { const Adapter = Factory({ database: 'test', }); before(function(done) { Adapter.connect().catch(done).then(function() { done(); }); }); it('should return Promise and data must be deleted', function(done) { const Query = Adapter.query('orm_test'); Promise.resolve(null) .then(function() { const result = Query.deleteOne({ key: 'value', }).exec().then(function(data) { expect(data.deletedCount).to.be.ok.and.to.be.eql(1); expect(result).to.be.instanceof(Promise); }); }).then(function() { const result = Query.deleteMany({ key: 'value', }).exec().then(function(data) { expect(data.deletedCount).to.be.ok.and.to.be.eql(2); expect(result).to.be.instanceof(Promise); Adapter.close(); done(); }); }); }); }); describe('Hooks test', function() { const Adapter = Factory({ database: 'test', }); before(function(done) { Adapter.connect().catch(done).then(function() { done(); }); }); it('Hooks should process passing data', function(done) { const Query = Adapter.query('orm_test'); hooks.registerBeforeHook('insert', function(value) { value.before = 'before'; return value; }); hooks.registerAfterHook('insert', function(value) { return value.insertedCount; }); hooks.registerBeforeHook('find', function(value) { value.key = 'value'; return value; }); hooks.registerAfterHook('find', function(value) { value.after = 'after'; return value; }); Query.insert({ key: 'value', }).exec().then(function(data) { expect(data).to.be.ok.and.to.be.eql(1); }); Query.findOne({}).exec().then(function(data) { expect(data.key).to.be.ok.and.to.be.eql('value'); expect(data.before).to.be.ok.and.to.be.eql('before'); expect(data.after).to.be.ok.and.to.be.eql('after'); clearHooks('insert'); clearHooks('find') }); Query.deleteMany({ key: 'value', }).exec().then(function(data) { Adapter.close(); done(); }); }); });
zoilorys/jupiter-orm-mongo
test/index.js
JavaScript
mit
5,847
// ---------------------------------------------------------------------------- PCH #include "app/rdo_studio/pch/editor_pch.h" // ----------------------------------------------------------------------- INCLUDES #include <boost/algorithm/string.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "app/rdo_studio/src/editor/parser_edit.h" #include "app/rdo_studio/res/scintilla/ac_function.xpm" #include "app/rdo_studio/res/scintilla/ac_data.xpm" #include "app/rdo_studio/res/scintilla/ac_trace.xpm" #include "thirdparty/scintilla/include/SciLexer.h" // -------------------------------------------------------------------------------- using namespace rdo::gui::editor; using namespace rdo::gui::style; Parser::Parser(QWidget* pParent) : super(pParent) , kw0("$Activities?0 $Back_picture?0 $Body?0 $Changes?0 $Compare_tops?0 $Condition?0 \ $Constant?0 $Decision_point?0 $Default?0 $End?0 $End_picture?0 $Evaluate_by?0 $Frame?0 $Function?0 \ $Include?0 $Multithreading?0 $multithreading?0 $Operations?0 $Parameters?0 $Fuzzy_Parameters?0 Term?0 $Pattern?0 $Process?0 $Relevant_resources?0 $Resource_type?0 \ $Resources?0 $Result_values?0 $Results?0 $Sequence?0 $Status?0 $Term_condition?0 $Time?0 $Tracing?0 \ $Type?0 $Watching?0 active?0 AExpCalcCounter?0 after?0 algorithmic?0 all?0 and?0 Animation?0 array?0 before?0 \ BExpCalcCounter?0 bitmap?0 Break_point?0 by_hist?0 Choice?0 Convert_begin?0 \ Convert_end?0 Convert_event?0 Convert_rule?0 Create?0 circle?0 ellipse?0 enumerative?0 Erase?0 EventCount?0 \ exponential?0 first?0 Frame_file?0 Frame_number?0 from?0 get_value?0 Get_value?0 integer?0 \ event?0 Keep?0 keyboard?0 line?0 list?0 longint?0 Model_name?0 Monitor?0 NO?0 Planning?0 Stopping?0 \ NoChange?0 NoCheck?0 NonExist?0 normal?0 NoShow?0 operation?0 \ OperRuleCheckCounter?0 OprIev_file?0 or?0 permanent?0 r_rect?0 real?0 enum?0 rect?0 Resource_file?0 \ Results_file?0 rule?0 Run_file?0 Run_StartTime?0 s_bmp?0 search?0 Seconds?0 selected?0 \ ADVANCE?0 SEIZE?0 RELEASE?0 GENERATE?0 QUEUE?0 DEPART?0 ASSIGN?0 TERMINATE?0 \ set?0 Show_mode?0 Show_rate?0 some?0 Statistic_file?0 such_as?0 table?0 temporary?0 \ Terminate_if?0 text?0 Time_now?0 Trace_EndTime?2 Trace_file?2 Trace_StartTime?2 triang?0 triangular?0 \ uniform?0 until?0 value?0 watch_par?0 watch_quant?0 watch_state?0 watch_value?0 with_max?0 \ with_min?0 YES?0 Seed?0 ะกะธัั‚ะตะผะฝะพะต_ะฒั€ะตะผั?0 not?0 if?0 else?0 for?0 return?0 break?0 result?0 ruler?0 space?0 string?0 bool?0 true?0 false?0 \ External_Model?0 external_model?0 $Priority?0 $Parent?0 prior?0 cf?0 Terminate_counter?0 typedef?0 $Typedef?0 $Sprite?0") , kw1("Abs?1 ArcCos?1 ArcSin?1 ArcTan?1 Cos?1 Cotan?1 Exist?1 Exp?1 Floor?1 For_All?1 Frac?1 \ GetRelResNumber?1 GetResNumber?1 IAbs?1 IMax?1 IMin?1 Int?1 IntPower?1 Ln?1 Log10?1 Log2?1 LogN?1 Max?1 Min?1 \ Not_Exist?1 Not_For_All?1 Power?1 Round?1 Sin?1 Sqrt?1 Tan?1 Select?1 Size?1 Empty?1") , kw2("no_trace?2 trace?2 trace_all?2 trace_stat?2 trace_tops?2") , kw3("transparent last white black red green blue cyan magenta yellow gray") { sendEditor(SCI_SETLEXER, SCLEX_RDO); sendEditor(SCI_GETLEXER); sendEditorString(SCI_SETPROPERTY, reinterpret_cast<unsigned long>("fold"), "1"); sendEditor(SCI_SETMARGINWIDTHN, 1, 0); sendEditor(SCI_SETSTYLEBITS, 5); sendEditorString(SCI_SETKEYWORDS, 0, Parser::convertToLexer(kw0).c_str()); sendEditorString(SCI_SETKEYWORDS, 1, Parser::convertToLexer(kw1).c_str()); sendEditorString(SCI_SETKEYWORDS, 2, Parser::convertToLexer(kw2).c_str()); sendEditorString(SCI_SETKEYWORDS, 3, Parser::convertToLexer(kw3).c_str()); sendEditor(SCI_REGISTERIMAGE, 0, reinterpret_cast<long>(xpm_ac_function)); sendEditor(SCI_REGISTERIMAGE, 1, reinterpret_cast<unsigned long>(xpm_ac_data)); sendEditor(SCI_REGISTERIMAGE, 2, reinterpret_cast<unsigned long>(xpm_ac_trace)); } Parser::~Parser() {} std::string Parser::getAllKW() const { return rdo::format("%s %s %s %s", kw0.c_str(), kw1.c_str(), kw2.c_str(), kw3.c_str()); } std::string Parser::convertToLexer(const std::string& kw) { std::string s = kw; while (s.find('?') != std::string::npos) { std::string::size_type pos1 = s.find('?'); std::string::size_type pos2 = s.find(' ', pos1); s.erase(pos1, pos2 - pos1); } std::string str_big = boost::algorithm::to_lower_copy(s); return str_big + " " + s; } void Parser::setEditorStyle(ParserStyle* pStyle) { super::setEditorStyle(pStyle); if (!m_pStyle) return; // ---------- // Colors sendEditor(SCI_STYLESETFORE, SCE_RDO_DEFAULT, convertColor(static_cast<ModelStyle*>(m_pStyle)->defaultColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_DEFAULT, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_IDENTIFIER, convertColor(static_cast<ModelStyle*>(m_pStyle)->identifierColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_IDENTIFIER, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_KEYWORD, convertColor(static_cast<ModelStyle*>(m_pStyle)->keywordColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_KEYWORD, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_FUNCTION, convertColor(static_cast<ModelStyle*>(m_pStyle)->functionsColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_FUNCTION, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_TRACE, convertColor(static_cast<ModelStyle*>(m_pStyle)->traceColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_TRACE, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_FRAME_COLOR, convertColor(static_cast<ModelStyle*>(m_pStyle)->colorColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_FRAME_COLOR, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_COMMENT_CPP, convertColor(static_cast<ModelStyle*>(m_pStyle)->commentColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_COMMENT_CPP, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_COMMENT_LINE, convertColor(static_cast<ModelStyle*>(m_pStyle)->commentColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_COMMENT_LINE, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_NUMBER, convertColor(static_cast<ModelStyle*>(m_pStyle)->numberColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_NUMBER, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_STRING, convertColor(static_cast<ModelStyle*>(m_pStyle)->stringColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_STRING, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); sendEditor(SCI_STYLESETFORE, SCE_RDO_OPERATOR, convertColor(static_cast<ModelStyle*>(m_pStyle)->operatorColor)); sendEditor(SCI_STYLESETBACK, SCE_RDO_OPERATOR, convertColor(static_cast<ModelStyle*>(m_pStyle)->backgroundColor)); // ---------- // Styles sendEditor(SCI_STYLESETBOLD , SCE_RDO_DEFAULT, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->defaultStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_DEFAULT, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->defaultStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_DEFAULT, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->defaultStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_IDENTIFIER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->identifierStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_IDENTIFIER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->identifierStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_IDENTIFIER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->identifierStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_KEYWORD, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->keywordStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_KEYWORD, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->keywordStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_KEYWORD, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->keywordStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_FUNCTION, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->functionsStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_FUNCTION, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->functionsStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_FUNCTION, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->functionsStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_TRACE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->traceStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_TRACE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->traceStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_TRACE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->traceStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_FRAME_COLOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->colorStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_FRAME_COLOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->colorStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_FRAME_COLOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->colorStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_COMMENT_CPP, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_COMMENT_CPP, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_COMMENT_CPP, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_COMMENT_LINE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_COMMENT_LINE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_COMMENT_LINE, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->commentStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_NUMBER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->numberStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_NUMBER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->numberStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_NUMBER, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->numberStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_STRING, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->stringStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_STRING, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->stringStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_STRING, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->stringStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); sendEditor(SCI_STYLESETBOLD , SCE_RDO_OPERATOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->operatorStyle) & static_cast<int>(StyleFont::Style::BOLD) ); sendEditor(SCI_STYLESETITALIC , SCE_RDO_OPERATOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->operatorStyle) & static_cast<int>(StyleFont::Style::ITALIC) ); sendEditor(SCI_STYLESETUNDERLINE, SCE_RDO_OPERATOR, static_cast<int>(static_cast<ModelStyle*>(m_pStyle)->operatorStyle) & static_cast<int>(StyleFont::Style::UNDERLINE)); // ---------- // Font Name sendEditorString(SCI_STYLESETFONT, SCE_RDO_DEFAULT, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_IDENTIFIER, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_KEYWORD, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_FUNCTION, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_TRACE, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_FRAME_COLOR, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_COMMENT_CPP, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_COMMENT_LINE, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_NUMBER, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_STRING, m_pStyle->font.name.c_str()); sendEditorString(SCI_STYLESETFONT, SCE_RDO_OPERATOR, m_pStyle->font.name.c_str()); // ---------- // Font Size sendEditor(SCI_STYLESETSIZE, SCE_RDO_DEFAULT, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_IDENTIFIER, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_KEYWORD, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_FUNCTION, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_TRACE, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_FRAME_COLOR, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_COMMENT_CPP, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_COMMENT_LINE, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_NUMBER, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_STRING, m_pStyle->font.size); sendEditor(SCI_STYLESETSIZE, SCE_RDO_OPERATOR, m_pStyle->font.size); } void Parser::replaceCurrent(const QString& str, int changePosValue) const { int pos = changePosValue != -1 ? getCurrentPos() : 0; sendEditorString(SCI_REPLACESEL, str.toStdString()); if (changePosValue != -1) { pos += changePosValue; setCurrentPos(pos); } }
AlexChernov/rdo_studio
app/rdo_studio/src/editor/parser_edit.cpp
C++
mit
15,095
package plugins; /** * This class represents the CaesarsCode1Plugin to change the text with the Caesar's code with a shift precised in the constructor * * @author Damien SAUVALLE, Laurent THIEBAULT, Amรฉlie MULEBECQ, Nicolas SVIRCHEVSKY */ public class CaesarsCodePlugin implements Plugin { protected int shift; public CaesarsCodePlugin() { this.shift = 1; } public CaesarsCodePlugin(int shift) { this.shift = shift; } /** * This function is called when we want to know the label of a Plugin * * @return the description of the Plugin */ @Override public String getDescription() { return "Code Cesar " + this.shift; } /** * This function is called when we want to transform the text with the Caesar's code * * @return the text transformed by the Plugin */ @Override public String doAction(String text) { String response = ""; for (int i = 0; i < text.length(); i++) { char c = text.charAt(i); if (Character.isLetter(c)) { if (Character.isLowerCase(c)) { c = (char) ('a' + (((c - 'a') + this.shift) % 26)); } else { c = (char) ('A' + (((c - 'A') + this.shift) % 26)); } } response = response + c; } return response; } }
lauthieb/plugins
src/main/java/plugins/CaesarsCodePlugin.java
Java
mit
1,411
import { checkTest } from './utils'; var MethodCallTracker = function(env, methodName) { this._env = env; this._methodName = methodName; this._isExpectingNoCalls = false; this._expecteds = []; this._actuals = []; }; MethodCallTracker.prototype = { stubMethod() { if (this._originalMethod) { // Method is already stubbed return; } let env = this._env; let methodName = this._methodName; this._originalMethod = env.getDebugFunction(methodName); env.setDebugFunction(methodName, (message, test) => { let resultOfTest = checkTest(test); this._actuals.push([message, resultOfTest]); }); }, restoreMethod() { if (this._originalMethod) { this._env.setDebugFunction(this._methodName, this._originalMethod); } }, expectCall(message) { this.stubMethod(); this._expecteds.push(message || /.*/); }, expectNoCalls() { this.stubMethod(); this._isExpectingNoCalls = true; }, isExpectingNoCalls() { return this._isExpectingNoCalls; }, isExpectingCalls() { return !this._isExpectingNoCalls && this._expecteds.length; }, assert() { let { assert } = QUnit.config.current; let env = this._env; let methodName = this._methodName; let isExpectingNoCalls = this._isExpectingNoCalls; let expecteds = this._expecteds; let actuals = this._actuals; let o, i; if (!isExpectingNoCalls && expecteds.length === 0 && actuals.length === 0) { return; } if (env.runningProdBuild) { assert.ok(true, `calls to Ember.${methodName} disabled in production builds.`); return; } if (isExpectingNoCalls) { let actualMessages = []; for (i = 0; i < actuals.length; i++) { if (!actuals[i][1]) { actualMessages.push(actuals[i][0]); } } assert.ok( actualMessages.length === 0, `Expected no Ember.${methodName} calls, got ${actuals.length}: ${actualMessages.join(', ')}` ); return; } let expected, actual, match; for (o = 0; o < expecteds.length; o++) { expected = expecteds[o]; for (i = 0; i < actuals.length; i++) { actual = actuals[i]; if (!actual[1]) { if (expected instanceof RegExp) { if (expected.test(actual[0])) { match = actual; break; } } else { if (expected === actual[0]) { match = actual; break; } } } } if (!actual) { assert.ok(false, `Received no Ember.${methodName} calls at all, expecting: ${expected}`); } else if (match && !match[1]) { assert.ok(true, `Received failing Ember.${methodName} call with message: ${match[0]}`); } else if (match && match[1]) { assert.ok( false, `Expected failing Ember.${methodName} call, got succeeding with message: ${match[0]}` ); } else if (actual[1]) { assert.ok( false, `Did not receive failing Ember.${methodName} call matching '${expected}', last was success with '${ actual[0] }'` ); } else if (!actual[1]) { assert.ok( false, `Did not receive failing Ember.${methodName} call matching '${expected}', last was failure with '${ actual[0] }'` ); } } }, }; export default MethodCallTracker;
Gaurav0/ember.js
packages/internal-test-helpers/lib/ember-dev/method-call-tracker.js
JavaScript
mit
3,484
/** * Example on how to use regular NodeJS files, the (module)exports is used */ var config = require('../../index')(); console.log(config.message); // $> node example.js -> "We are in development" // $> NODE_ENV=production node example.js -> "We are in production"
flesler/config-node
examples/js/example.js
JavaScript
mit
270
package pelican /* import ( "fmt" cv "github.com/glycerine/goconvey/convey" "testing" ) func TestKnownHostsSaveAndRestoreWork(t *testing.T) { StopAllDockers() StartDockerImage(DockerHubTestImage) defer StopAllDockers() my_known_hosts_file := "my.known.hosts" CleanupOldKnownHosts(my_known_hosts_file) h := NewKnownHosts(my_known_hosts_file) defer h.Close() pw, err := h.SshAsRootIntoDocker([]string{"cat", "/etc/passwd"}) if err != nil { fmt.Printf("error: '%s', output during SshAsRootIntoDocker(): '%s'\n", err, string(pw)) panic(err) } fmt.Printf("pw seen: '%s'\n", string(pw)) cv.Convey("When NewKnownHosts() is given an existing known_hosts file path, we should restore the previously known hosts set.\n", t, func() { h2 := NewKnownHosts(my_known_hosts_file) defer h2.Close() equal, err := KnownHostsEqual(h, h2) if !equal { fmt.Printf("\n a is '%#v'\n\n b is '%#v'\n\n", h, h2) panic(err) } cv.So(equal, cv.ShouldEqual, true) }) } */
mailgun/pelican-protocol
persist_test.go
GO
mit
987
class Comment < ActiveRecord::Base validates :description, presence: true belongs_to :user belongs_to :commentable, polymorphic: true has_many :votes, as: :voteable def points votes.sum(:value) end end
samanthavholmes/TravelOverflow
app/models/comment.rb
Ruby
mit
220
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EmployeesLiveDemoWithoutMvp { using System; using System.Collections.Generic; public partial class Supplier { [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")] public Supplier() { this.Products = new HashSet<Product>(); } public int SupplierID { get; set; } public string CompanyName { get; set; } public string ContactName { get; set; } public string ContactTitle { get; set; } public string Address { get; set; } public string City { get; set; } public string Region { get; set; } public string PostalCode { get; set; } public string Country { get; set; } public string Phone { get; set; } public string Fax { get; set; } public string HomePage { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")] public virtual ICollection<Product> Products { get; set; } } }
shopOFF/TelerikAcademyCourses
ASP.NET-Web-Forms/15. Live Demo - MVP pattern with Ninject/EmployeesLiveDemo/EmployeesLiveDemoWithoutMvp/Supplier.cs
C#
mit
1,536
--- title: Cut Template Filter linkText: Cut description: Cut Template Filter --- # Cut Template Filter Removes all instances of value provided from the input ## Example ```text {% raw %} {{ TestValue|cut:' ' }} {% endraw %} ```
BlythMeister/Ensconce
docs/templates/filters/cut.md
Markdown
mit
233
<!DOCTYPE html> <html lang="en"> <head> <title>STPBankAccountParams Class Reference</title> <link rel="stylesheet" type="text/css" href="../css/jazzy.css" /> <link rel="stylesheet" type="text/css" href="../css/highlight.css" /> <meta charset="utf-8"> <script src="../js/jquery.min.js" defer></script> <script src="../js/jazzy.js" defer></script> <script src="../js/lunr.min.js" defer></script> <script src="../js/typeahead.jquery.js" defer></script> <script src="../js/jazzy.search.js" defer></script> </head> <body> <a name="//apple_ref/swift/Class/STPBankAccountParams" class="dashAnchor"></a> <a title="STPBankAccountParams Class Reference"></a> <header class="header"> <p class="header-col header-col--primary"> <a class="header-link" href="../../index.html"> Stripe iOS SDKs 21.12.0 </a> </p> <p class="header-col--secondary"> <form role="search" action="../search.json"> <input type="text" placeholder="Search documentation" data-typeahead> </form> </p> <p class="header-col header-col--secondary"> <a class="header-link" href="https://github.com/stripe/stripe-ios"> <img class="header-icon" src="../img/gh.png"/> View on GitHub </a> </p> </header> <p class="breadcrumbs"> <a class="breadcrumb" href="../../index.html">Stripe iOS SDKs</a> <img class="carat" src="../img/carat.png" /> <a class="breadcrumb" href="../index.html">Stripe</a> <img class="carat" src="../img/carat.png" /> STPBankAccountParams Class Reference </p> <div class="content-wrapper"> <nav class="navigation"> <ul class="nav-groups"> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Classes.html">Classes</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet.html">PaymentSheet</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/Configuration.html">โ€“ Configuration</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/PaymentButton.html">โ€“ PaymentButton</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/FlowController.html">โ€“ FlowController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/UserInterfaceStyle.html">โ€“ UserInterfaceStyle</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/SavePaymentMethodOptInBehavior.html">โ€“ SavePaymentMethodOptInBehavior</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/CustomerConfiguration.html">โ€“ CustomerConfiguration</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/ApplePayConfiguration.html">โ€“ ApplePayConfiguration</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/Address.html">โ€“ Address</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/PaymentSheet/BillingDetails.html">โ€“ BillingDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPAPIClient.html">STPAPIClient</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPAUBECSDebitFormView.html">STPAUBECSDebitFormView</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPAddCardViewController.html">STPAddCardViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPAddress.html">STPAddress</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPAppInfo.html">STPAppInfo</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPApplePayContext.html">STPApplePayContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPApplePayContext/PaymentStatus.html">โ€“ PaymentStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPApplePayPaymentOption.html">STPApplePayPaymentOption</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPBankAccount.html">STPBankAccount</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPBankAccountParams.html">STPBankAccountParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPBankSelectionViewController.html">STPBankSelectionViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCard.html">STPCard</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCardBrandUtilities.html">STPCardBrandUtilities</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCardFormView.html">STPCardFormView</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCardFormView/Representable.html">โ€“ Representable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCardParams.html">STPCardParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCardValidator.html">STPCardValidator</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConfirmAlipayOptions.html">STPConfirmAlipayOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConfirmBLIKOptions.html">STPConfirmBLIKOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConfirmCardOptions.html">STPConfirmCardOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConfirmPaymentMethodOptions.html">STPConfirmPaymentMethodOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConfirmWeChatPayOptions.html">STPConfirmWeChatPayOptions</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountAddress.html">STPConnectAccountAddress</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountCompanyParams.html">STPConnectAccountCompanyParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountIndividualParams.html">STPConnectAccountIndividualParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountIndividualVerification.html">STPConnectAccountIndividualVerification</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountParams.html">STPConnectAccountParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPConnectAccountVerificationDocument.html">STPConnectAccountVerificationDocument</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPContactField.html">STPContactField</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCoreScrollViewController.html">STPCoreScrollViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCoreTableViewController.html">STPCoreTableViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCoreViewController.html">STPCoreViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCustomer.html">STPCustomer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCustomerContext.html">STPCustomerContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPCustomerDeserializer.html">STPCustomerDeserializer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPDateOfBirth.html">STPDateOfBirth</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPError.html">STPError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPFPXBank.html">STPFPXBank</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPFakeAddPaymentPassViewController.html">STPFakeAddPaymentPassViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPFile.html">STPFile</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes.html#/c:@M@Stripe@objc(cs)STPFormView">STPFormView</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPImageLibrary.html">STPImageLibrary</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentAction.html">STPIntentAction</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentActionAlipayHandleRedirect.html">STPIntentActionAlipayHandleRedirect</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentActionBoletoDisplayDetails.html">STPIntentActionBoletoDisplayDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentActionOXXODisplayDetails.html">STPIntentActionOXXODisplayDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentActionRedirectToURL.html">STPIntentActionRedirectToURL</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIntentActionWechatPayRedirectToApp.html">STPIntentActionWechatPayRedirectToApp</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPIssuingCardPin.html">STPIssuingCardPin</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPKlarnaLineItem.html">STPKlarnaLineItem</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPMandateCustomerAcceptanceParams.html">STPMandateCustomerAcceptanceParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPMandateDataParams.html">STPMandateDataParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPMandateOnlineParams.html">STPMandateOnlineParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPMultiFormTextField.html">STPMultiFormTextField</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentActivityIndicatorView.html">STPPaymentActivityIndicatorView</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentCardTextField.html">STPPaymentCardTextField</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentCardTextField/Representable.html">โ€“ Representable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentConfiguration.html">STPPaymentConfiguration</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentContext.html">STPPaymentContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentHandler.html">STPPaymentHandler</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntent.html">STPPaymentIntent</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes.html#/c:@M@Stripe@objc(cs)STPPaymentIntentAction">STPPaymentIntentAction</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentLastPaymentError.html">STPPaymentIntentLastPaymentError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentParams.html">STPPaymentIntentParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentShippingDetails.html">STPPaymentIntentShippingDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentShippingDetailsAddress.html">STPPaymentIntentShippingDetailsAddress</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentShippingDetailsAddressParams.html">STPPaymentIntentShippingDetailsAddressParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentIntentShippingDetailsParams.html">STPPaymentIntentShippingDetailsParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethod.html">STPPaymentMethod</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAUBECSDebit.html">STPPaymentMethodAUBECSDebit</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAUBECSDebitParams.html">STPPaymentMethodAUBECSDebitParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAddress.html">STPPaymentMethodAddress</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAfterpayClearpay.html">STPPaymentMethodAfterpayClearpay</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAfterpayClearpayParams.html">STPPaymentMethodAfterpayClearpayParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes.html#/c:@M@Stripe@objc(cs)STPPaymentMethodAlipay">STPPaymentMethodAlipay</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodAlipayParams.html">STPPaymentMethodAlipayParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes.html#/c:@M@Stripe@objc(cs)STPPaymentMethodBLIK">STPPaymentMethodBLIK</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBLIKParams.html">STPPaymentMethodBLIKParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBacsDebit.html">STPPaymentMethodBacsDebit</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBacsDebitParams.html">STPPaymentMethodBacsDebitParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBancontact.html">STPPaymentMethodBancontact</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBancontactParams.html">STPPaymentMethodBancontactParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBillingDetails.html">STPPaymentMethodBillingDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBoleto.html">STPPaymentMethodBoleto</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodBoletoParams.html">STPPaymentMethodBoletoParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCard.html">STPPaymentMethodCard</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardChecks.html">STPPaymentMethodCardChecks</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardNetworks.html">STPPaymentMethodCardNetworks</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardParams.html">STPPaymentMethodCardParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardPresent.html">STPPaymentMethodCardPresent</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardWallet.html">STPPaymentMethodCardWallet</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardWalletMasterpass.html">STPPaymentMethodCardWalletMasterpass</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodCardWalletVisaCheckout.html">STPPaymentMethodCardWalletVisaCheckout</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodEPS.html">STPPaymentMethodEPS</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodEPSParams.html">STPPaymentMethodEPSParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodFPX.html">STPPaymentMethodFPX</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodFPXParams.html">STPPaymentMethodFPXParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodGiropay.html">STPPaymentMethodGiropay</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodGiropayParams.html">STPPaymentMethodGiropayParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodGrabPay.html">STPPaymentMethodGrabPay</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodGrabPayParams.html">STPPaymentMethodGrabPayParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes.html#/c:@M@Stripe@objc(cs)STPPaymentMethodKlarna">STPPaymentMethodKlarna</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodKlarnaParams.html">STPPaymentMethodKlarnaParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodLink.html">STPPaymentMethodLink</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodLinkParams.html">STPPaymentMethodLinkParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodNetBanking.html">STPPaymentMethodNetBanking</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodNetBankingParams.html">STPPaymentMethodNetBankingParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodOXXO.html">STPPaymentMethodOXXO</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodOXXOParams.html">STPPaymentMethodOXXOParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodParams.html">STPPaymentMethodParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodPrzelewy24.html">STPPaymentMethodPrzelewy24</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodPrzelewy24Params.html">STPPaymentMethodPrzelewy24Params</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodSEPADebit.html">STPPaymentMethodSEPADebit</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodSEPADebitParams.html">STPPaymentMethodSEPADebitParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodSofort.html">STPPaymentMethodSofort</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodSofortParams.html">STPPaymentMethodSofortParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodThreeDSecureUsage.html">STPPaymentMethodThreeDSecureUsage</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodUPI.html">STPPaymentMethodUPI</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodUPIParams.html">STPPaymentMethodUPIParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodiDEAL.html">STPPaymentMethodiDEAL</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentMethodiDEALParams.html">STPPaymentMethodiDEALParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentOptionsViewController.html">STPPaymentOptionsViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPaymentResult.html">STPPaymentResult</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPinManagementService.html">STPPinManagementService</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPushProvisioningContext.html">STPPushProvisioningContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPPushProvisioningDetailsParams.html">STPPushProvisioningDetailsParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPRadarSession.html">STPRadarSession</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPRedirectContext.html">STPRedirectContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSetupIntent.html">STPSetupIntent</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSetupIntentConfirmParams.html">STPSetupIntentConfirmParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSetupIntentLastSetupError.html">STPSetupIntentLastSetupError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPShippingAddressViewController.html">STPShippingAddressViewController</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSource.html">STPSource</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceCardDetails.html">STPSourceCardDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceKlarnaDetails.html">STPSourceKlarnaDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceOwner.html">STPSourceOwner</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceParams.html">STPSourceParams</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceReceiver.html">STPSourceReceiver</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceRedirect.html">STPSourceRedirect</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceSEPADebitDetails.html">STPSourceSEPADebitDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceVerification.html">STPSourceVerification</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPSourceWeChatPayDetails.html">STPSourceWeChatPayDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPTheme.html">STPTheme</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSButtonCustomization.html">STPThreeDSButtonCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSCustomizationSettings.html">STPThreeDSCustomizationSettings</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSFooterCustomization.html">STPThreeDSFooterCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSLabelCustomization.html">STPThreeDSLabelCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSNavigationBarCustomization.html">STPThreeDSNavigationBarCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSSelectionCustomization.html">STPThreeDSSelectionCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSTextFieldCustomization.html">STPThreeDSTextFieldCustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPThreeDSUICustomization.html">STPThreeDSUICustomization</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPToken.html">STPToken</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/STPUserInformation.html">STPUserInformation</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/StripeAPI.html">StripeAPI</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/StripeAPI/BillingDetails.html">โ€“ BillingDetails</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Classes/StripeAPI/PaymentMethod.html">โ€“ PaymentMethod</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Enums.html">Enumerations</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/PaymentSheetError.html">PaymentSheetError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/PaymentSheetResult.html">PaymentSheetResult</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPBankAccountHolderType.html">STPBankAccountHolderType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPBankAccountStatus.html">STPBankAccountStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPBankSelectionMethod.html">STPBankSelectionMethod</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPBillingAddressFields.html">STPBillingAddressFields</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPCardBrand.html">STPCardBrand</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPCardErrorCode.html">STPCardErrorCode</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPCardFormViewStyle.html">STPCardFormViewStyle</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPCardFundingType.html">STPCardFundingType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPCardValidationState.html">STPCardValidationState</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPConnectAccountBusinessType.html">STPConnectAccountBusinessType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPErrorCode.html">STPErrorCode</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPFPXBankBrand.html">STPFPXBankBrand</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPFilePurpose.html">STPFilePurpose</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPIntentActionType.html">STPIntentActionType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPKlarnaLineItemType.html">STPKlarnaLineItemType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPKlarnaPaymentMethods.html">STPKlarnaPaymentMethods</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPMandateCustomerAcceptanceType.html">STPMandateCustomerAcceptanceType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentHandlerActionStatus.html">STPPaymentHandlerActionStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentHandlerErrorCode.html">STPPaymentHandlerErrorCode</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentActionType.html">STPPaymentIntentActionType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentCaptureMethod.html">STPPaymentIntentCaptureMethod</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentConfirmationMethod.html">STPPaymentIntentConfirmationMethod</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentLastPaymentErrorType.html">STPPaymentIntentLastPaymentErrorType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentSetupFutureUsage.html">STPPaymentIntentSetupFutureUsage</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentSourceActionType.html">STPPaymentIntentSourceActionType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentIntentStatus.html">STPPaymentIntentStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentMethodCardCheckResult.html">STPPaymentMethodCardCheckResult</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentMethodCardWalletType.html">STPPaymentMethodCardWalletType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentMethodType.html">STPPaymentMethodType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPaymentStatus.html">STPPaymentStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPPinStatus.html">STPPinStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPRedirectContextError.html">STPRedirectContextError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPRedirectContextState.html">STPRedirectContextState</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSetupIntentLastSetupErrorType.html">STPSetupIntentLastSetupErrorType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSetupIntentStatus.html">STPSetupIntentStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSetupIntentUsage.html">STPSetupIntentUsage</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPShippingStatus.html">STPShippingStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPShippingType.html">STPShippingType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceCard3DSecureStatus.html">STPSourceCard3DSecureStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceFlow.html">STPSourceFlow</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceRedirectStatus.html">STPSourceRedirectStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceStatus.html">STPSourceStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceType.html">STPSourceType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceUsage.html">STPSourceUsage</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPSourceVerificationStatus.html">STPSourceVerificationStatus</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPThreeDSButtonTitleStyle.html">STPThreeDSButtonTitleStyle</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPThreeDSCustomizationButtonType.html">STPThreeDSCustomizationButtonType</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Enums/STPTokenType.html">STPTokenType</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Extensions.html">Extensions</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/NSError.html">NSError</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/UINavigationBar.html">UINavigationBar</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Extensions/View.html">View</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Protocols.html">Protocols</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/ApplePayContextDelegate.html">ApplePayContextDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPAPIResponseDecodable.html">STPAPIResponseDecodable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPAUBECSDebitFormViewDelegate.html">STPAUBECSDebitFormViewDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPAddCardViewControllerDelegate.html">STPAddCardViewControllerDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPApplePayContextDelegate.html">STPApplePayContextDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPAuthenticationContext.html">STPAuthenticationContext</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPBackendAPIAdapter.html">STPBackendAPIAdapter</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPBankSelectionViewControllerDelegate.html">STPBankSelectionViewControllerDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPCardFormViewDelegate.html">STPCardFormViewDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPCustomerEphemeralKeyProvider.html">STPCustomerEphemeralKeyProvider</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols.html#/c:@M@Stripe@objc(pl)STPEphemeralKeyProvider">STPEphemeralKeyProvider</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPFormEncodable.html">STPFormEncodable</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPFormTextFieldContainer.html">STPFormTextFieldContainer</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPIssuingCardEphemeralKeyProvider.html">STPIssuingCardEphemeralKeyProvider</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPPaymentCardTextFieldDelegate.html">STPPaymentCardTextFieldDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPPaymentContextDelegate.html">STPPaymentContextDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPPaymentOption.html">STPPaymentOption</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPPaymentOptionsViewControllerDelegate.html">STPPaymentOptionsViewControllerDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPShippingAddressViewControllerDelegate.html">STPShippingAddressViewControllerDelegate</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Protocols/STPSourceProtocol.html">STPSourceProtocol</a> </li> </ul> </li> <li class="nav-group-name"> <a class="nav-group-name-link" href="../Typealiases.html">Type Aliases</a> <ul class="nav-group-tasks"> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe22STPBooleanSuccessBlocka">STPBooleanSuccessBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe26STPCustomerCompletionBlocka">STPCustomerCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe13STPErrorBlocka">STPErrorBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe22STPFileCompletionBlocka">STPFileCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:14StripeApplePay36STPIntentClientSecretCompletionBlocka">STPIntentClientSecretCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe30STPJSONResponseCompletionBlocka">STPJSONResponseCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe51STPPaymentHandlerActionPaymentIntentCompletionBlocka">STPPaymentHandlerActionPaymentIntentCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe49STPPaymentHandlerActionSetupIntentCompletionBlocka">STPPaymentHandlerActionSetupIntentCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe31STPPaymentIntentCompletionBlocka">STPPaymentIntentCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe31STPPaymentMethodCompletionBlocka">STPPaymentMethodCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe32STPPaymentMethodsCompletionBlocka">STPPaymentMethodsCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe21STPPaymentStatusBlocka">STPPaymentStatusBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe21STPPinCompletionBlocka">STPPinCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe30STPRadarSessionCompletionBlocka">STPRadarSessionCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe33STPRedirectContextCompletionBlocka">STPRedirectContextCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe46STPRedirectContextPaymentIntentCompletionBlocka">STPRedirectContextPaymentIntentCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe39STPRedirectContextSourceCompletionBlocka">STPRedirectContextSourceCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe29STPSetupIntentCompletionBlocka">STPSetupIntentCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe33STPShippingMethodsCompletionBlocka">STPShippingMethodsCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe24STPSourceCompletionBlocka">STPSourceCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe32STPSourceProtocolCompletionBlocka">STPSourceProtocolCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:6Stripe23STPTokenCompletionBlocka">STPTokenCompletionBlock</a> </li> <li class="nav-group-task"> <a class="nav-group-task-link" href="../Typealiases.html#/s:14StripeApplePay12STPVoidBlocka">STPVoidBlock</a> </li> </ul> </li> </ul> </nav> <article class="main-content"> <section class="section"> <div class="section-content top-matter"> <h1>STPBankAccountParams</h1> <div class="declaration"> <div class="language"> <pre class="highlight swift"><code><span class="kd">public</span> <span class="kd">class</span> <span class="kt">STPBankAccountParams</span> <span class="p">:</span> <span class="kt">NSObject</span><span class="p">,</span> <span class="kt"><a href="../Protocols/STPFormEncodable.html">STPFormEncodable</a></span></code></pre> </div> </div> <p>Representation of a user&rsquo;s bank account details. You can assemble these with information that your user enters and then create Stripe tokens with them using an STPAPIClient.</p> <div class="aside aside-seealso"> <p class="aside-title">Seealso</p> <a href="https://stripe.com/docs/api#create_bank_account_token">https://stripe.com/docs/api#create_bank_account_token</a> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L23-L126">Show on GitHub</a> </div> </div> </section> <section class="section"> <div class="section-content"> <div class="task-group"> <ul class="item-container"> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountNumber"></a> <a name="//apple_ref/swift/Property/accountNumber" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountNumber">accountNumber</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The account number for the bank account. Currently must be a checking account.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">accountNumber</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L25">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)last4"></a> <a name="//apple_ref/swift/Property/last4" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)last4">last4</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The last 4 digits of the bank account&rsquo;s account number, if it&rsquo;s been set, otherwise nil.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">last4</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span> <span class="p">{</span> <span class="k">get</span> <span class="p">}</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L29-L36">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)routingNumber"></a> <a name="//apple_ref/swift/Property/routingNumber" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)routingNumber">routingNumber</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The routing number for the bank account. This should be the ACH routing number, not the wire routing number.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">routingNumber</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L39">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)country"></a> <a name="//apple_ref/swift/Property/country" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)country">country</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Two-letter ISO code representing the country the bank account is located in.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">country</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L41">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)currency"></a> <a name="//apple_ref/swift/Property/currency" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)currency">currency</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The default currency for the bank account.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">currency</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L43">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountHolderName"></a> <a name="//apple_ref/swift/Property/accountHolderName" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountHolderName">accountHolderName</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The name of the person or business that owns the bank account.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">accountHolderName</span><span class="p">:</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L45">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountHolderType"></a> <a name="//apple_ref/swift/Property/accountHolderType" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(py)accountHolderType">accountHolderType</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>The type of entity that holds the account. Defaults to STPBankAccountHolderTypeIndividual.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">accountHolderType</span><span class="p">:</span> <span class="kt"><a href="../Enums/STPBankAccountHolderType.html">STPBankAccountHolderType</a></span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L48">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(pl)STPFormEncodable(py)additionalAPIParameters"></a> <a name="//apple_ref/swift/Property/additionalAPIParameters" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(pl)STPFormEncodable(py)additionalAPIParameters">additionalAPIParameters</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="k">var</span> <span class="nv">additionalAPIParameters</span><span class="p">:</span> <span class="p">[</span><span class="kt">AnyHashable</span> <span class="p">:</span> <span class="kt">Any</span><span class="p">]</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L22">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(cs)STPBankAccountParams(im)init"></a> <a name="//apple_ref/swift/Method/init()" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(cs)STPBankAccountParams(im)init">init()</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> <p>Initializes an empty STPBankAccountParams.</p> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">public</span> <span class="k">override</span> <span class="nf">init</span><span class="p">()</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L53-L57">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> <div class="task-group"> <div class="task-name-container"> <a name="/STPFormEncodable"></a> <a name="//apple_ref/swift/Section/STPFormEncodable" class="dashAnchor"></a> <div class="section-name-container"> <a class="section-name-link" href="#/STPFormEncodable"></a> <h3 class="section-name"><span>STPFormEncodable</span> </h3> </div> </div> <ul class="item-container"> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(pl)STPFormEncodable(cm)rootObjectName"></a> <a name="//apple_ref/swift/Method/rootObjectName()" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(pl)STPFormEncodable(cm)rootObjectName">rootObjectName()</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="kd">class</span> <span class="kd">func</span> <span class="nf">rootObjectName</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="kt">String</span><span class="p">?</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L107-L109">Show on GitHub</a> </div> </section> </div> </li> <li class="item"> <div> <code> <a name="/c:@M@Stripe@objc(pl)STPFormEncodable(cm)propertyNamesToFormFieldNamesMapping"></a> <a name="//apple_ref/swift/Method/propertyNamesToFormFieldNamesMapping()" class="dashAnchor"></a> <a class="token" href="#/c:@M@Stripe@objc(pl)STPFormEncodable(cm)propertyNamesToFormFieldNamesMapping">propertyNamesToFormFieldNamesMapping()</a> </code> </div> <div class="height-container"> <div class="pointer-container"></div> <section class="section"> <div class="pointer"></div> <div class="abstract"> </div> <div class="declaration"> <h4>Declaration</h4> <div class="language"> <p class="aside-title">Swift</p> <pre class="highlight swift"><code><span class="kd">@objc</span> <span class="kd">public</span> <span class="kd">class</span> <span class="kd">func</span> <span class="nf">propertyNamesToFormFieldNamesMapping</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="p">[</span><span class="kt">String</span> <span class="p">:</span> <span class="kt">String</span><span class="p">]</span></code></pre> </div> </div> <div class="slightly-smaller"> <a href="https://github.com/stripe/stripe-ios/tree/21.12.0/Stripe/STPBankAccountParams.swift#L112-L121">Show on GitHub</a> </div> </section> </div> </li> </ul> </div> </div> </section> </article> </div> <section class="footer"> <p>&copy; 2022 <a class="link" href="https://stripe.com" target="_blank" rel="external noopener">Stripe</a>. All rights reserved. (Last updated: 2022-02-17)</p> <p>Generated by <a class="link" href="https://github.com/realm/jazzy" target="_blank" rel="external">jazzy โ™ชโ™ซ v0.14.1</a>, a <a class="link" href="https://realm.io" target="_blank" rel="external">Realm</a> project.</p> </section> </body> </div> </html>
stripe/stripe-ios
docs/docs/docsets/Stripe.docset/Contents/Resources/Documents/Classes/STPBankAccountParams.html
HTML
mit
73,186
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.qs=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ /** * Object#toString() ref for stringify(). */ var toString = Object.prototype.toString; /** * Object#hasOwnProperty ref */ var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Array#indexOf shim. */ var indexOf = typeof Array.prototype.indexOf === 'function' ? function(arr, el) { return arr.indexOf(el); } : function(arr, el) { for (var i = 0; i < arr.length; i++) { if (arr[i] === el) return i; } return -1; }; /** * Array.isArray shim. */ var isArray = Array.isArray || function(arr) { return toString.call(arr) == '[object Array]'; }; /** * Object.keys shim. */ var objectKeys = Object.keys || function(obj) { var ret = []; for (var key in obj) { if (obj.hasOwnProperty(key)) { ret.push(key); } } return ret; }; /** * Array#forEach shim. */ var forEach = typeof Array.prototype.forEach === 'function' ? function(arr, fn) { return arr.forEach(fn); } : function(arr, fn) { for (var i = 0; i < arr.length; i++) fn(arr[i]); }; /** * Array#reduce shim. */ var reduce = function(arr, fn, initial) { if (typeof arr.reduce === 'function') return arr.reduce(fn, initial); var res = initial; for (var i = 0; i < arr.length; i++) res = fn(res, arr[i]); return res; }; /** * Cache non-integer test regexp. */ var isint = /^[0-9]+$/; function promote(parent, key) { if (parent[key].length == 0) return parent[key] = {} var t = {}; for (var i in parent[key]) { if (hasOwnProperty.call(parent[key], i)) { t[i] = parent[key][i]; } } parent[key] = t; return t; } function parse(parts, parent, key, val) { var part = parts.shift(); // illegal if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; // end if (!part) { if (isArray(parent[key])) { parent[key].push(val); } else if ('object' == typeof parent[key]) { parent[key] = val; } else if ('undefined' == typeof parent[key]) { parent[key] = val; } else { parent[key] = [parent[key], val]; } // array } else { var obj = parent[key] = parent[key] || []; if (']' == part) { if (isArray(obj)) { if ('' != val) obj.push(val); } else if ('object' == typeof obj) { obj[objectKeys(obj).length] = val; } else { obj = parent[key] = [parent[key], val]; } // prop } else if (~indexOf(part, ']')) { part = part.substr(0, part.length - 1); if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); parse(parts, obj, part, val); // key } else { if (!isint.test(part) && isArray(obj)) obj = promote(parent, key); parse(parts, obj, part, val); } } } /** * Merge parent key/val pair. */ function merge(parent, key, val){ if (~indexOf(key, ']')) { var parts = key.split('[') , len = parts.length , last = len - 1; parse(parts, parent, 'base', val); // optimize } else { if (!isint.test(key) && isArray(parent.base)) { var t = {}; for (var k in parent.base) t[k] = parent.base[k]; parent.base = t; } set(parent.base, key, val); } return parent; } /** * Compact sparse arrays. */ function compact(obj) { if ('object' != typeof obj) return obj; if (isArray(obj)) { var ret = []; for (var i in obj) { if (hasOwnProperty.call(obj, i)) { ret.push(obj[i]); } } return ret; } for (var key in obj) { obj[key] = compact(obj[key]); } return obj; } /** * Parse the given obj. */ function parseObject(obj){ var ret = { base: {} }; forEach(objectKeys(obj), function(name){ merge(ret, name, obj[name]); }); return compact(ret.base); } /** * Parse the given str. */ function parseString(str){ var ret = reduce(String(str).split('&'), function(ret, pair){ var eql = indexOf(pair, '=') , brace = lastBraceInKey(pair) , key = pair.substr(0, brace || eql) , val = pair.substr(brace || eql, pair.length) , val = val.substr(indexOf(val, '=') + 1, val.length); // ?foo if ('' == key) key = pair, val = ''; if ('' == key) return ret; return merge(ret, decode(key), decode(val)); }, { base: {} }).base; return compact(ret); } /** * Parse the given query `str` or `obj`, returning an object. * * @param {String} str | {Object} obj * @return {Object} * @api public */ exports.parse = function(str){ if (null == str || '' == str) return {}; return 'object' == typeof str ? parseObject(str) : parseString(str); }; /** * Turn the given `obj` into a query string * * @param {Object} obj * @return {String} * @api public */ var stringify = exports.stringify = function(obj, prefix) { if (isArray(obj)) { return stringifyArray(obj, prefix); } else if ('[object Object]' == toString.call(obj)) { return stringifyObject(obj, prefix); } else if ('string' == typeof obj) { return stringifyString(obj, prefix); } else { return prefix + '=' + encodeURIComponent(String(obj)); } }; /** * Stringify the given `str`. * * @param {String} str * @param {String} prefix * @return {String} * @api private */ function stringifyString(str, prefix) { if (!prefix) throw new TypeError('stringify expects an object'); return prefix + '=' + encodeURIComponent(str); } /** * Stringify the given `arr`. * * @param {Array} arr * @param {String} prefix * @return {String} * @api private */ function stringifyArray(arr, prefix) { var ret = []; if (!prefix) throw new TypeError('stringify expects an object'); for (var i = 0; i < arr.length; i++) { ret.push(stringify(arr[i], prefix + '[' + i + ']')); } return ret.join('&'); } /** * Stringify the given `obj`. * * @param {Object} obj * @param {String} prefix * @return {String} * @api private */ function stringifyObject(obj, prefix) { var ret = [] , keys = objectKeys(obj) , key; for (var i = 0, len = keys.length; i < len; ++i) { key = keys[i]; if ('' == key) continue; if (null == obj[key]) { ret.push(encodeURIComponent(key) + '='); } else { ret.push(stringify(obj[key], prefix ? prefix + '[' + encodeURIComponent(key) + ']' : encodeURIComponent(key))); } } return ret.join('&'); } /** * Set `obj`'s `key` to `val` respecting * the weird and wonderful syntax of a qs, * where "foo=bar&foo=baz" becomes an array. * * @param {Object} obj * @param {String} key * @param {String} val * @api private */ function set(obj, key, val) { var v = obj[key]; if (Object.getOwnPropertyDescriptor(Object.prototype, key)) return; if (undefined === v) { obj[key] = val; } else if (isArray(v)) { v.push(val); } else { obj[key] = [v, val]; } } /** * Locate last brace in `str` within the key. * * @param {String} str * @return {Number} * @api private */ function lastBraceInKey(str) { var len = str.length , brace , c; for (var i = 0; i < len; ++i) { c = str[i]; if (']' == c) brace = false; if ('[' == c) brace = true; if ('=' == c && !brace) return i; } } /** * Decode `str`. * * @param {String} str * @return {String} * @api private */ function decode(str) { try { return decodeURIComponent(str.replace(/\+/g, ' ')); } catch (err) { return str; } } },{}]},{},[1]) (1) });
kumu/widgets
test/browser/qs.js
JavaScript
mit
8,121
var env = require('./environment.js'); exports.config = { seleniumAddress: env.seleniumAddress, framework: 'jasmine', specs: ['pass_spec.js'], baseUrl: env.baseUrl, plugins: [{ path: '../index.js', failOnWarning: false, failOnError: false }] };
sjelin/protractor-console-plugin
spec/consolePassConfig.js
JavaScript
mit
270
#!/usr/bin/env node /* * * Copyright 2013 Anis Kadri * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ // copyright (c) 2013 Andrew Lunny, Adobe Systems var path = require('path') , url = require('url') , package = require(path.join(__dirname, 'package')) , nopt = require('nopt') , plugins = require('./src/util/plugins') , Q = require('q') , plugman = require('./plugman'); var known_opts = { 'platform' : [ 'ios', 'android', 'amazon-fireos', 'blackberry10', 'wp7', 'wp8' , 'windows8', 'firefoxos' ] , 'project' : path , 'plugin' : [String, path, url, Array] , 'version' : Boolean , 'help' : Boolean , 'debug' : Boolean , 'silent' : Boolean , 'plugins': path , 'link': Boolean , 'variable' : Array , 'www': path , 'searchpath' : [path, Array] }, shortHands = { 'var' : ['--variable'], 'v': ['--version'], 'h': ['--help'] }; var cli_opts = nopt(known_opts, shortHands); var cmd = cli_opts.argv.remain.shift(); // Without these arguments, the commands will fail and print the usage anyway. if (cli_opts.plugins_dir || cli_opts.project) { cli_opts.plugins_dir = typeof cli_opts.plugins_dir == 'string' ? cli_opts.plugins_dir : path.join(cli_opts.project, 'cordova', 'plugins'); } process.on('uncaughtException', function(error) { if (cli_opts.debug) { console.error(error.stack); } else { console.error(error.message); } process.exit(1); }); // Set up appropriate logging based on events if (cli_opts.debug) { plugman.on('verbose', console.log); } if (!cli_opts.silent) { plugman.on('log', console.log); plugman.on('warn', console.warn); plugman.on('results', console.log); } plugman.on('error', console.error); if (cli_opts.version) { console.log(package.version); } else if (cli_opts.help) { console.log(plugman.help()); } else if (plugman.commands[cmd]) { var result = plugman.commands[cmd](cli_opts); if (result && Q.isPromise(result)) { result.done(); } } else { console.log(plugman.help()); }
yfsun/FoodMe
node_modules/cordova/node_modules/plugman/main.js
JavaScript
mit
2,639
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Management.Automation.Internal; using System.Management.Automation.Language; using System.Management.Automation.Runspaces; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Text.RegularExpressions; using System.Threading; using Microsoft.Management.Infrastructure; using Microsoft.Management.Infrastructure.Options; using Microsoft.PowerShell; using Microsoft.PowerShell.Cim; using Microsoft.PowerShell.Commands; using Microsoft.PowerShell.Commands.Internal.Format; namespace System.Management.Automation { /// <summary> /// </summary> public static class CompletionCompleters { static CompletionCompleters() { AppDomain.CurrentDomain.AssemblyLoad += UpdateTypeCacheOnAssemblyLoad; } private static void UpdateTypeCacheOnAssemblyLoad(object sender, AssemblyLoadEventArgs args) { // Just null out the cache - we'll rebuild it the next time someone tries to complete a type. // We could rebuild it now, but we could be loading multiple assemblies (e.g. dependent assemblies) // and there is no sense in rebuilding anything until we're done loading all of the assemblies. Interlocked.Exchange(ref s_typeCache, null); } #region Command Names /// <summary> /// </summary> /// <param name="commandName"></param> /// <returns></returns> public static IEnumerable<CompletionResult> CompleteCommand(string commandName) { return CompleteCommand(commandName, null); } /// <summary> /// </summary> /// <param name="commandName"></param> /// <param name="moduleName"></param> /// <param name="commandTypes"></param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1026:DefaultParametersShouldNotBeUsed")] public static IEnumerable<CompletionResult> CompleteCommand(string commandName, string moduleName, CommandTypes commandTypes = CommandTypes.All) { var runspace = Runspace.DefaultRunspace; if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; } var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace)); var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext; return CompleteCommand(new CompletionContext { WordToComplete = commandName, Helper = helper, ExecutionContext = executionContext }, moduleName, commandTypes); } internal static List<CompletionResult> CompleteCommand(CompletionContext context) { return CompleteCommand(context, null); } private static List<CompletionResult> CompleteCommand(CompletionContext context, string moduleName, CommandTypes types = CommandTypes.All) { var addAmpersandIfNecessary = IsAmpersandNeeded(context, false); string commandName = context.WordToComplete; string quote = HandleDoubleAndSingleQuote(ref commandName); List<CompletionResult> commandResults = null; if (commandName.IndexOfAny(Utils.Separators.DirectoryOrDrive) == -1) { // The name to complete is neither module qualified nor is it a relative/rooted file path. Ast lastAst = null; if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) { lastAst = context.RelatedAsts.Last(); } commandResults = ExecuteGetCommandCommand(useModulePrefix: false); if (lastAst != null) { // We need to add the wildcard to the end so the regex is built correctly. commandName += "*"; // Search the asts for function definitions that we might be calling var findFunctionsVisitor = new FindFunctionsVisitor(); while (lastAst.Parent != null) { lastAst = lastAst.Parent; } lastAst.Visit(findFunctionsVisitor); WildcardPattern commandNamePattern = WildcardPattern.Get(commandName, WildcardOptions.IgnoreCase); foreach (var defn in findFunctionsVisitor.FunctionDefinitions) { if (commandNamePattern.IsMatch(defn.Name) && !commandResults.Any(cr => cr.CompletionText.Equals(defn.Name, StringComparison.OrdinalIgnoreCase))) { // Results found in the current script are prepended to show up at the top of the list. commandResults.Insert(0, GetCommandNameCompletionResult(defn.Name, defn, addAmpersandIfNecessary, quote)); } } } } else { // If there is a single \, we might be looking for a module/snapin qualified command var indexOfFirstColon = commandName.IndexOf(':'); var indexOfFirstBackslash = commandName.IndexOf('\\'); if (indexOfFirstBackslash > 0 && (indexOfFirstBackslash < indexOfFirstColon || indexOfFirstColon == -1)) { // First try the name before the backslash as a module name. // Use the exact module name provided by the user moduleName = commandName.Substring(0, indexOfFirstBackslash); commandName = commandName.Substring(indexOfFirstBackslash + 1); commandResults = ExecuteGetCommandCommand(useModulePrefix: true); } } return commandResults; List<CompletionResult> ExecuteGetCommandCommand(bool useModulePrefix) { var powershell = context.Helper .AddCommandWithPreferenceSetting("Get-Command", typeof(GetCommandCommand)) .AddParameter("All") .AddParameter("Name", commandName + "*"); if (moduleName != null) { powershell.AddParameter("Module", moduleName); } if (!types.Equals(CommandTypes.All)) { powershell.AddParameter("CommandType", types); } // Exception is ignored, the user simply does not get any completion results if the pipeline fails Exception exceptionThrown; var commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); if (commandInfos == null || commandInfos.Count == 0) { powershell.Commands.Clear(); powershell .AddCommandWithPreferenceSetting("Get-Command", typeof(GetCommandCommand)) .AddParameter("All") .AddParameter("Name", commandName) .AddParameter("UseAbbreviationExpansion"); if (moduleName != null) { powershell.AddParameter("Module", moduleName); } if (!types.Equals(CommandTypes.All)) { powershell.AddParameter("CommandType", types); } commandInfos = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); } List<CompletionResult> completionResults = null; if (commandInfos != null && commandInfos.Count > 1) { // OrderBy is using stable sorting var sortedCommandInfos = commandInfos.OrderBy(static a => a, new CommandNameComparer()); completionResults = MakeCommandsUnique(sortedCommandInfos, useModulePrefix, addAmpersandIfNecessary, quote); } else { completionResults = MakeCommandsUnique(commandInfos, useModulePrefix, addAmpersandIfNecessary, quote); } return completionResults; } } private static readonly HashSet<string> s_keywordsToExcludeFromAddingAmpersand = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { nameof(TokenKind.InlineScript), nameof(TokenKind.Configuration) }; internal static CompletionResult GetCommandNameCompletionResult(string name, object command, bool addAmpersandIfNecessary, string quote) { string syntax = name, listItem = name; var commandInfo = command as CommandInfo; if (commandInfo != null) { try { listItem = commandInfo.Name; // This may require parsing a script, which could fail in a number of different ways // (syntax errors, security exceptions, etc.) If so, the name is fine for the tooltip. syntax = commandInfo.Syntax; } catch (Exception) { } } syntax = string.IsNullOrEmpty(syntax) ? name : syntax; bool needAmpersand; if (CompletionRequiresQuotes(name, false)) { needAmpersand = quote == string.Empty && addAmpersandIfNecessary; string quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") { name = name.Replace("'", "''"); } else { name = name.Replace("`", "``"); name = name.Replace("$", "`$"); } name = quoteInUse + name + quoteInUse; } else { needAmpersand = quote == string.Empty && addAmpersandIfNecessary && Tokenizer.IsKeyword(name) && !s_keywordsToExcludeFromAddingAmpersand.Contains(name); name = quote + name + quote; } // It's useless to call ForEach-Object (foreach) as the first command of a pipeline. For example: // PS C:\> fore<tab> ---> PS C:\> foreach (expected, use as the keyword) // PS C:\> fore<tab> ---> PS C:\> & foreach (unexpected, ForEach-Object is seldom used as the first command of a pipeline) if (needAmpersand && name != SpecialVariables.@foreach) { name = "& " + name; } return new CompletionResult(name, listItem, CompletionResultType.Command, syntax); } internal static List<CompletionResult> MakeCommandsUnique(IEnumerable<PSObject> commandInfoPsObjs, bool includeModulePrefix, bool addAmpersandIfNecessary, string quote) { List<CompletionResult> results = new List<CompletionResult>(); if (commandInfoPsObjs == null || !commandInfoPsObjs.Any()) { return results; } var commandTable = new Dictionary<string, object>(StringComparer.OrdinalIgnoreCase); foreach (var psobj in commandInfoPsObjs) { object baseObj = PSObject.Base(psobj); string name = null; var commandInfo = baseObj as CommandInfo; if (commandInfo != null) { // Skip the private commands if (commandInfo.Visibility == SessionStateEntryVisibility.Private) { continue; } name = commandInfo.Name; if (includeModulePrefix && !string.IsNullOrEmpty(commandInfo.ModuleName)) { // The command might be a prefixed commandInfo that we get by importing a module with the -Prefix parameter, for example: // FooModule.psm1: Get-Foo // import-module FooModule -Prefix PowerShell // --> command 'Get-PowerShellFoo' in the global session state (prefixed commandInfo) // command 'Get-Foo' in the module session state (un-prefixed commandInfo) // in that case, we should not add the module name qualification because it doesn't work if (string.IsNullOrEmpty(commandInfo.Prefix) || !ModuleCmdletBase.IsPrefixedCommand(commandInfo)) { name = commandInfo.ModuleName + "\\" + commandInfo.Name; } } } else { name = baseObj as string; if (name == null) { continue; } } object value; if (!commandTable.TryGetValue(name, out value)) { commandTable.Add(name, baseObj); } else { var list = value as List<object>; if (list != null) { list.Add(baseObj); } else { list = new List<object> { value, baseObj }; commandTable[name] = list; } } } List<CompletionResult> endResults = null; foreach (var keyValuePair in commandTable) { var commandList = keyValuePair.Value as List<object>; if (commandList != null) { if (endResults == null) { endResults = new List<CompletionResult>(); } // The first command might be an un-prefixed commandInfo that we get by importing a module with the -Prefix parameter, // in that case, we should add the module name qualification because if the module is not in the module path, calling // 'Get-Foo' directly doesn't work string completionName = keyValuePair.Key; if (!includeModulePrefix) { var commandInfo = commandList[0] as CommandInfo; if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) { completionName = commandInfo.ModuleName + "\\" + completionName; } } } results.Add(GetCommandNameCompletionResult(completionName, commandList[0], addAmpersandIfNecessary, quote)); // For the other commands that are hidden, we need to disambiguate, // but put these at the end as it's less likely any of the hidden // commands are desired. If we can't add anything to disambiguate, // then we'll skip adding a completion result. for (int index = 1; index < commandList.Count; index++) { var commandInfo = commandList[index] as CommandInfo; Diagnostics.Assert(commandInfo != null, "Elements should always be CommandInfo"); if (commandInfo.CommandType == CommandTypes.Application) { endResults.Add(GetCommandNameCompletionResult(commandInfo.Definition, commandInfo, addAmpersandIfNecessary, quote)); } else if (!string.IsNullOrEmpty(commandInfo.ModuleName)) { var name = commandInfo.ModuleName + "\\" + commandInfo.Name; endResults.Add(GetCommandNameCompletionResult(name, commandInfo, addAmpersandIfNecessary, quote)); } } } else { // The first command might be an un-prefixed commandInfo that we get by importing a module with the -Prefix parameter, // in that case, we should add the module name qualification because if the module is not in the module path, calling // 'Get-Foo' directly doesn't work string completionName = keyValuePair.Key; if (!includeModulePrefix) { var commandInfo = keyValuePair.Value as CommandInfo; if (commandInfo != null && !string.IsNullOrEmpty(commandInfo.Prefix)) { Diagnostics.Assert(!string.IsNullOrEmpty(commandInfo.ModuleName), "the module name should exist if commandInfo.Prefix is not an empty string"); if (!ModuleCmdletBase.IsPrefixedCommand(commandInfo)) { completionName = commandInfo.ModuleName + "\\" + completionName; } } } results.Add(GetCommandNameCompletionResult(completionName, keyValuePair.Value, addAmpersandIfNecessary, quote)); } } if (endResults != null && endResults.Count > 0) { results.AddRange(endResults); } return results; } private sealed class FindFunctionsVisitor : AstVisitor { internal readonly List<FunctionDefinitionAst> FunctionDefinitions = new List<FunctionDefinitionAst>(); public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { FunctionDefinitions.Add(functionDefinitionAst); return AstVisitAction.Continue; } } #endregion Command Names #region Module Names internal static List<CompletionResult> CompleteModuleName(CompletionContext context, bool loadedModulesOnly, bool skipEditionCheck = false) { var moduleName = context.WordToComplete ?? string.Empty; var result = new List<CompletionResult>(); var quote = HandleDoubleAndSingleQuote(ref moduleName); if (!moduleName.EndsWith('*')) { moduleName += "*"; } var powershell = context.Helper.AddCommandWithPreferenceSetting("Get-Module", typeof(GetModuleCommand)).AddParameter("Name", moduleName); if (!loadedModulesOnly) { powershell.AddParameter("ListAvailable", true); // -SkipEditionCheck should only be set or apply to -ListAvailable if (skipEditionCheck) { powershell.AddParameter("SkipEditionCheck", true); } } Exception exceptionThrown; var psObjects = context.Helper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects != null) { foreach (dynamic moduleInfo in psObjects) { var completionText = moduleInfo.Name.ToString(); var listItemText = completionText; var toolTip = "Description: " + moduleInfo.Description.ToString() + "\r\nModuleType: " + moduleInfo.ModuleType.ToString() + "\r\nPath: " + moduleInfo.Path.ToString(); if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, toolTip)); } } return result; } #endregion Module Names #region Command Parameters private static readonly string[] s_parameterNamesOfImportDSCResource = { "Name", "ModuleName", "ModuleVersion" }; internal static List<CompletionResult> CompleteCommandParameter(CompletionContext context) { string partialName = null; bool withColon = false; CommandAst commandAst = null; List<CompletionResult> result = new List<CompletionResult>(); // Find the parameter ast, it will be near or at the end CommandParameterAst parameterAst = null; DynamicKeywordStatementAst keywordAst = null; for (int i = context.RelatedAsts.Count - 1; i >= 0; i--) { if (keywordAst == null) keywordAst = context.RelatedAsts[i] as DynamicKeywordStatementAst; parameterAst = (context.RelatedAsts[i] as CommandParameterAst); if (parameterAst != null) break; } if (parameterAst != null) { keywordAst = parameterAst.Parent as DynamicKeywordStatementAst; } // If parent is DynamicKeywordStatementAst - 'Import-DscResource', // then customize the auto completion results if (keywordAst != null && string.Equals(keywordAst.Keyword.Keyword, "Import-DscResource", StringComparison.OrdinalIgnoreCase) && !string.IsNullOrWhiteSpace(context.WordToComplete) && context.WordToComplete.StartsWith('-')) { var lastAst = context.RelatedAsts.Last(); var wordToMatch = string.Concat(context.WordToComplete.AsSpan(1), "*"); var pattern = WildcardPattern.Get(wordToMatch, WildcardOptions.IgnoreCase); var parameterNames = keywordAst.CommandElements.Where(static ast => ast is CommandParameterAst).Select(static ast => (ast as CommandParameterAst).ParameterName); foreach (var parameterName in s_parameterNamesOfImportDSCResource) { if (pattern.IsMatch(parameterName) && !parameterNames.Contains(parameterName, StringComparer.OrdinalIgnoreCase)) { string tooltip = "[String] " + parameterName; result.Add(new CompletionResult("-" + parameterName, parameterName, CompletionResultType.ParameterName, tooltip)); } } if (result.Count > 0) { context.ReplacementLength = context.WordToComplete.Length; context.ReplacementIndex = lastAst.Extent.StartOffset; } return result; } if (parameterAst != null) { // Parent must be a command commandAst = (CommandAst)parameterAst.Parent; partialName = parameterAst.ParameterName; withColon = context.WordToComplete.EndsWith(':'); } else { // No CommandParameterAst is found. It could be a StringConstantExpressionAst "-" if (!(context.RelatedAsts[context.RelatedAsts.Count - 1] is StringConstantExpressionAst dashAst)) return result; if (!dashAst.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) return result; // Parent must be a command commandAst = (CommandAst)dashAst.Parent; partialName = string.Empty; } PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() .DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion); // The command cannot be found or it's not a cmdlet, not a script cmdlet, not a function. // Try completing as if it the parameter is a command argument for native command completion. if (pseudoBinding == null) { return CompleteCommandArgument(context); } switch (pseudoBinding.InfoType) { case PseudoBindingInfoType.PseudoBindingFail: // The command is a cmdlet or script cmdlet. Binding failed result = GetParameterCompletionResults(partialName, uint.MaxValue, pseudoBinding.UnboundParameters, withColon); break; case PseudoBindingInfoType.PseudoBindingSucceed: // The command is a cmdlet or script cmdlet. Binding succeeded. result = GetParameterCompletionResults(partialName, pseudoBinding, parameterAst, withColon); break; } if (result.Count == 0) { result = pseudoBinding.CommandName.Equals("Set-Location", StringComparison.OrdinalIgnoreCase) ? new List<CompletionResult>(CompleteFilename(context, containerOnly: true, extension: null)) : new List<CompletionResult>(CompleteFilename(context)); } return result; } /// <summary> /// Get the parameter completion results when the pseudo binding was successful. /// </summary> /// <param name="parameterName"></param> /// <param name="bindingInfo"></param> /// <param name="parameterAst"></param> /// <param name="withColon"></param> /// <returns></returns> private static List<CompletionResult> GetParameterCompletionResults(string parameterName, PseudoBindingInfo bindingInfo, CommandParameterAst parameterAst, bool withColon) { Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "The pseudo binding should succeed"); List<CompletionResult> result = new List<CompletionResult>(); if (parameterName == string.Empty) { result = GetParameterCompletionResults( parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.UnboundParameters, withColon); return result; } if (bindingInfo.ParametersNotFound.Count > 0) { // The parameter name cannot be matched to any parameter if (bindingInfo.ParametersNotFound.Any(pAst => parameterAst.GetHashCode() == pAst.GetHashCode())) { return result; } } if (bindingInfo.AmbiguousParameters.Count > 0) { // The parameter name is ambiguous. It's ignored in the pseudo binding, and we should search in the UnboundParameters if (bindingInfo.AmbiguousParameters.Any(pAst => parameterAst.GetHashCode() == pAst.GetHashCode())) { result = GetParameterCompletionResults( parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.UnboundParameters, withColon); } return result; } if (bindingInfo.DuplicateParameters.Count > 0) { // The parameter name is resolved to a parameter that is already bound. We search it in the BoundParameters if (bindingInfo.DuplicateParameters.Any(pAst => parameterAst.GetHashCode() == pAst.Parameter.GetHashCode())) { result = GetParameterCompletionResults( parameterName, bindingInfo.ValidParameterSetsFlags, bindingInfo.BoundParameters.Values, withColon); } return result; } // The parameter should be bound in the pseudo binding during the named binding string matchedParameterName = null; foreach (KeyValuePair<string, AstParameterArgumentPair> entry in bindingInfo.BoundArguments) { switch (entry.Value.ParameterArgumentType) { case AstParameterArgumentType.AstPair: { AstPair pair = (AstPair)entry.Value; if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode()) { matchedParameterName = entry.Key; } else if (pair.ArgumentIsCommandParameterAst && pair.Argument.GetHashCode() == parameterAst.GetHashCode()) { // The parameter name cannot be resolved to a parameter return result; } } break; case AstParameterArgumentType.Fake: { FakePair pair = (FakePair)entry.Value; if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode()) { matchedParameterName = entry.Key; } } break; case AstParameterArgumentType.Switch: { SwitchPair pair = (SwitchPair)entry.Value; if (pair.ParameterSpecified && pair.Parameter.GetHashCode() == parameterAst.GetHashCode()) { matchedParameterName = entry.Key; } } break; case AstParameterArgumentType.AstArray: case AstParameterArgumentType.PipeObject: break; } if (matchedParameterName != null) break; } Diagnostics.Assert(matchedParameterName != null, "we should find matchedParameterName from the BoundArguments"); MergedCompiledCommandParameter param = bindingInfo.BoundParameters[matchedParameterName]; WildcardPattern pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase); string parameterType = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] "; string colonSuffix = withColon ? ":" : string.Empty; if (pattern.IsMatch(matchedParameterName)) { string completionText = "-" + matchedParameterName + colonSuffix; string tooltip = parameterType + matchedParameterName; result.Add(new CompletionResult(completionText, matchedParameterName, CompletionResultType.ParameterName, tooltip)); } // Process alias when there is partial input result.AddRange(from alias in param.Parameter.Aliases where pattern.IsMatch(alias) select new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, parameterType + alias)); return result; } /// <summary> /// Get the parameter completion results by using the given valid parameter sets and available parameters. /// </summary> /// <param name="parameterName"></param> /// <param name="validParameterSetFlags"></param> /// <param name="parameters"></param> /// <param name="withColon"></param> /// <returns></returns> private static List<CompletionResult> GetParameterCompletionResults( string parameterName, uint validParameterSetFlags, IEnumerable<MergedCompiledCommandParameter> parameters, bool withColon) { var result = new List<CompletionResult>(); var commonParamResult = new List<CompletionResult>(); var pattern = WildcardPattern.Get(parameterName + "*", WildcardOptions.IgnoreCase); var colonSuffix = withColon ? ":" : string.Empty; bool addCommonParameters = true; foreach (MergedCompiledCommandParameter param in parameters) { bool inParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets; if (!inParameterSet) continue; string name = param.Parameter.Name; string type = "[" + ToStringCodeMethods.Type(param.Parameter.Type, dropNamespaces: true) + "] "; bool isCommonParameter = Cmdlet.CommonParameters.Contains(name, StringComparer.OrdinalIgnoreCase); List<CompletionResult> listInUse = isCommonParameter ? commonParamResult : result; if (pattern.IsMatch(name)) { // Then using functions to back dynamic keywords, we don't necessarily // want all of the parameters to be shown to the user. Those that are marked // DontShow will not be displayed. Also, if any of the parameters have // don't show set, we won't show any of the common parameters either. bool showToUser = true; var compiledAttributes = param.Parameter.CompiledAttributes; if (compiledAttributes != null && compiledAttributes.Count > 0) { foreach (var attr in compiledAttributes) { var pattr = attr as ParameterAttribute; if (pattr != null && pattr.DontShow) { showToUser = false; addCommonParameters = false; break; } } } if (showToUser) { string completionText = "-" + name + colonSuffix; string tooltip = type + name; listInUse.Add(new CompletionResult(completionText, name, CompletionResultType.ParameterName, tooltip)); } } if (parameterName != string.Empty) { // Process alias when there is partial input listInUse.AddRange(from alias in param.Parameter.Aliases where pattern.IsMatch(alias) select new CompletionResult("-" + alias + colonSuffix, alias, CompletionResultType.ParameterName, type + alias)); } } // Add the common parameters to the results if expected. if (addCommonParameters) { result.AddRange(commonParamResult); } return result; } /// <summary> /// Get completion results for operators that start with <paramref name="wordToComplete"/> /// </summary> /// <param name="wordToComplete">The starting text of the operator to complete.</param> /// <returns>A list of completion results.</returns> public static List<CompletionResult> CompleteOperator(string wordToComplete) { if (wordToComplete.StartsWith('-')) { wordToComplete = wordToComplete.Substring(1); } return (from op in Tokenizer._operatorText where op.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase) orderby op select new CompletionResult("-" + op, op, CompletionResultType.ParameterName, GetOperatorDescription(op))).ToList(); } private static string GetOperatorDescription(string op) { return ResourceManagerCache.GetResourceString(typeof(CompletionCompleters).Assembly, "System.Management.Automation.resources.TabCompletionStrings", op + "OperatorDescription"); } #endregion Command Parameters #region Command Arguments internal static List<CompletionResult> CompleteCommandArgument(CompletionContext context) { CommandAst commandAst = null; List<CompletionResult> result = new List<CompletionResult>(); // Find the expression ast. It should be at the end if there is one ExpressionAst expressionAst = null; MemberExpressionAst secondToLastMemberAst = null; Ast lastAst = context.RelatedAsts.Last(); expressionAst = lastAst as ExpressionAst; if (expressionAst != null) { if (expressionAst.Parent is CommandAst) { commandAst = (CommandAst)expressionAst.Parent; if (expressionAst is ErrorExpressionAst && expressionAst.Extent.Text.EndsWith(',')) { context.WordToComplete = string.Empty; // BUGBUG context.CursorPosition = expressionAst.Extent.StartScriptPosition; } else if (commandAst.CommandElements.Count == 1 || context.WordToComplete == string.Empty) { expressionAst = null; } else if (commandAst.CommandElements.Count > 2) { var length = commandAst.CommandElements.Count; var index = 1; for (; index < length; index++) { if (commandAst.CommandElements[index] == expressionAst) break; } CommandElementAst secondToLastAst = null; if (index > 1) { secondToLastAst = commandAst.CommandElements[index - 1]; secondToLastMemberAst = secondToLastAst as MemberExpressionAst; } var partialPathAst = expressionAst as StringConstantExpressionAst; if (partialPathAst != null && secondToLastAst != null && partialPathAst.StringConstantType == StringConstantType.BareWord && secondToLastAst.Extent.EndLineNumber == partialPathAst.Extent.StartLineNumber && secondToLastAst.Extent.EndColumnNumber == partialPathAst.Extent.StartColumnNumber && partialPathAst.Value.IndexOfAny(Utils.Separators.Directory) == 0) { var secondToLastStringConstantAst = secondToLastAst as StringConstantExpressionAst; var secondToLastExpandableStringAst = secondToLastAst as ExpandableStringExpressionAst; var secondToLastArrayAst = secondToLastAst as ArrayLiteralAst; var secondToLastParamAst = secondToLastAst as CommandParameterAst; if (secondToLastStringConstantAst != null || secondToLastExpandableStringAst != null) { var fullPath = ConcatenateStringPathArguments(secondToLastAst, partialPathAst.Value, context); expressionAst = secondToLastStringConstantAst != null ? (ExpressionAst)secondToLastStringConstantAst : (ExpressionAst)secondToLastExpandableStringAst; context.ReplacementIndex = ((InternalScriptPosition)secondToLastAst.Extent.StartScriptPosition).Offset; context.ReplacementLength += ((InternalScriptPosition)secondToLastAst.Extent.EndScriptPosition).Offset - context.ReplacementIndex; context.WordToComplete = fullPath; // context.CursorPosition = secondToLastAst.Extent.StartScriptPosition; } else if (secondToLastArrayAst != null) { // Handle cases like: dir -Path .\cd, 'a b'\new<tab> var lastArrayElement = secondToLastArrayAst.Elements.LastOrDefault(); var fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context); if (fullPath != null) { expressionAst = secondToLastArrayAst; context.ReplacementIndex = ((InternalScriptPosition)lastArrayElement.Extent.StartScriptPosition).Offset; context.ReplacementLength += ((InternalScriptPosition)lastArrayElement.Extent.EndScriptPosition).Offset - context.ReplacementIndex; context.WordToComplete = fullPath; } } else if (secondToLastParamAst != null) { // Handle cases like: dir -Path: .\cd, 'a b'\new<tab> || dir -Path: 'a b'\new<tab> var fullPath = ConcatenateStringPathArguments(secondToLastParamAst.Argument, partialPathAst.Value, context); if (fullPath != null) { expressionAst = secondToLastParamAst.Argument; context.ReplacementIndex = ((InternalScriptPosition)secondToLastParamAst.Argument.Extent.StartScriptPosition).Offset; context.ReplacementLength += ((InternalScriptPosition)secondToLastParamAst.Argument.Extent.EndScriptPosition).Offset - context.ReplacementIndex; context.WordToComplete = fullPath; } else { var arrayArgAst = secondToLastParamAst.Argument as ArrayLiteralAst; if (arrayArgAst != null) { var lastArrayElement = arrayArgAst.Elements.LastOrDefault(); fullPath = ConcatenateStringPathArguments(lastArrayElement, partialPathAst.Value, context); if (fullPath != null) { expressionAst = arrayArgAst; context.ReplacementIndex = ((InternalScriptPosition)lastArrayElement.Extent.StartScriptPosition).Offset; context.ReplacementLength += ((InternalScriptPosition)lastArrayElement.Extent.EndScriptPosition).Offset - context.ReplacementIndex; context.WordToComplete = fullPath; } } } } } } } else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandAst) { commandAst = (CommandAst)expressionAst.Parent.Parent; if (commandAst.CommandElements.Count == 1 || context.WordToComplete == string.Empty) { // dir -Path a.txt, b.txt <tab> expressionAst = null; } else { // dir -Path a.txt, b.txt c<tab> expressionAst = (ExpressionAst)expressionAst.Parent; } } else if (expressionAst.Parent is ArrayLiteralAst && expressionAst.Parent.Parent is CommandParameterAst) { // Handle scenarios such as // dir -Path: a.txt, <tab> || dir -Path: a.txt, b.txt <tab> commandAst = (CommandAst)expressionAst.Parent.Parent.Parent; if (context.WordToComplete == string.Empty) { // dir -Path: a.txt, b.txt <tab> expressionAst = null; } else { // dir -Path: a.txt, b<tab> expressionAst = (ExpressionAst)expressionAst.Parent; } } else if (expressionAst.Parent is CommandParameterAst && expressionAst.Parent.Parent is CommandAst) { commandAst = (CommandAst)expressionAst.Parent.Parent; if (expressionAst is ErrorExpressionAst && expressionAst.Extent.Text.EndsWith(',')) { // dir -Path: a.txt,<tab> context.WordToComplete = string.Empty; // context.CursorPosition = expressionAst.Extent.StartScriptPosition; } else if (context.WordToComplete == string.Empty) { // Handle scenario like this: Set-ExecutionPolicy -Scope:CurrentUser <tab> expressionAst = null; } } } else { var paramAst = lastAst as CommandParameterAst; if (paramAst != null) { commandAst = paramAst.Parent as CommandAst; } else { commandAst = lastAst as CommandAst; } } if (commandAst == null) { // We don't know if this could be expanded into anything interesting return result; } PseudoBindingInfo pseudoBinding = new PseudoParameterBinder() .DoPseudoParameterBinding(commandAst, null, null, PseudoParameterBinder.BindingType.ArgumentCompletion); do { // The command cannot be found, or it's NOT a cmdlet, NOT a script cmdlet and NOT a function if (pseudoBinding == null) break; bool parsedArgumentsProvidesMatch = false; if (pseudoBinding.AllParsedArguments != null && pseudoBinding.AllParsedArguments.Count > 0) { ArgumentLocation argLocation; bool treatAsExpression = false; if (expressionAst != null) { treatAsExpression = true; var dashExp = expressionAst as StringConstantExpressionAst; if (dashExp != null && dashExp.Value.Trim().Equals("-", StringComparison.OrdinalIgnoreCase)) { // "-" is represented as StringConstantExpressionAst. Most likely the user is typing a <tab> // after it, so in the pseudo binder, we ignore it to avoid treating it as an argument. // for example: // Get-Content -Path "-<tab> --> Get-Content -Path ".\-patt.txt" treatAsExpression = false; } } if (treatAsExpression) { argLocation = FindTargetArgumentLocation( pseudoBinding.AllParsedArguments, expressionAst); } else { argLocation = FindTargetArgumentLocation( pseudoBinding.AllParsedArguments, context.TokenAtCursor ?? context.TokenBeforeCursor); } if (argLocation != null) { context.PseudoBindingInfo = pseudoBinding; switch (pseudoBinding.InfoType) { case PseudoBindingInfoType.PseudoBindingSucceed: result = GetArgumentCompletionResultsWithSuccessfulPseudoBinding(context, argLocation, commandAst); break; case PseudoBindingInfoType.PseudoBindingFail: result = GetArgumentCompletionResultsWithFailedPseudoBinding(context, argLocation, commandAst); break; } parsedArgumentsProvidesMatch = true; } } if (!parsedArgumentsProvidesMatch) { int index = 0; CommandElementAst prevElem = null; if (expressionAst != null) { foreach (CommandElementAst eleAst in commandAst.CommandElements) { if (eleAst.GetHashCode() == expressionAst.GetHashCode()) break; prevElem = eleAst; index++; } } else { var token = context.TokenAtCursor ?? context.TokenBeforeCursor; foreach (CommandElementAst eleAst in commandAst.CommandElements) { if (eleAst.Extent.StartOffset > token.Extent.EndOffset) break; prevElem = eleAst; index++; } } // positional argument with position 0 if (index == 1) { CompletePositionalArgument( pseudoBinding.CommandName, commandAst, context, result, pseudoBinding.UnboundParameters, pseudoBinding.DefaultParameterSetFlag, uint.MaxValue, 0); } else { if (prevElem is CommandParameterAst && ((CommandParameterAst)prevElem).Argument == null) { var paramName = ((CommandParameterAst)prevElem).ParameterName; var pattern = WildcardPattern.Get(paramName + "*", WildcardOptions.IgnoreCase); foreach (MergedCompiledCommandParameter param in pseudoBinding.UnboundParameters) { if (pattern.IsMatch(param.Parameter.Name)) { ProcessParameter(pseudoBinding.CommandName, commandAst, context, result, param); break; } var isAliasMatch = false; foreach (string alias in param.Parameter.Aliases) { if (pattern.IsMatch(alias)) { isAliasMatch = true; ProcessParameter(pseudoBinding.CommandName, commandAst, context, result, param); break; } } if (isAliasMatch) break; } } } } } while (false); // Indicate if the current argument completion falls into those pre-defined cases and // has been processed already. bool hasBeenProcessed = false; if (result.Count > 0 && result[result.Count - 1].Equals(CompletionResult.Null)) { result.RemoveAt(result.Count - 1); hasBeenProcessed = true; if (result.Count > 0) return result; } // Handle some special cases such as: // & "get-comm<tab> --> & "Get-Command" // & "sa<tab> --> & ".\sa[v].txt" if (expressionAst == null && !hasBeenProcessed && commandAst.CommandElements.Count == 1 && commandAst.InvocationOperator != TokenKind.Unknown && context.WordToComplete != string.Empty) { // Use literal path after Ampersand var tryCmdletCompletion = false; var clearLiteralPathsKey = TurnOnLiteralPathOption(context); if (context.WordToComplete.Contains('-')) { tryCmdletCompletion = true; } try { var fileCompletionResults = new List<CompletionResult>(CompleteFilename(context)); if (tryCmdletCompletion) { // It's actually command name completion, other than argument completion var cmdletCompletionResults = CompleteCommand(context); if (cmdletCompletionResults != null && cmdletCompletionResults.Count > 0) { fileCompletionResults.AddRange(cmdletCompletionResults); } } return fileCompletionResults; } finally { if (clearLiteralPathsKey) context.Options.Remove("LiteralPaths"); } } if (expressionAst is StringConstantExpressionAst) { var pathAst = (StringConstantExpressionAst)expressionAst; // Handle static member completion: echo [int]::<tab> var shareMatch = Regex.Match(pathAst.Value, @"^(\[[\w\d\.]+\]::[\w\d\*]*)$"); if (shareMatch.Success) { int fakeReplacementIndex, fakeReplacementLength; var input = shareMatch.Groups[1].Value; var completionParameters = CommandCompletion.MapStringInputToParsedInput(input, input.Length); var completionAnalysis = new CompletionAnalysis(completionParameters.Item1, completionParameters.Item2, completionParameters.Item3, context.Options); var ret = completionAnalysis.GetResults( context.Helper.CurrentPowerShell, out fakeReplacementIndex, out fakeReplacementLength); if (ret != null && ret.Count > 0) { string prefix = string.Concat(TokenKind.LParen.Text(), input.AsSpan(0, fakeReplacementIndex)); foreach (CompletionResult entry in ret) { string completionText = prefix + entry.CompletionText; if (entry.ResultType.Equals(CompletionResultType.Property)) completionText += TokenKind.RParen.Text(); result.Add(new CompletionResult(completionText, entry.ListItemText, entry.ResultType, entry.ToolTip)); } return result; } } // Handle member completion with wildcard: echo $a.*<tab> if (pathAst.Value.Contains('*') && secondToLastMemberAst != null && secondToLastMemberAst.Extent.EndLineNumber == pathAst.Extent.StartLineNumber && secondToLastMemberAst.Extent.EndColumnNumber == pathAst.Extent.StartColumnNumber) { var memberName = pathAst.Value.EndsWith('*') ? pathAst.Value : pathAst.Value + "*"; var targetExpr = secondToLastMemberAst.Expression; if (IsSplattedVariable(targetExpr)) { // It's splatted variable, and the member completion is not useful return result; } var memberAst = secondToLastMemberAst.Member as StringConstantExpressionAst; if (memberAst != null) { memberName = memberAst.Value + memberName; } CompleteMemberHelper(false, memberName, targetExpr, context, result); if (result.Count > 0) { context.ReplacementIndex = ((InternalScriptPosition)secondToLastMemberAst.Expression.Extent.EndScriptPosition).Offset + 1; if (memberAst != null) context.ReplacementLength += memberAst.Value.Length; return result; } } // Treat it as the file name completion // Handle this scenario: & 'c:\a b'\<tab> string fileName = pathAst.Value; if (commandAst.InvocationOperator != TokenKind.Unknown && fileName.IndexOfAny(Utils.Separators.Directory) == 0 && commandAst.CommandElements.Count == 2 && commandAst.CommandElements[0] is StringConstantExpressionAst && commandAst.CommandElements[0].Extent.EndLineNumber == expressionAst.Extent.StartLineNumber && commandAst.CommandElements[0].Extent.EndColumnNumber == expressionAst.Extent.StartColumnNumber) { if (pseudoBinding != null) { // CommandElements[0] is resolved to a command return result; } else { var constantAst = (StringConstantExpressionAst)commandAst.CommandElements[0]; fileName = constantAst.Value + fileName; context.ReplacementIndex = ((InternalScriptPosition)constantAst.Extent.StartScriptPosition).Offset; context.ReplacementLength += ((InternalScriptPosition)constantAst.Extent.EndScriptPosition).Offset - context.ReplacementIndex; context.WordToComplete = fileName; // commandAst.InvocationOperator != TokenKind.Unknown, so we should use literal path var clearLiteralPathKey = TurnOnLiteralPathOption(context); try { return new List<CompletionResult>(CompleteFilename(context)); } finally { if (clearLiteralPathKey) context.Options.Remove("LiteralPaths"); } } } } // The default argument completion: file path completion, command name completion('WordToComplete' is not empty and contains a dash). // If the current argument completion has been process already, we don't go through the default argument completion anymore. if (!hasBeenProcessed) { var commandName = commandAst.GetCommandName(); var customCompleter = GetCustomArgumentCompleter( "NativeArgumentCompleters", new[] { commandName, Path.GetFileName(commandName), Path.GetFileNameWithoutExtension(commandName) }, context); if (customCompleter != null) { if (InvokeScriptArgumentCompleter( customCompleter, new object[] { context.WordToComplete, commandAst, context.CursorPosition.Offset }, result)) { return result; } } var clearLiteralPathKey = false; if (pseudoBinding == null) { // the command could be a native command such as notepad.exe, we use literal path in this case clearLiteralPathKey = TurnOnLiteralPathOption(context); } try { result = new List<CompletionResult>(CompleteFilename(context)); } finally { if (clearLiteralPathKey) context.Options.Remove("LiteralPaths"); } // The word to complete contains a dash and it's not the first character. We try command names in this case. if (context.WordToComplete.IndexOf('-') > 0) { var commandResults = CompleteCommand(context); if (commandResults != null) result.AddRange(commandResults); } } return result; } internal static string ConcatenateStringPathArguments(CommandElementAst stringAst, string partialPath, CompletionContext completionContext) { var constantPathAst = stringAst as StringConstantExpressionAst; if (constantPathAst != null) { string quote = string.Empty; switch (constantPathAst.StringConstantType) { case StringConstantType.SingleQuoted: quote = "'"; break; case StringConstantType.DoubleQuoted: quote = "\""; break; default: break; } return quote + constantPathAst.Value + partialPath + quote; } else { var expandablePathAst = stringAst as ExpandableStringExpressionAst; string fullPath = null; if (expandablePathAst != null && IsPathSafelyExpandable(expandableStringAst: expandablePathAst, extraText: partialPath, executionContext: completionContext.ExecutionContext, expandedString: out fullPath)) { return fullPath; } } return null; } /// <summary> /// Get the argument completion results when the pseudo binding was not successful. /// </summary> private static List<CompletionResult> GetArgumentCompletionResultsWithFailedPseudoBinding( CompletionContext context, ArgumentLocation argLocation, CommandAst commandAst) { List<CompletionResult> result = new List<CompletionResult>(); PseudoBindingInfo bindingInfo = context.PseudoBindingInfo; if (argLocation.IsPositional) { CompletePositionalArgument( bindingInfo.CommandName, commandAst, context, result, bindingInfo.UnboundParameters, bindingInfo.DefaultParameterSetFlag, uint.MaxValue, argLocation.Position); } else { string paramName = argLocation.Argument.ParameterName; WildcardPattern pattern = WildcardPattern.Get(paramName + "*", WildcardOptions.IgnoreCase); foreach (MergedCompiledCommandParameter param in bindingInfo.UnboundParameters) { if (pattern.IsMatch(param.Parameter.Name)) { ProcessParameter(bindingInfo.CommandName, commandAst, context, result, param); break; } bool isAliasMatch = false; foreach (string alias in param.Parameter.Aliases) { if (pattern.IsMatch(alias)) { isAliasMatch = true; ProcessParameter(bindingInfo.CommandName, commandAst, context, result, param); break; } } if (isAliasMatch) break; } } return result; } /// <summary> /// Get the argument completion results when the pseudo binding was successful. /// </summary> private static List<CompletionResult> GetArgumentCompletionResultsWithSuccessfulPseudoBinding( CompletionContext context, ArgumentLocation argLocation, CommandAst commandAst) { PseudoBindingInfo bindingInfo = context.PseudoBindingInfo; Diagnostics.Assert(bindingInfo.InfoType.Equals(PseudoBindingInfoType.PseudoBindingSucceed), "Caller needs to make sure the pseudo binding was successful"); List<CompletionResult> result = new List<CompletionResult>(); if (argLocation.IsPositional && argLocation.Argument == null) { AstPair lastPositionalArg; AstParameterArgumentPair targetPositionalArg = FindTargetPositionalArgument( bindingInfo.AllParsedArguments, argLocation.Position, out lastPositionalArg); if (targetPositionalArg != null) argLocation.Argument = targetPositionalArg; else { if (lastPositionalArg != null) { bool lastPositionalGetBound = false; Collection<string> parameterNames = new Collection<string>(); foreach (KeyValuePair<string, AstParameterArgumentPair> entry in bindingInfo.BoundArguments) { // positional argument if (!entry.Value.ParameterSpecified) { var arg = (AstPair)entry.Value; if (arg.Argument.GetHashCode() == lastPositionalArg.Argument.GetHashCode()) { lastPositionalGetBound = true; break; } } else if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray)) { // check if the positional argument would be bound to a "ValueFromRemainingArgument" parameter var arg = (AstArrayPair)entry.Value; if (arg.Argument.Any(exp => exp.GetHashCode() == lastPositionalArg.Argument.GetHashCode())) { parameterNames.Add(entry.Key); } } } if (parameterNames.Count > 0) { // parameter should be in BoundParameters foreach (string param in parameterNames) { MergedCompiledCommandParameter parameter = bindingInfo.BoundParameters[param]; ProcessParameter(bindingInfo.CommandName, commandAst, context, result, parameter, bindingInfo.BoundArguments); } return result; } else if (!lastPositionalGetBound) { // last positional argument was not bound, then positional argument 'tab' wants to // expand will not get bound either return result; } } CompletePositionalArgument( bindingInfo.CommandName, commandAst, context, result, bindingInfo.UnboundParameters, bindingInfo.DefaultParameterSetFlag, bindingInfo.ValidParameterSetsFlags, argLocation.Position, bindingInfo.BoundArguments); return result; } } if (argLocation.Argument != null) { Collection<string> parameterNames = new Collection<string>(); foreach (KeyValuePair<string, AstParameterArgumentPair> entry in bindingInfo.BoundArguments) { if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.PipeObject)) continue; if (entry.Value.ParameterArgumentType.Equals(AstParameterArgumentType.AstArray) && !argLocation.Argument.ParameterSpecified) { var arrayArg = (AstArrayPair)entry.Value; var target = (AstPair)argLocation.Argument; if (arrayArg.Argument.Any(exp => exp.GetHashCode() == target.Argument.GetHashCode())) { parameterNames.Add(entry.Key); } } else if (entry.Value.GetHashCode() == argLocation.Argument.GetHashCode()) { parameterNames.Add(entry.Key); } } if (parameterNames.Count > 0) { // those parameters should be in BoundParameters foreach (string param in parameterNames) { MergedCompiledCommandParameter parameter = bindingInfo.BoundParameters[param]; ProcessParameter(bindingInfo.CommandName, commandAst, context, result, parameter, bindingInfo.BoundArguments); } } } return result; } /// <summary> /// Get the positional argument completion results based on the position it's in the command line. /// </summary> private static void CompletePositionalArgument( string commandName, CommandAst commandAst, CompletionContext context, List<CompletionResult> result, IEnumerable<MergedCompiledCommandParameter> parameters, uint defaultParameterSetFlag, uint validParameterSetFlags, int position, Dictionary<string, AstParameterArgumentPair> boundArguments = null) { bool isProcessedAsPositional = false; bool isDefaultParameterSetValid = defaultParameterSetFlag != 0 && (defaultParameterSetFlag & validParameterSetFlags) != 0; MergedCompiledCommandParameter positionalParam = null; foreach (MergedCompiledCommandParameter param in parameters) { bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets; if (!isInParameterSet) continue; var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags); foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection) { // in the first pass, we skip the remaining argument ones if (parameterSetData.ValueFromRemainingArguments) { continue; } // Check the position int positionInParameterSet = parameterSetData.Position; if (positionInParameterSet == int.MinValue || positionInParameterSet != position) { // The parameter is not positional, or its position is not what we want continue; } if (isDefaultParameterSetValid) { if (parameterSetData.ParameterSetFlag == defaultParameterSetFlag) { ProcessParameter(commandName, commandAst, context, result, param, boundArguments); isProcessedAsPositional = result.Count > 0; break; } else { if (positionalParam == null) positionalParam = param; } } else { isProcessedAsPositional = true; ProcessParameter(commandName, commandAst, context, result, param, boundArguments); break; } } if (isProcessedAsPositional) break; } if (!isProcessedAsPositional && positionalParam != null) { isProcessedAsPositional = true; ProcessParameter(commandName, commandAst, context, result, positionalParam, boundArguments); } if (!isProcessedAsPositional) { foreach (MergedCompiledCommandParameter param in parameters) { bool isInParameterSet = (param.Parameter.ParameterSetFlags & validParameterSetFlags) != 0 || param.Parameter.IsInAllSets; if (!isInParameterSet) continue; var parameterSetDataCollection = param.Parameter.GetMatchingParameterSetData(validParameterSetFlags); foreach (ParameterSetSpecificMetadata parameterSetData in parameterSetDataCollection) { // in the second pass, we check the remaining argument ones if (parameterSetData.ValueFromRemainingArguments) { ProcessParameter(commandName, commandAst, context, result, param, boundArguments); break; } } } } } /// <summary> /// Process a parameter to get the argument completion results. /// </summary> /// <remarks> /// If the argument completion falls into these pre-defined cases: /// 1. The matching parameter is of type Enum /// 2. The matching parameter is of type SwitchParameter /// 3. The matching parameter is declared with ValidateSetAttribute /// 4. Falls into the native command argument completion /// a null instance of CompletionResult is added to the end of the /// "result" list, to indicate that this particular argument completion /// has been processed already. If the "result" list is still empty, we /// will not go through the default argument completion steps anymore. /// </remarks> private static void ProcessParameter( string commandName, CommandAst commandAst, CompletionContext context, List<CompletionResult> result, MergedCompiledCommandParameter parameter, Dictionary<string, AstParameterArgumentPair> boundArguments = null) { CompletionResult fullMatch = null; Type parameterType = GetEffectiveParameterType(parameter.Parameter.Type); if (parameterType.IsArray) { parameterType = parameterType.GetElementType(); } if (parameterType.IsEnum) { RemoveLastNullCompletionResult(result); string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(parameterType); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); string wordToComplete = context.WordToComplete; string quote = HandleDoubleAndSingleQuote(ref wordToComplete); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List<string>(); foreach (string value in enumArray) { if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) { string completionText = quote == string.Empty ? value : quote + value + quote; fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value); continue; } if (pattern.IsMatch(value)) { enumList.Add(value); } } if (fullMatch != null) { result.Add(fullMatch); } enumList.Sort(); result.AddRange(from entry in enumList let completionText = quote == string.Empty ? entry : quote + entry + quote select new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); result.Add(CompletionResult.Null); return; } if (parameterType.Equals(typeof(SwitchParameter))) { RemoveLastNullCompletionResult(result); if (context.WordToComplete == string.Empty || context.WordToComplete.Equals("$", StringComparison.Ordinal)) { result.Add(new CompletionResult("$true", "$true", CompletionResultType.ParameterValue, "$true")); result.Add(new CompletionResult("$false", "$false", CompletionResultType.ParameterValue, "$false")); } result.Add(CompletionResult.Null); return; } foreach (ValidateArgumentsAttribute att in parameter.Parameter.ValidationAttributes) { if (att is ValidateSetAttribute setAtt) { RemoveLastNullCompletionResult(result); string wordToComplete = context.WordToComplete; string quote = HandleDoubleAndSingleQuote(ref wordToComplete); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var setList = new List<string>(); foreach (string value in setAtt.ValidValues) { if (value == string.Empty) { continue; } if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) { string completionText = quote == string.Empty ? value : quote + value + quote; fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterValue, value); continue; } if (pattern.IsMatch(value)) { setList.Add(value); } } if (fullMatch != null) { result.Add(fullMatch); } setList.Sort(); foreach (string entry in setList) { string realEntry = entry; string completionText = entry; if (quote == string.Empty) { if (CompletionRequiresQuotes(entry, false)) { realEntry = CodeGeneration.EscapeSingleQuotedStringContent(entry); completionText = "'" + realEntry + "'"; } } else { if (quote.Equals("'", StringComparison.OrdinalIgnoreCase)) { realEntry = CodeGeneration.EscapeSingleQuotedStringContent(entry); } completionText = quote + realEntry + quote; } result.Add(new CompletionResult(completionText, entry, CompletionResultType.ParameterValue, entry)); } result.Add(CompletionResult.Null); return; } } NativeCommandArgumentCompletion(commandName, parameter.Parameter, result, commandAst, context, boundArguments); } private static IEnumerable<PSTypeName> NativeCommandArgumentCompletion_InferTypesOfArgument( Dictionary<string, AstParameterArgumentPair> boundArguments, CommandAst commandAst, CompletionContext context, string parameterName) { if (boundArguments == null) { yield break; } AstParameterArgumentPair astParameterArgumentPair; if (!boundArguments.TryGetValue(parameterName, out astParameterArgumentPair)) { yield break; } Ast argumentAst = null; switch (astParameterArgumentPair.ParameterArgumentType) { case AstParameterArgumentType.AstPair: { AstPair astPair = (AstPair)astParameterArgumentPair; argumentAst = astPair.Argument; } break; case AstParameterArgumentType.PipeObject: { var pipelineAst = commandAst.Parent as PipelineAst; if (pipelineAst != null) { int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) { if (pipelineAst.PipelineElements[i] == commandAst) break; } if (i != 0) { argumentAst = pipelineAst.PipelineElements[i - 1]; } } } break; default: break; } if (argumentAst == null) { yield break; } ExpressionAst argumentExpressionAst = argumentAst as ExpressionAst; if (argumentExpressionAst == null) { CommandExpressionAst argumentCommandExpressionAst = argumentAst as CommandExpressionAst; if (argumentCommandExpressionAst != null) { argumentExpressionAst = argumentCommandExpressionAst.Expression; } } object argumentValue; if (argumentExpressionAst != null && SafeExprEvaluator.TrySafeEval(argumentExpressionAst, context.ExecutionContext, out argumentValue)) { if (argumentValue != null) { IEnumerable enumerable = LanguagePrimitives.GetEnumerable(argumentValue) ?? new object[] { argumentValue }; foreach (var element in enumerable) { if (element == null) { continue; } PSObject pso = PSObject.AsPSObject(element); if ((pso.TypeNames.Count > 0) && (!(pso.TypeNames[0].Equals(pso.BaseObject.GetType().FullName, StringComparison.OrdinalIgnoreCase)))) { yield return new PSTypeName(pso.TypeNames[0]); } if (pso.BaseObject is not PSCustomObject) { yield return new PSTypeName(pso.BaseObject.GetType()); } } yield break; } } foreach (PSTypeName typeName in AstTypeInference.InferTypeOf(argumentAst, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval)) { yield return typeName; } } internal static IList<string> NativeCommandArgumentCompletion_ExtractSecondaryArgument( Dictionary<string, AstParameterArgumentPair> boundArguments, string parameterName) { List<string> result = new List<string>(); if (boundArguments == null) { return result; } AstParameterArgumentPair argumentValue; if (!boundArguments.TryGetValue(parameterName, out argumentValue)) { return result; } switch (argumentValue.ParameterArgumentType) { case AstParameterArgumentType.AstPair: { var value = (AstPair)argumentValue; if (value.Argument is StringConstantExpressionAst) { var argument = (StringConstantExpressionAst)value.Argument; result.Add(argument.Value); } else if (value.Argument is ArrayLiteralAst) { var argument = (ArrayLiteralAst)value.Argument; foreach (ExpressionAst entry in argument.Elements) { var entryAsString = entry as StringConstantExpressionAst; if (entryAsString != null) { result.Add(entryAsString.Value); } else { result.Clear(); break; } } } break; } case AstParameterArgumentType.AstArray: { var value = (AstArrayPair)argumentValue; var argument = value.Argument; foreach (ExpressionAst entry in argument) { var entryAsString = entry as StringConstantExpressionAst; if (entryAsString != null) { result.Add(entryAsString.Value); } else { result.Clear(); break; } } break; } default: break; } return result; } private static void NativeCommandArgumentCompletion( string commandName, CompiledCommandParameter parameter, List<CompletionResult> result, CommandAst commandAst, CompletionContext context, Dictionary<string, AstParameterArgumentPair> boundArguments = null) { string parameterName = parameter.Name; // Fall back to the commandAst command name if a command name is not found. This can be caused by a script block or AST with the matching function definition being passed to CompleteInput // This allows for editors and other tools using CompleteInput with Script/AST definations to get values from RegisteredArgumentCompleters to better match the console experience. // See issue https://github.com/PowerShell/PowerShell/issues/10567 string actualCommandName = string.IsNullOrEmpty(commandName) ? commandAst.GetCommandName() : commandName; if (string.IsNullOrEmpty(actualCommandName)) { return; } string parameterFullName = $"{actualCommandName}:{parameterName}"; ScriptBlock customCompleter = GetCustomArgumentCompleter( "CustomArgumentCompleters", new[] { parameterFullName, parameterName }, context); if (customCompleter != null) { if (InvokeScriptArgumentCompleter( customCompleter, commandName, parameterName, context.WordToComplete, commandAst, context, result)) { return; } } var argumentCompleterAttribute = parameter.CompiledAttributes.OfType<ArgumentCompleterAttribute>().FirstOrDefault(); if (argumentCompleterAttribute != null) { try { var completer = argumentCompleterAttribute.CreateArgumentCompleter(); if (completer != null) { var customResults = completer.CompleteArgument(commandName, parameterName, context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); if (customResults != null) { result.AddRange(customResults); result.Add(CompletionResult.Null); return; } } else { if (InvokeScriptArgumentCompleter( argumentCompleterAttribute.ScriptBlock, commandName, parameterName, context.WordToComplete, commandAst, context, result)) { return; } } } catch (Exception) { } } var argumentCompletionsAttribute = parameter.CompiledAttributes.OfType<ArgumentCompletionsAttribute>().FirstOrDefault(); if (argumentCompletionsAttribute != null) { var customResults = argumentCompletionsAttribute.CompleteArgument(commandName, parameterName, context.WordToComplete, commandAst, GetBoundArgumentsAsHashtable(context)); if (customResults != null) { result.AddRange(customResults); result.Add(CompletionResult.Null); return; } } switch (commandName) { case "Get-Command": { if (parameterName.Equals("Module", StringComparison.OrdinalIgnoreCase)) { NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result); break; } if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var moduleNames = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Module"); if (moduleNames.Count > 0) { foreach (string module in moduleNames) { NativeCompletionGetCommand(context, module, parameterName, result); } } else { NativeCompletionGetCommand(context, /* moduleName: */ null, parameterName, result); } break; } if (parameterName.Equals("ParameterType", StringComparison.OrdinalIgnoreCase)) { NativeCompletionTypeName(context, result); break; } break; } case "Show-Command": { NativeCompletionGetHelpCommand(context, parameterName, /* isHelpRelated: */ false, result); break; } case "help": case "Get-Help": { NativeCompletionGetHelpCommand(context, parameterName, /* isHelpRelated: */ true, result); break; } case "Invoke-Expression": { if (parameterName.Equals("Command", StringComparison.OrdinalIgnoreCase)) { var commandResults = CompleteCommand(context); if (commandResults != null) result.AddRange(commandResults); } break; } case "Clear-EventLog": case "Get-EventLog": case "Limit-EventLog": case "Remove-EventLog": case "Write-EventLog": { NativeCompletionEventLogCommands(context, parameterName, result); break; } case "Get-Job": case "Receive-Job": case "Remove-Job": case "Stop-Job": case "Wait-Job": case "Suspend-Job": case "Resume-Job": { NativeCompletionJobCommands(context, parameterName, result); break; } case "Disable-ScheduledJob": case "Enable-ScheduledJob": case "Get-ScheduledJob": case "Unregister-ScheduledJob": { NativeCompletionScheduledJobCommands(context, parameterName, result); break; } case "Get-Module": { bool loadedModulesOnly = boundArguments == null || !boundArguments.ContainsKey("ListAvailable"); bool skipEditionCheck = !loadedModulesOnly && boundArguments.ContainsKey("SkipEditionCheck"); NativeCompletionModuleCommands(context, parameterName, result, loadedModulesOnly, skipEditionCheck: skipEditionCheck); break; } case "Remove-Module": { NativeCompletionModuleCommands(context, parameterName, result, loadedModulesOnly: true); break; } case "Import-Module": { bool skipEditionCheck = boundArguments != null && boundArguments.ContainsKey("SkipEditionCheck"); NativeCompletionModuleCommands(context, parameterName, result, isImportModule: true, skipEditionCheck: skipEditionCheck); break; } case "Debug-Process": case "Get-Process": case "Stop-Process": case "Wait-Process": case "Enter-PSHostProcess": { NativeCompletionProcessCommands(context, parameterName, result); break; } case "Get-PSDrive": case "Remove-PSDrive": { if (parameterName.Equals("PSProvider", StringComparison.OrdinalIgnoreCase)) { NativeCompletionProviderCommands(context, parameterName, result); } else if (parameterName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var psProviders = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "PSProvider"); if (psProviders.Count > 0) { foreach (string psProvider in psProviders) { NativeCompletionDriveCommands(context, psProvider, parameterName, result); } } else { NativeCompletionDriveCommands(context, /* psProvider: */ null, parameterName, result); } } break; } case "New-PSDrive": { NativeCompletionProviderCommands(context, parameterName, result); break; } case "Get-PSProvider": { NativeCompletionProviderCommands(context, parameterName, result); break; } case "Get-Service": case "Start-Service": case "Restart-Service": case "Resume-Service": case "Set-Service": case "Stop-Service": case "Suspend-Service": { NativeCompletionServiceCommands(context, parameterName, result); break; } case "Clear-Variable": case "Get-Variable": case "Remove-Variable": case "Set-Variable": { NativeCompletionVariableCommands(context, parameterName, result); break; } case "Get-Alias": { NativeCompletionAliasCommands(context, parameterName, result); break; } case "Get-TraceSource": case "Set-TraceSource": case "Trace-Command": { NativeCompletionTraceSourceCommands(context, parameterName, result); break; } case "Push-Location": case "Set-Location": { NativeCompletionSetLocationCommand(context, parameterName, result); break; } case "Move-Item": case "Copy-Item": { NativeCompletionCopyMoveItemCommand(context, parameterName, result); break; } case "New-Item": { NativeCompletionNewItemCommand(context, parameterName, result); break; } case "ForEach-Object": { if (parameterName.Equals("MemberName", StringComparison.OrdinalIgnoreCase)) { NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } break; } case "Group-Object": case "Measure-Object": case "Sort-Object": case "Where-Object": { if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) { NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } break; } case "Format-Custom": case "Format-List": case "Format-Table": case "Format-Wide": { if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) { NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } else if (parameterName.Equals("View", StringComparison.OrdinalIgnoreCase)) { NativeCompletionFormatViewName(context, boundArguments, result, commandAst, commandName); } break; } case "Select-Object": { if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) || parameterName.Equals("ExcludeProperty", StringComparison.OrdinalIgnoreCase) || parameterName.Equals("ExpandProperty", StringComparison.OrdinalIgnoreCase)) { NativeCompletionMemberName(context, result, commandAst, boundArguments?[parameterName]); } break; } case "New-Object": { if (parameterName.Equals("TypeName", StringComparison.OrdinalIgnoreCase)) { NativeCompletionTypeName(context, result); } break; } case "Get-CimClass": case "Get-CimInstance": case "Get-CimAssociatedInstance": case "Invoke-CimMethod": case "New-CimInstance": case "Register-CimIndicationEvent": case "Set-CimInstance": { // Avoids completion for parameters that expect a hashtable. if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase) || (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && !commandName.Equals("Get-CimInstance"))) { break; } HashSet<string> excludedValues = null; if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase) && boundArguments["Property"] is AstPair pair) { excludedValues = GetParameterValues(pair, context.CursorPosition.Offset); } NativeCompletionCimCommands(parameterName, boundArguments, result, commandAst, context, excludedValues, commandName); break; } default: { NativeCompletionPathArgument(context, parameterName, result); break; } } } private static Hashtable GetBoundArgumentsAsHashtable(CompletionContext context) { var result = new Hashtable(StringComparer.OrdinalIgnoreCase); if (context.PseudoBindingInfo != null) { var boundArguments = context.PseudoBindingInfo.BoundArguments; if (boundArguments != null) { foreach (var boundArgument in boundArguments) { var astPair = boundArgument.Value as AstPair; if (astPair != null) { var parameterAst = astPair.Argument as CommandParameterAst; var exprAst = parameterAst != null ? parameterAst.Argument : astPair.Argument as ExpressionAst; object value; if (exprAst != null && SafeExprEvaluator.TrySafeEval(exprAst, context.ExecutionContext, out value)) { result[boundArgument.Key] = value; } continue; } var switchPair = boundArgument.Value as SwitchPair; if (switchPair != null) { result[boundArgument.Key] = switchPair.Argument; continue; } // Ignored: // AstArrayPair - only used for ValueFromRemainingArguments, not that useful for tab completion // FakePair - missing argument, not that useful // PipeObjectPair - no actual argument, makes for a poor api } } } return result; } private static ScriptBlock GetCustomArgumentCompleter( string optionKey, IEnumerable<string> keys, CompletionContext context) { ScriptBlock scriptBlock; var options = context.Options; if (options != null) { var customCompleters = options[optionKey] as Hashtable; if (customCompleters != null) { foreach (var key in keys) { if (customCompleters.ContainsKey(key)) { scriptBlock = customCompleters[key] as ScriptBlock; if (scriptBlock != null) return scriptBlock; } } } } var registeredCompleters = optionKey.Equals("NativeArgumentCompleters", StringComparison.OrdinalIgnoreCase) ? context.NativeArgumentCompleters : context.CustomArgumentCompleters; if (registeredCompleters != null) { foreach (var key in keys) { if (registeredCompleters.TryGetValue(key, out scriptBlock)) { return scriptBlock; } } } return null; } private static bool InvokeScriptArgumentCompleter( ScriptBlock scriptBlock, string commandName, string parameterName, string wordToComplete, CommandAst commandAst, CompletionContext context, List<CompletionResult> resultList) { bool result = InvokeScriptArgumentCompleter( scriptBlock, new object[] { commandName, parameterName, wordToComplete, commandAst, GetBoundArgumentsAsHashtable(context) }, resultList); if (result) { resultList.Add(CompletionResult.Null); } return result; } private static bool InvokeScriptArgumentCompleter( ScriptBlock scriptBlock, object[] argumentsToCompleter, List<CompletionResult> result) { Collection<PSObject> customResults = null; try { customResults = scriptBlock.Invoke(argumentsToCompleter); } catch (Exception) { } if (customResults == null || customResults.Count == 0) { return false; } foreach (var customResult in customResults) { var resultAsCompletion = customResult.BaseObject as CompletionResult; if (resultAsCompletion != null) { result.Add(resultAsCompletion); continue; } var resultAsString = customResult.ToString(); result.Add(new CompletionResult(resultAsString)); } return true; } // All the methods for native command argument completion will add a null instance of the type CompletionResult to the end of the // "result" list, to indicate that this particular argument completion has fallen into one of the native command argument completion methods, // and has been processed already. So if the "result" list is still empty afterward, we will not go through the default argument completion anymore. #region Native Command Argument Completion private static void RemoveLastNullCompletionResult(List<CompletionResult> result) { if (result.Count > 0 && result[result.Count - 1].Equals(CompletionResult.Null)) { result.RemoveAt(result.Count - 1); } } private static void NativeCompletionCimCommands( string parameter, Dictionary<string, AstParameterArgumentPair> boundArguments, List<CompletionResult> result, CommandAst commandAst, CompletionContext context, HashSet<string> excludedValues, string commandName) { if (boundArguments != null) { AstParameterArgumentPair astParameterArgumentPair; if ((boundArguments.TryGetValue("ComputerName", out astParameterArgumentPair) || boundArguments.TryGetValue("CimSession", out astParameterArgumentPair)) && astParameterArgumentPair != null) { switch (astParameterArgumentPair.ParameterArgumentType) { case AstParameterArgumentType.PipeObject: case AstParameterArgumentType.Fake: break; default: return; // we won't tab-complete remote class names } } } RemoveLastNullCompletionResult(result); if (parameter.Equals("Namespace", StringComparison.OrdinalIgnoreCase)) { NativeCompletionCimNamespace(result, context); result.Add(CompletionResult.Null); return; } string pseudoboundCimNamespace = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "Namespace").FirstOrDefault(); if (parameter.Equals("ClassName", StringComparison.OrdinalIgnoreCase)) { NativeCompletionCimClassName(pseudoboundCimNamespace, result, context); result.Add(CompletionResult.Null); return; } bool gotInstance = false; IEnumerable<PSTypeName> cimClassTypeNames = null; string pseudoboundClassName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "ClassName").FirstOrDefault(); if (pseudoboundClassName != null) { gotInstance = false; var tmp = new List<PSTypeName>(); tmp.Add(new PSTypeName(typeof(CimInstance).FullName + "#" + (pseudoboundCimNamespace ?? "root/cimv2") + "/" + pseudoboundClassName)); cimClassTypeNames = tmp; } else if (boundArguments != null && boundArguments.ContainsKey("InputObject")) { gotInstance = true; cimClassTypeNames = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject"); } if (cimClassTypeNames != null) { foreach (PSTypeName typeName in cimClassTypeNames) { if (TypeInferenceContext.ParseCimCommandsTypeName(typeName, out pseudoboundCimNamespace, out pseudoboundClassName)) { if (parameter.Equals("ResultClassName", StringComparison.OrdinalIgnoreCase)) { NativeCompletionCimAssociationResultClassName(pseudoboundCimNamespace, pseudoboundClassName, result, context); } else if (parameter.Equals("MethodName", StringComparison.OrdinalIgnoreCase)) { NativeCompletionCimMethodName(pseudoboundCimNamespace, pseudoboundClassName, !gotInstance, result, context); } else if (parameter.Equals("Arguments", StringComparison.OrdinalIgnoreCase)) { string pseudoboundMethodName = NativeCommandArgumentCompletion_ExtractSecondaryArgument(boundArguments, "MethodName").FirstOrDefault(); NativeCompletionCimMethodArgumentName(pseudoboundCimNamespace, pseudoboundClassName, pseudoboundMethodName, excludedValues, result, context); } else if (parameter.Equals("Property", StringComparison.OrdinalIgnoreCase)) { bool includeReadOnly = !commandName.Equals("Set-CimInstance", StringComparison.OrdinalIgnoreCase); NativeCompletionCimPropertyName(pseudoboundCimNamespace, pseudoboundClassName, includeReadOnly, excludedValues, result, context); } } } result.Add(CompletionResult.Null); } } private static readonly ConcurrentDictionary<string, IEnumerable<string>> s_cimNamespaceAndClassNameToAssociationResultClassNames = new ConcurrentDictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase); private static IEnumerable<string> NativeCompletionCimAssociationResultClassName_GetResultClassNames( string cimNamespaceOfSource, string cimClassNameOfSource) { StringBuilder safeClassName = new StringBuilder(); foreach (char c in cimClassNameOfSource) { if (char.IsLetterOrDigit(c) || c == '_') { safeClassName.Append(c); } } List<string> resultClassNames = new List<string>(); using (var cimSession = CimSession.Create(null)) { CimClass cimClass = cimSession.GetClass(cimNamespaceOfSource ?? "root/cimv2", cimClassNameOfSource); while (cimClass != null) { string query = string.Format( CultureInfo.InvariantCulture, "associators of {{{0}}} WHERE SchemaOnly", cimClass.CimSystemProperties.ClassName); resultClassNames.AddRange( cimSession.QueryInstances(cimNamespaceOfSource ?? "root/cimv2", "WQL", query) .Select(static associationInstance => associationInstance.CimSystemProperties.ClassName)); cimClass = cimClass.CimSuperClass; } } resultClassNames.Sort(StringComparer.OrdinalIgnoreCase); return resultClassNames.Distinct(StringComparer.OrdinalIgnoreCase).ToList(); } private static void NativeCompletionCimAssociationResultClassName( string pseudoboundNamespace, string pseudoboundClassName, List<CompletionResult> result, CompletionContext context) { if (string.IsNullOrWhiteSpace(pseudoboundClassName)) { return; } IEnumerable<string> resultClassNames = s_cimNamespaceAndClassNameToAssociationResultClassNames.GetOrAdd( (pseudoboundNamespace ?? "root/cimv2") + ":" + pseudoboundClassName, _ => NativeCompletionCimAssociationResultClassName_GetResultClassNames(pseudoboundNamespace, pseudoboundClassName)); WildcardPattern resultClassNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); result.AddRange(resultClassNames .Where(resultClassNamePattern.IsMatch) .Select(x => new CompletionResult(x, x, CompletionResultType.Type, string.Format(CultureInfo.InvariantCulture, "{0} -> {1}", pseudoboundClassName, x)))); } private static void NativeCompletionCimMethodName( string pseudoboundNamespace, string pseudoboundClassName, bool staticMethod, List<CompletionResult> result, CompletionContext context) { if (string.IsNullOrWhiteSpace(pseudoboundClassName)) { return; } CimClass cimClass; using (var cimSession = CimSession.Create(null)) { cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName); } WildcardPattern methodNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); List<CompletionResult> localResults = new List<CompletionResult>(); foreach (CimMethodDeclaration methodDeclaration in cimClass.CimClassMethods) { string methodName = methodDeclaration.Name; if (!methodNamePattern.IsMatch(methodName)) { continue; } bool currentMethodIsStatic = methodDeclaration.Qualifiers.Any(static q => q.Name.Equals("Static", StringComparison.OrdinalIgnoreCase)); if ((currentMethodIsStatic && !staticMethod) || (!currentMethodIsStatic && staticMethod)) { continue; } StringBuilder tooltipText = new StringBuilder(); tooltipText.Append(methodName); tooltipText.Append('('); bool gotFirstParameter = false; foreach (var methodParameter in methodDeclaration.Parameters) { bool outParameter = methodParameter.Qualifiers.Any(static q => q.Name.Equals("Out", StringComparison.OrdinalIgnoreCase)); if (!gotFirstParameter) { gotFirstParameter = true; } else { tooltipText.Append(", "); } if (outParameter) { tooltipText.Append("[out] "); } tooltipText.Append(CimInstanceAdapter.CimTypeToTypeNameDisplayString(methodParameter.CimType)); tooltipText.Append(' '); tooltipText.Append(methodParameter.Name); if (outParameter) { continue; } } tooltipText.Append(')'); localResults.Add(new CompletionResult(methodName, methodName, CompletionResultType.Method, tooltipText.ToString())); } result.AddRange(localResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); } private static void NativeCompletionCimMethodArgumentName( string pseudoboundNamespace, string pseudoboundClassName, string pseudoboundMethodName, HashSet<string> excludedParameters, List<CompletionResult> result, CompletionContext context) { if (string.IsNullOrWhiteSpace(pseudoboundClassName) || string.IsNullOrWhiteSpace(pseudoboundMethodName)) { return; } CimClass cimClass; using (var cimSession = CimSession.Create(null)) { using var options = new CimOperationOptions(); options.Flags |= CimOperationFlags.LocalizedQualifiers; cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options); } var methodParameters = cimClass.CimClassMethods[pseudoboundMethodName]?.Parameters; if (methodParameters is null) { return; } foreach (var parameter in methodParameters) { if ((string.IsNullOrEmpty(context.WordToComplete) || parameter.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) && (excludedParameters is null || !excludedParameters.Contains(parameter.Name)) && parameter.Qualifiers["In"]?.Value is true) { string parameterDescription = parameter.Qualifiers["Description"]?.Value as string ?? string.Empty; string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(parameter.CimType)}] {parameterDescription}"; result.Add(new CompletionResult(parameter.Name, parameter.Name, CompletionResultType.Property, toolTip)); } } } private static void NativeCompletionCimPropertyName( string pseudoboundNamespace, string pseudoboundClassName, bool includeReadOnly, HashSet<string> excludedProperties, List<CompletionResult> result, CompletionContext context) { if (string.IsNullOrWhiteSpace(pseudoboundClassName)) { return; } CimClass cimClass; using (var cimSession = CimSession.Create(null)) { using var options = new CimOperationOptions(); options.Flags |= CimOperationFlags.LocalizedQualifiers; cimClass = cimSession.GetClass(pseudoboundNamespace ?? "root/cimv2", pseudoboundClassName, options); } foreach (var property in cimClass.CimClassProperties) { bool isReadOnly = (property.Flags & CimFlags.ReadOnly) != 0; if ((!isReadOnly || (isReadOnly && includeReadOnly)) && (string.IsNullOrEmpty(context.WordToComplete) || property.Name.StartsWith(context.WordToComplete, StringComparison.OrdinalIgnoreCase)) && (excludedProperties is null || !excludedProperties.Contains(property.Name))) { string propertyDescription = property.Qualifiers["Description"]?.Value as string ?? string.Empty; string accessString = isReadOnly ? "{ get; }" : "{ get; set; }"; string toolTip = $"[{CimInstanceAdapter.CimTypeToTypeNameDisplayString(property.CimType)}] {accessString} {propertyDescription}"; result.Add(new CompletionResult(property.Name, property.Name, CompletionResultType.Property, toolTip)); } } } private static readonly ConcurrentDictionary<string, IEnumerable<string>> s_cimNamespaceToClassNames = new ConcurrentDictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase); private static IEnumerable<string> NativeCompletionCimClassName_GetClassNames(string targetNamespace) { List<string> result = new List<string>(); using (CimSession cimSession = CimSession.Create(null)) { using (var operationOptions = new CimOperationOptions { ClassNamesOnly = true }) foreach (CimClass cimClass in cimSession.EnumerateClasses(targetNamespace, null, operationOptions)) using (cimClass) { string className = cimClass.CimSystemProperties.ClassName; result.Add(className); } } return result; } private static void NativeCompletionCimClassName( string pseudoBoundNamespace, List<CompletionResult> result, CompletionContext context) { string targetNamespace = pseudoBoundNamespace ?? "root/cimv2"; List<string> regularClasses = new List<string>(); List<string> systemClasses = new List<string>(); IEnumerable<string> allClasses = s_cimNamespaceToClassNames.GetOrAdd( targetNamespace, NativeCompletionCimClassName_GetClassNames); WildcardPattern classNamePattern = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.CultureInvariant | WildcardOptions.IgnoreCase); foreach (string className in allClasses) { if (context.Helper.CancelTabCompletion) { break; } if (!classNamePattern.IsMatch(className)) { continue; } if (className.Length > 0 && className[0] == '_') { systemClasses.Add(className); } else { regularClasses.Add(className); } } regularClasses.Sort(StringComparer.OrdinalIgnoreCase); systemClasses.Sort(StringComparer.OrdinalIgnoreCase); result.AddRange( regularClasses.Concat(systemClasses) .Select(className => new CompletionResult(className, className, CompletionResultType.Type, targetNamespace + ":" + className))); } private static void NativeCompletionCimNamespace( List<CompletionResult> result, CompletionContext context) { string containerNamespace = "root"; string prefixOfChildNamespace = string.Empty; if (!string.IsNullOrEmpty(context.WordToComplete)) { int lastSlashOrBackslash = context.WordToComplete.LastIndexOfAny(Utils.Separators.Directory); if (lastSlashOrBackslash != (-1)) { containerNamespace = context.WordToComplete.Substring(0, lastSlashOrBackslash); prefixOfChildNamespace = context.WordToComplete.Substring(lastSlashOrBackslash + 1); } } List<CompletionResult> namespaceResults = new List<CompletionResult>(); WildcardPattern childNamespacePattern = WildcardPattern.Get(prefixOfChildNamespace + "*", WildcardOptions.IgnoreCase | WildcardOptions.CultureInvariant); using (CimSession cimSession = CimSession.Create(null)) { foreach (CimInstance namespaceInstance in cimSession.EnumerateInstances(containerNamespace, "__Namespace")) using (namespaceInstance) { if (context.Helper.CancelTabCompletion) { break; } CimProperty namespaceNameProperty = namespaceInstance.CimInstanceProperties["Name"]; if (namespaceNameProperty == null) { continue; } if (!(namespaceNameProperty.Value is string childNamespace)) { continue; } if (!childNamespacePattern.IsMatch(childNamespace)) { continue; } namespaceResults.Add(new CompletionResult( containerNamespace + "/" + childNamespace, childNamespace, CompletionResultType.Namespace, containerNamespace + "/" + childNamespace)); } } result.AddRange(namespaceResults.OrderBy(static x => x.ListItemText, StringComparer.OrdinalIgnoreCase)); } private static void NativeCompletionGetCommand(CompletionContext context, string moduleName, string paramName, List<CompletionResult> result) { if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); // Available commands var commandResults = CompleteCommand(context, moduleName); if (commandResults != null) result.AddRange(commandResults); // Consider files only if the -Module parameter is not present if (moduleName == null) { // ps1 files and directories. We only complete the files with .ps1 extension for Get-Command, because the -Syntax // may only works on files with .ps1 extension var ps1Extension = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { StringLiterals.PowerShellScriptFileExtension }; var moduleFilesResults = new List<CompletionResult>(CompleteFilename(context, /* containerOnly: */ false, ps1Extension)); if (moduleFilesResults.Count > 0) result.AddRange(moduleFilesResults); } result.Add(CompletionResult.Null); } else if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Module", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); var modules = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var moduleResults = CompleteModuleName(context, loadedModulesOnly: true); if (moduleResults != null) { foreach (CompletionResult moduleResult in moduleResults) { if (!modules.Contains(moduleResult.ToolTip)) { modules.Add(moduleResult.ToolTip); result.Add(moduleResult); } } } moduleResults = CompleteModuleName(context, loadedModulesOnly: false); if (moduleResults != null) { foreach (CompletionResult moduleResult in moduleResults) { if (!modules.Contains(moduleResult.ToolTip)) { modules.Add(moduleResult.ToolTip); result.Add(moduleResult); } } } result.Add(CompletionResult.Null); } } private static void NativeCompletionGetHelpCommand(CompletionContext context, string paramName, bool isHelpRelated, List<CompletionResult> result) { if (!string.IsNullOrEmpty(paramName) && paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); // Available commands const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.Alias | CommandTypes.ExternalScript | CommandTypes.Configuration; var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes); if (commandResults != null) result.AddRange(commandResults); // ps1 files and directories var ps1Extension = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { StringLiterals.PowerShellScriptFileExtension }; var fileResults = new List<CompletionResult>(CompleteFilename(context, /* containerOnly: */ false, ps1Extension)); if (fileResults.Count > 0) result.AddRange(fileResults); if (isHelpRelated) { // Available topics var helpTopicResults = CompleteHelpTopics(context); if (helpTopicResults != null) result.AddRange(helpTopicResults); } result.Add(CompletionResult.Null); } } private static void NativeCompletionEventLogCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (!string.IsNullOrEmpty(paramName) && paramName.Equals("LogName", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); var logName = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref logName); if (!logName.EndsWith('*')) { logName += "*"; } var pattern = WildcardPattern.Get(logName, WildcardOptions.IgnoreCase); var powerShellExecutionHelper = context.Helper; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-EventLog").AddParameter("LogName", "*"); Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects != null) { foreach (dynamic eventLog in psObjects) { var completionText = eventLog.Log.ToString(); var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } if (pattern.IsMatch(listItemText)) { result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } } result.Add(CompletionResult.Null); } } private static void NativeCompletionJobCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) return; var wordToComplete = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { wordToComplete += "*"; } var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); var paramIsName = paramName.Equals("Name", StringComparison.OrdinalIgnoreCase); var (parameterName, value) = paramIsName ? ("Name", wordToComplete) : ("IncludeChildJob", (object)true); var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper.AddCommandWithPreferenceSetting("Get-Job", typeof(GetJobCommand)).AddParameter(parameterName, value); Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); foreach (dynamic psJob in psObjects) { var completionText = psJob.Id.ToString(); if (pattern.IsMatch(completionText)) { var listItemText = completionText; completionText = quote + completionText + quote; result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } else if (paramName.Equals("InstanceId", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); foreach (dynamic psJob in psObjects) { var completionText = psJob.InstanceId.ToString(); if (pattern.IsMatch(completionText)) { var listItemText = completionText; completionText = quote + completionText + quote; result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } else if (paramIsName) { RemoveLastNullCompletionResult(result); foreach (dynamic psJob in psObjects) { var completionText = psJob.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } } private static void NativeCompletionScheduledJobCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) return; var wordToComplete = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { wordToComplete += "*"; } var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); var powerShellExecutionHelper = context.Helper; if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { powerShellExecutionHelper.AddCommandWithPreferenceSetting("PSScheduledJob\\Get-ScheduledJob").AddParameter("Name", wordToComplete); } else { powerShellExecutionHelper.AddCommandWithPreferenceSetting("PSScheduledJob\\Get-ScheduledJob"); } Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); foreach (dynamic psJob in psObjects) { var completionText = psJob.Id.ToString(); if (pattern.IsMatch(completionText)) { var listItemText = completionText; completionText = quote + completionText + quote; result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); foreach (dynamic psJob in psObjects) { var completionText = psJob.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } } private static void NativeCompletionModuleCommands( CompletionContext context, string paramName, List<CompletionResult> result, bool loadedModulesOnly = false, bool isImportModule = false, bool skipEditionCheck = false) { if (string.IsNullOrEmpty(paramName)) { return; } if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); if (isImportModule) { var moduleExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { StringLiterals.PowerShellScriptFileExtension, StringLiterals.PowerShellModuleFileExtension, StringLiterals.PowerShellDataFileExtension, StringLiterals.PowerShellNgenAssemblyExtension, StringLiterals.PowerShellILAssemblyExtension, StringLiterals.PowerShellILExecutableExtension, StringLiterals.PowerShellCmdletizationFileExtension }; var moduleFilesResults = new List<CompletionResult>(CompleteFilename(context, containerOnly: false, moduleExtensions)); if (moduleFilesResults.Count > 0) result.AddRange(moduleFilesResults); var assemblyOrModuleName = context.WordToComplete; if (assemblyOrModuleName.IndexOfAny(Utils.Separators.DirectoryOrDrive) != -1) { // The partial input is a path, then we don't iterate modules under $ENV:PSModulePath return; } } var moduleResults = CompleteModuleName(context, loadedModulesOnly, skipEditionCheck); if (moduleResults != null && moduleResults.Count > 0) result.AddRange(moduleResults); result.Add(CompletionResult.Null); } else if (paramName.Equals("Assembly", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); var moduleExtensions = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { ".dll" }; var moduleFilesResults = new List<CompletionResult>(CompleteFilename(context, /* containerOnly: */ false, moduleExtensions)); if (moduleFilesResults.Count > 0) result.AddRange(moduleFilesResults); result.Add(CompletionResult.Null); } } private static void NativeCompletionProcessCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) return; var wordToComplete = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { wordToComplete += "*"; } var powerShellExecutionHelper = context.Helper; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Process"); } else { powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Process").AddParameter("Name", wordToComplete); } Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects == null) return; if (paramName.Equals("Id", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); foreach (dynamic process in psObjects) { var processId = process.Id.ToString(); if (pattern.IsMatch(processId)) { var processName = process.Name; var idAndName = $"{processId} - {processName}"; processId = quote + processId + quote; result.Add(new CompletionResult(processId, idAndName, CompletionResultType.ParameterValue, idAndName)); } } result.Add(CompletionResult.Null); } else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); var uniqueSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (dynamic process in psObjects) { var completionText = process.Name; var listItemText = completionText; if (uniqueSet.Contains(completionText)) continue; uniqueSet.Add(completionText); if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } // on macOS, system processes names will be empty if PowerShell isn't run as `sudo` if (string.IsNullOrEmpty(listItemText)) { continue; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } } private static void NativeCompletionProviderCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || !paramName.Equals("PSProvider", StringComparison.OrdinalIgnoreCase)) { return; } RemoveLastNullCompletionResult(result); var providerName = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref providerName); if (!providerName.EndsWith('*')) { providerName += "*"; } var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSProvider").AddParameter("PSProvider", providerName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); if (psObjects == null) return; foreach (dynamic providerInfo in psObjects) { var completionText = providerInfo.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } private static void NativeCompletionDriveCommands(CompletionContext context, string psProvider, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) return; RemoveLastNullCompletionResult(result); var wordToComplete = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { wordToComplete += "*"; } var powerShellExecutionHelper = context.Helper; var powershell = powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive") .AddParameter("Name", wordToComplete); if (psProvider != null) powershell.AddParameter("PSProvider", psProvider); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); if (psObjects != null) { foreach (dynamic driveInfo in psObjects) { var completionText = driveInfo.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } private static void NativeCompletionServiceCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) return; var wordToComplete = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); if (!wordToComplete.EndsWith('*')) { wordToComplete += "*"; } Exception exceptionThrown; var powerShellExecutionHelper = context.Helper; if (paramName.Equals("DisplayName", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Service") .AddParameter("DisplayName", wordToComplete) .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", "DisplayName"); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects != null) { foreach (dynamic serviceInfo in psObjects) { var completionText = serviceInfo.DisplayName; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } else if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { RemoveLastNullCompletionResult(result); powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Service").AddParameter("Name", wordToComplete); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects != null) { foreach (dynamic serviceInfo in psObjects) { var completionText = serviceInfo.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } result.Add(CompletionResult.Null); } } private static void NativeCompletionVariableCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { return; } RemoveLastNullCompletionResult(result); var variableName = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref variableName); if (!variableName.EndsWith('*')) { variableName += "*"; } var powerShellExecutionHelper = context.Helper; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Variable").AddParameter("Name", variableName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _); if (psObjects == null) return; foreach (dynamic variable in psObjects) { var effectiveQuote = quote; var completionText = variable.Name; var listItemText = completionText; // Handle special characters ? and * in variable names if (completionText.IndexOfAny(Utils.Separators.StarOrQuestion) != -1) { effectiveQuote = "'"; completionText = completionText.Replace("?", "`?"); completionText = completionText.Replace("*", "`*"); } if (!completionText.Equals("$", StringComparison.Ordinal) && CompletionRequiresQuotes(completionText, false)) { var quoteInUse = effectiveQuote == string.Empty ? "'" : effectiveQuote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = effectiveQuote + completionText + effectiveQuote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } private static void NativeCompletionAliasCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || (!paramName.Equals("Definition", StringComparison.OrdinalIgnoreCase) && !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase))) { return; } RemoveLastNullCompletionResult(result); var powerShellExecutionHelper = context.Helper; if (paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { var commandName = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref commandName); if (!commandName.EndsWith('*')) { commandName += "*"; } Exception exceptionThrown; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-Alias").AddParameter("Name", commandName); var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects != null) { foreach (dynamic aliasInfo in psObjects) { var completionText = aliasInfo.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } } } else { // Complete for the parameter Definition // Available commands const CommandTypes commandTypes = CommandTypes.Cmdlet | CommandTypes.Function | CommandTypes.ExternalScript | CommandTypes.Configuration; var commandResults = CompleteCommand(context, /* moduleName: */ null, commandTypes); if (commandResults != null && commandResults.Count > 0) result.AddRange(commandResults); // The parameter Definition takes a file var fileResults = new List<CompletionResult>(CompleteFilename(context)); if (fileResults.Count > 0) result.AddRange(fileResults); } result.Add(CompletionResult.Null); } private static void NativeCompletionTraceSourceCommands(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || !paramName.Equals("Name", StringComparison.OrdinalIgnoreCase)) { return; } RemoveLastNullCompletionResult(result); var traceSourceName = context.WordToComplete ?? string.Empty; var quote = HandleDoubleAndSingleQuote(ref traceSourceName); if (!traceSourceName.EndsWith('*')) { traceSourceName += "*"; } var powerShellExecutionHelper = context.Helper; var powershell = powerShellExecutionHelper.AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Get-TraceSource").AddParameter("Name", traceSourceName); Exception exceptionThrown; var psObjects = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psObjects == null) return; foreach (dynamic trace in psObjects) { var completionText = trace.Name; var listItemText = completionText; if (CompletionRequiresQuotes(completionText, false)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") completionText = completionText.Replace("'", "''"); completionText = quoteInUse + completionText + quoteInUse; } else { completionText = quote + completionText + quote; } result.Add(new CompletionResult(completionText, listItemText, CompletionResultType.ParameterValue, listItemText)); } result.Add(CompletionResult.Null); } private static void NativeCompletionSetLocationCommand(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || (!paramName.Equals("Path", StringComparison.OrdinalIgnoreCase) && !paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase))) { return; } RemoveLastNullCompletionResult(result); context.WordToComplete ??= string.Empty; var clearLiteralPath = false; if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)) { clearLiteralPath = TurnOnLiteralPathOption(context); } try { var fileNameResults = CompleteFilename(context, containerOnly: true, extension: null); if (fileNameResults != null) result.AddRange(fileNameResults); } finally { if (clearLiteralPath) context.Options.Remove("LiteralPaths"); } result.Add(CompletionResult.Null); } /// <summary> /// Provides completion results for NewItemCommand. /// </summary> /// <param name="context">Completion context.</param> /// <param name="paramName">Name of the parameter whose value needs completion.</param> /// <param name="result">List of completion suggestions.</param> private static void NativeCompletionNewItemCommand(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) { return; } var executionContext = context.ExecutionContext; var boundArgs = GetBoundArgumentsAsHashtable(context); var providedPath = boundArgs["Path"] as string ?? executionContext.SessionState.Path.CurrentLocation.Path; ProviderInfo provider; executionContext.LocationGlobber.GetProviderPath(providedPath, out provider); var isFileSystem = provider != null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); // AutoComplete only if filesystem provider. if (isFileSystem) { if (paramName.Equals("ItemType", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrEmpty(context.WordToComplete)) { WildcardPattern patternEvaluator = WildcardPattern.Get(context.WordToComplete + "*", WildcardOptions.IgnoreCase); if (patternEvaluator.IsMatch("file")) { result.Add(new CompletionResult("File")); } else if (patternEvaluator.IsMatch("directory")) { result.Add(new CompletionResult("Directory")); } else if (patternEvaluator.IsMatch("symboliclink")) { result.Add(new CompletionResult("SymbolicLink")); } else if (patternEvaluator.IsMatch("junction")) { result.Add(new CompletionResult("Junction")); } else if (patternEvaluator.IsMatch("hardlink")) { result.Add(new CompletionResult("HardLink")); } } else { result.Add(new CompletionResult("File")); result.Add(new CompletionResult("Directory")); result.Add(new CompletionResult("SymbolicLink")); result.Add(new CompletionResult("Junction")); result.Add(new CompletionResult("HardLink")); } result.Add(CompletionResult.Null); } } } private static void NativeCompletionCopyMoveItemCommand(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName)) { return; } if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) || paramName.Equals("Path", StringComparison.OrdinalIgnoreCase)) { NativeCompletionPathArgument(context, paramName, result); } else if (paramName.Equals("Destination", StringComparison.OrdinalIgnoreCase)) { // The parameter Destination for Move-Item and Copy-Item takes literal path RemoveLastNullCompletionResult(result); context.WordToComplete ??= string.Empty; var clearLiteralPath = TurnOnLiteralPathOption(context); try { var fileNameResults = CompleteFilename(context); if (fileNameResults != null) result.AddRange(fileNameResults); } finally { if (clearLiteralPath) context.Options.Remove("LiteralPaths"); } result.Add(CompletionResult.Null); } } private static void NativeCompletionPathArgument(CompletionContext context, string paramName, List<CompletionResult> result) { if (string.IsNullOrEmpty(paramName) || (!paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase) && (!paramName.Equals("Path", StringComparison.OrdinalIgnoreCase)) && (!paramName.Equals("FilePath", StringComparison.OrdinalIgnoreCase)))) { return; } RemoveLastNullCompletionResult(result); context.WordToComplete ??= string.Empty; var clearLiteralPath = false; if (paramName.Equals("LiteralPath", StringComparison.OrdinalIgnoreCase)) { clearLiteralPath = TurnOnLiteralPathOption(context); } try { var fileNameResults = CompleteFilename(context); if (fileNameResults != null) result.AddRange(fileNameResults); } finally { if (clearLiteralPath) context.Options.Remove("LiteralPaths"); } result.Add(CompletionResult.Null); } private static IEnumerable<PSTypeName> GetInferenceTypes(CompletionContext context, CommandAst commandAst) { // Command is something like where-object/foreach-object/format-list/etc. where there is a parameter that is a property name // and we want member names based on the input object, which is either the parameter InputObject, or comes from the pipeline. if (commandAst.Parent is not PipelineAst pipelineAst) { return null; } int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) { if (pipelineAst.PipelineElements[i] == commandAst) { break; } } IEnumerable<PSTypeName> prevType = null; if (i == 0) { // based on a type of the argument which is binded to 'InputObject' parameter. AstParameterArgumentPair pair; if (!context.PseudoBindingInfo.BoundArguments.TryGetValue("InputObject", out pair) || !pair.ArgumentSpecified) { return null; } var astPair = pair as AstPair; if (astPair == null || astPair.Argument == null) { return null; } prevType = AstTypeInference.InferTypeOf(astPair.Argument, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } else { // based on OutputTypeAttribute() of the first cmdlet in pipeline. prevType = AstTypeInference.InferTypeOf(pipelineAst.PipelineElements[i - 1], context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } return prevType; } private static void NativeCompletionMemberName(CompletionContext context, List<CompletionResult> result, CommandAst commandAst, AstParameterArgumentPair parameterInfo) { IEnumerable<PSTypeName> prevType = GetInferenceTypes(context, commandAst); if (prevType is not null) { HashSet<string> excludedMembers = null; if (parameterInfo is AstPair pair) { excludedMembers = GetParameterValues(pair, context.CursorPosition.Offset); } CompleteMemberByInferredType(context.TypeInferenceContext, prevType, result, context.WordToComplete + "*", filter: IsPropertyMember, isStatic: false, excludedMembers); } result.Add(CompletionResult.Null); } /// <summary> /// Returns all string values bound to a parameter except the one the cursor is currently at. /// </summary> private static HashSet<string>GetParameterValues(AstPair parameter, int cursorOffset) { var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var parameterValues = parameter.Argument.FindAll(ast => !(cursorOffset >= ast.Extent.StartOffset && cursorOffset <= ast.Extent.EndOffset) && ast is StringConstantExpressionAst, searchNestedScriptBlocks: false); foreach (Ast ast in parameterValues) { result.Add(ast.Extent.Text); } return result; } private static void NativeCompletionFormatViewName( CompletionContext context, Dictionary<string, AstParameterArgumentPair> boundArguments, List<CompletionResult> result, CommandAst commandAst, string commandName) { IEnumerable<PSTypeName> prevType = NativeCommandArgumentCompletion_InferTypesOfArgument(boundArguments, commandAst, context, "InputObject"); if (prevType is not null) { string[] inferTypeNames = prevType.Select(t => t.Name).ToArray(); CompleteFormatViewByInferredType(context, inferTypeNames, result, commandName); } result.Add(CompletionResult.Null); } private static void NativeCompletionTypeName(CompletionContext context, List<CompletionResult> result) { var wordToComplete = context.WordToComplete; var isQuoted = wordToComplete.Length > 0 && (wordToComplete[0].IsSingleQuote() || wordToComplete[0].IsDoubleQuote()); string prefix = string.Empty; string suffix = string.Empty; if (isQuoted) { prefix = suffix = wordToComplete.Substring(0, 1); var endQuoted = (wordToComplete.Length > 1) && wordToComplete[wordToComplete.Length - 1] == wordToComplete[0]; wordToComplete = wordToComplete.Substring(1, wordToComplete.Length - (endQuoted ? 2 : 1)); } if (wordToComplete.Contains('[')) { var cursor = (InternalScriptPosition)context.CursorPosition; cursor = cursor.CloneWithNewOffset(cursor.Offset - context.TokenAtCursor.Extent.StartOffset - (isQuoted ? 1 : 0)); var fullTypeName = Parser.ScanType(wordToComplete, ignoreErrors: true); var typeNameToComplete = CompletionAnalysis.FindTypeNameToComplete(fullTypeName, cursor); if (typeNameToComplete == null) return; var openBrackets = 0; var closeBrackets = 0; foreach (char c in wordToComplete) { if (c == '[') openBrackets += 1; else if (c == ']') closeBrackets += 1; } wordToComplete = typeNameToComplete.FullName; var typeNameText = fullTypeName.Extent.Text; if (!isQuoted) { // We need to add quotes - the square bracket messes up parsing the argument prefix = suffix = "'"; } if (closeBrackets < openBrackets) { suffix = suffix.Insert(0, new string(']', (openBrackets - closeBrackets))); } if (isQuoted && closeBrackets == openBrackets) { // Already quoted, and has matching []. We can give a better Intellisense experience // if we only replace the minimum. context.ReplacementIndex = typeNameToComplete.Extent.StartOffset + context.TokenAtCursor.Extent.StartOffset + 1; context.ReplacementLength = wordToComplete.Length; prefix = suffix = string.Empty; } else { prefix += typeNameText.Substring(0, typeNameToComplete.Extent.StartOffset); suffix = suffix.Insert(0, typeNameText.Substring(typeNameToComplete.Extent.EndOffset)); } } context.WordToComplete = wordToComplete; var typeResults = CompleteType(context, prefix, suffix); if (typeResults != null) { result.AddRange(typeResults); } result.Add(CompletionResult.Null); } #endregion Native Command Argument Completion /// <summary> /// Find the positional argument at the specific position from the parsed argument list. /// </summary> /// <param name="parsedArguments"></param> /// <param name="position"></param> /// <param name="lastPositionalArgument"></param> /// <returns> /// If the command line after the [tab] will not be truncated, the return value could be non-null: Get-Cmdlet [tab] abc /// If the command line after the [tab] is truncated, the return value will always be null /// </returns> private static AstPair FindTargetPositionalArgument(Collection<AstParameterArgumentPair> parsedArguments, int position, out AstPair lastPositionalArgument) { int index = 0; lastPositionalArgument = null; foreach (AstParameterArgumentPair pair in parsedArguments) { if (!pair.ParameterSpecified && index == position) return (AstPair)pair; else if (!pair.ParameterSpecified) { index++; lastPositionalArgument = (AstPair)pair; } } // Cannot find an existing positional argument at 'position' return null; } /// <summary> /// Find the location where 'tab' is typed based on the line and column. /// </summary> private static ArgumentLocation FindTargetArgumentLocation(Collection<AstParameterArgumentPair> parsedArguments, Token token) { int position = 0; AstParameterArgumentPair prevArg = null; foreach (AstParameterArgumentPair pair in parsedArguments) { switch (pair.ParameterArgumentType) { case AstParameterArgumentType.AstPair: { var arg = (AstPair)pair; if (arg.ParameterSpecified) { // Named argument if (arg.Parameter.Extent.StartOffset > token.Extent.StartOffset) { // case: Get-Cmdlet <tab> -Param abc return GenerateArgumentLocation(prevArg, position); } if (!arg.ParameterContainsArgument && arg.Argument.Extent.StartOffset > token.Extent.StartOffset) { // case: Get-Cmdlet -Param <tab> abc return new ArgumentLocation() { Argument = arg, IsPositional = false, Position = -1 }; } } else { // Positional argument if (arg.Argument.Extent.StartOffset > token.Extent.StartOffset) { // case: Get-Cmdlet <tab> abc return GenerateArgumentLocation(prevArg, position); } position++; } prevArg = arg; } break; case AstParameterArgumentType.Fake: case AstParameterArgumentType.Switch: { if (pair.Parameter.Extent.StartOffset > token.Extent.StartOffset) { return GenerateArgumentLocation(prevArg, position); } prevArg = pair; } break; case AstParameterArgumentType.AstArray: case AstParameterArgumentType.PipeObject: Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject"); break; } } // The 'tab' should be typed after the last argument return GenerateArgumentLocation(prevArg, position); } /// <summary> /// </summary> /// <param name="prev">The argument that is right before the 'tab' location.</param> /// <param name="position">The number of positional arguments before the 'tab' location.</param> /// <returns></returns> private static ArgumentLocation GenerateArgumentLocation(AstParameterArgumentPair prev, int position) { // Tab is typed before the first argument if (prev == null) { return new ArgumentLocation() { Argument = null, IsPositional = true, Position = 0 }; } switch (prev.ParameterArgumentType) { case AstParameterArgumentType.AstPair: case AstParameterArgumentType.Switch: if (!prev.ParameterSpecified) return new ArgumentLocation() { Argument = null, IsPositional = true, Position = position }; return prev.Parameter.Extent.Text.EndsWith(':') ? new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 } : new ArgumentLocation() { Argument = null, IsPositional = true, Position = position }; case AstParameterArgumentType.Fake: return new ArgumentLocation() { Argument = prev, IsPositional = false, Position = -1 }; default: Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject"); return null; } } /// <summary> /// Find the location where 'tab' is typed based on the expressionAst. /// </summary> /// <param name="parsedArguments"></param> /// <param name="expAst"></param> /// <returns></returns> private static ArgumentLocation FindTargetArgumentLocation(Collection<AstParameterArgumentPair> parsedArguments, ExpressionAst expAst) { Diagnostics.Assert(expAst != null, "Caller needs to make sure expAst is not null"); int position = 0; foreach (AstParameterArgumentPair pair in parsedArguments) { switch (pair.ParameterArgumentType) { case AstParameterArgumentType.AstPair: { AstPair arg = (AstPair)pair; if (arg.ArgumentIsCommandParameterAst) continue; if (arg.ParameterContainsArgument && arg.Argument == expAst) { return new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg }; } if (arg.Argument.GetHashCode() == expAst.GetHashCode()) { return arg.ParameterSpecified ? new ArgumentLocation() { IsPositional = false, Position = -1, Argument = arg } : new ArgumentLocation() { IsPositional = true, Position = position, Argument = arg }; } if (!arg.ParameterSpecified) position++; } break; case AstParameterArgumentType.Fake: case AstParameterArgumentType.Switch: // FakePair and SwitchPair contains no ExpressionAst break; case AstParameterArgumentType.AstArray: case AstParameterArgumentType.PipeObject: Diagnostics.Assert(false, "parsed arguments should not contain AstArray and PipeObject arguments"); break; } } // We should be able to find the ExpAst from the parsed argument list, if all parameters was specified correctly. // We may try to complete something incorrect // ls -Recurse -QQQ qwe<+tab> return null; } private sealed class ArgumentLocation { internal bool IsPositional { get; set; } internal int Position { get; set; } internal AstParameterArgumentPair Argument { get; set; } } #endregion Command Arguments #region Filenames /// <summary> /// </summary> /// <param name="fileName"></param> /// <returns></returns> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] public static IEnumerable<CompletionResult> CompleteFilename(string fileName) { var runspace = Runspace.DefaultRunspace; if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; } var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace)); var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext; return CompleteFilename(new CompletionContext { WordToComplete = fileName, Helper = helper, ExecutionContext = executionContext }); } internal static IEnumerable<CompletionResult> CompleteFilename(CompletionContext context) { return CompleteFilename(context, containerOnly: false, extension: null); } [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly")] internal static IEnumerable<CompletionResult> CompleteFilename(CompletionContext context, bool containerOnly, HashSet<string> extension) { var wordToComplete = context.WordToComplete; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); var results = new List<CompletionResult>(); // First, try to match \\server\share var shareMatch = Regex.Match(wordToComplete, "^\\\\\\\\([^\\\\]+)\\\\([^\\\\]*)$"); if (shareMatch.Success) { // Only match share names, no filenames. var server = shareMatch.Groups[1].Value; var sharePattern = WildcardPattern.Get(shareMatch.Groups[2].Value + "*", WildcardOptions.IgnoreCase); var ignoreHidden = context.GetOption("IgnoreHiddenShares", @default: false); var shares = GetFileShares(server, ignoreHidden); foreach (var share in shares) { if (sharePattern.IsMatch(share)) { string shareFullPath = "\\\\" + server + "\\" + share; if (quote != string.Empty) { shareFullPath = quote + shareFullPath + quote; } results.Add(new CompletionResult(shareFullPath, shareFullPath, CompletionResultType.ProviderContainer, shareFullPath)); } } } else { // We want to prefer relative paths in a completion result unless the user has already // specified a drive or portion of the path. var executionContext = context.ExecutionContext; var defaultRelative = string.IsNullOrWhiteSpace(wordToComplete) || (wordToComplete.IndexOfAny(Utils.Separators.Directory) != 0 && !Regex.Match(wordToComplete, @"^~[\\/]+.*").Success && !executionContext.LocationGlobber.IsAbsolutePath(wordToComplete, out _)); var relativePaths = context.GetOption("RelativePaths", @default: defaultRelative); var useLiteralPath = context.GetOption("LiteralPaths", @default: false); if (useLiteralPath && LocationGlobber.StringContainsGlobCharacters(wordToComplete)) { wordToComplete = WildcardPattern.Escape(wordToComplete, Utils.Separators.StarOrQuestion); } if (!defaultRelative && wordToComplete.Length >= 2 && wordToComplete[1] == ':' && char.IsLetter(wordToComplete[0]) && executionContext != null) { // We don't actually need the drive, but the drive must be "mounted" in PowerShell before completion // can succeed. This call will mount the drive if it wasn't already. executionContext.SessionState.Drive.GetAtScope(wordToComplete.Substring(0, 1), "global"); } var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Resolve-Path") .AddParameter("Path", wordToComplete + "*"); Exception exceptionThrown; var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psobjs != null) { var isFileSystem = false; var wordContainsProviderId = ProviderSpecified(wordToComplete); if (psobjs.Count > 0) { dynamic firstObj = psobjs[0]; var provider = firstObj.Provider as ProviderInfo; isFileSystem = provider != null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); } else { try { ProviderInfo provider; if (defaultRelative) { provider = executionContext.EngineSessionState.CurrentDrive.Provider; } else { executionContext.LocationGlobber.GetProviderPath(wordToComplete, out provider); } isFileSystem = provider != null && provider.Name.Equals(FileSystemProvider.ProviderName, StringComparison.OrdinalIgnoreCase); } catch (Exception) { } } if (isFileSystem) { bool hiddenFilesAreHandled = false; if (psobjs.Count > 0 && !LocationGlobber.StringContainsGlobCharacters(wordToComplete)) { string leaf = null; string pathWithoutProvider = wordContainsProviderId ? wordToComplete.Substring(wordToComplete.IndexOf(':') + 2) : wordToComplete; try { leaf = Path.GetFileName(pathWithoutProvider); } catch (Exception) { } var notHiddenEntries = new HashSet<string>(StringComparer.OrdinalIgnoreCase); string providerPath = null; foreach (dynamic entry in psobjs) { providerPath = entry.ProviderPath; if (string.IsNullOrEmpty(providerPath)) { // This is unexpected. ProviderPath should never be null or an empty string leaf = null; break; } if (!notHiddenEntries.Contains(providerPath)) { notHiddenEntries.Add(providerPath); } } if (leaf != null) { leaf += "*"; var parentPath = Path.GetDirectoryName(providerPath); // ProviderPath should be absolute path for FileSystem entries if (!string.IsNullOrEmpty(parentPath)) { string[] entries = null; try { entries = Directory.GetFileSystemEntries(parentPath, leaf, _enumerationOptions); } catch (Exception) { } if (entries != null) { hiddenFilesAreHandled = true; if (entries.Length > notHiddenEntries.Count) { // Do the iteration only if there are hidden files foreach (var entry in entries) { if (notHiddenEntries.Contains(entry)) continue; var fileInfo = new FileInfo(entry); try { if ((fileInfo.Attributes & FileAttributes.Hidden) != 0) { PSObject wrapper = PSObject.AsPSObject(entry); psobjs.Add(wrapper); } } catch { // do nothing if can't get file attributes } } } } } } } if (!hiddenFilesAreHandled) { powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-ChildItem") .AddParameter("Path", wordToComplete + "*") .AddParameter("Hidden", true); var hiddenItems = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (hiddenItems != null && hiddenItems.Count > 0) { foreach (var hiddenItem in hiddenItems) { psobjs.Add(hiddenItem); } } } } // Sorting the results by the path var sortedPsobjs = psobjs.OrderBy(static a => a, new ItemPathComparer()); foreach (PSObject psobj in sortedPsobjs) { object baseObj = PSObject.Base(psobj); string path = null, providerPath = null; // Get the path, the PSObject could be: // 1. a PathInfo object -- results of Resolve-Path // 2. a FileSystemInfo Object -- results of Get-ChildItem // 3. a string -- the path results return by the direct .NET API invocation var baseObjAsPathInfo = baseObj as PathInfo; if (baseObjAsPathInfo != null) { path = baseObjAsPathInfo.Path; providerPath = baseObjAsPathInfo.ProviderPath; } else if (baseObj is FileSystemInfo) { // The target provider is the FileSystem dynamic dirResult = psobj; providerPath = dirResult.FullName; path = wordContainsProviderId ? dirResult.PSPath : providerPath; } else { var baseObjAsString = baseObj as string; if (baseObjAsString != null) { // The target provider is the FileSystem providerPath = baseObjAsString; path = wordContainsProviderId ? FileSystemProvider.ProviderName + "::" + baseObjAsString : providerPath; } } if (path == null) continue; if (isFileSystem && providerPath == null) continue; string completionText; if (relativePaths) { try { var sessionStateInternal = executionContext.EngineSessionState; completionText = sessionStateInternal.NormalizeRelativePath(path, sessionStateInternal.CurrentLocation.ProviderPath); string parentDirectory = ".." + StringLiterals.DefaultPathSeparator; if (!completionText.StartsWith(parentDirectory, StringComparison.Ordinal)) completionText = Path.Combine(".", completionText); } catch (Exception) { // The object at the specified path is not accessable, such as c:\hiberfil.sys (for hibernation) or c:\pagefile.sys (for paging) // We ignore those files continue; } } else { completionText = path; } if (ProviderSpecified(completionText) && !wordContainsProviderId) { // Remove the provider id from the path: cd \\scratch2\scratch\dongbw var index = completionText.IndexOf(':'); completionText = completionText.Substring(index + 2); } if (CompletionRequiresQuotes(completionText, !useLiteralPath)) { var quoteInUse = quote == string.Empty ? "'" : quote; if (quoteInUse == "'") { completionText = completionText.Replace("'", "''"); } else { // When double quote is in use, we have to escape the backtip and '$' even when using literal path // Get-Content -LiteralPath ".\a``g.txt" completionText = completionText.Replace("`", "``"); completionText = completionText.Replace("$", "`$"); } if (!useLiteralPath) { if (quoteInUse == "'") { completionText = completionText.Replace("[", "`["); completionText = completionText.Replace("]", "`]"); } else { completionText = completionText.Replace("[", "``["); completionText = completionText.Replace("]", "``]"); } } completionText = quoteInUse + completionText + quoteInUse; } else if (quote != string.Empty) { completionText = quote + completionText + quote; } if (isFileSystem) { // Use .NET APIs directly to reduce the time overhead var isContainer = Directory.Exists(providerPath); if (containerOnly && !isContainer) continue; if (!containerOnly && !isContainer && !CheckFileExtension(providerPath, extension)) continue; string tooltip = providerPath, listItemText = Path.GetFileName(providerPath); results.Add(new CompletionResult(completionText, listItemText, isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, tooltip)); } else { powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item") .AddParameter("LiteralPath", path); var items = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (items != null && items.Count == 1) { dynamic item = items[0]; var isContainer = LanguagePrimitives.ConvertTo<bool>(item.PSIsContainer); if (containerOnly && !isContainer) continue; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Convert-Path") .AddParameter("LiteralPath", item.PSPath); var tooltips = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); string tooltip = null, listItemText = item.PSChildName; if (tooltips != null && tooltips.Count == 1) { tooltip = PSObject.Base(tooltips[0]) as string; } if (string.IsNullOrEmpty(listItemText)) { // For provider items that don't have PSChildName values, such as variable::error listItemText = item.Name; } results.Add(new CompletionResult(completionText, listItemText, isContainer ? CompletionResultType.ProviderContainer : CompletionResultType.ProviderItem, tooltip ?? path)); } else { // We can get here when get-item fails, perhaps due an acl or whatever. results.Add(new CompletionResult(completionText)); } } } } } return results; } [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)] private struct SHARE_INFO_1 { public string netname; public int type; public string remark; } private const int MAX_PREFERRED_LENGTH = -1; private const int NERR_Success = 0; private const int ERROR_MORE_DATA = 234; private const int STYPE_DISKTREE = 0; private const int STYPE_MASK = 0x000000FF; private static readonly System.IO.EnumerationOptions _enumerationOptions = new System.IO.EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, AttributesToSkip = 0 // Default is to skip Hidden and System files, so we clear this to retain existing behavior }; [DllImport("Netapi32.dll", CharSet = CharSet.Unicode)] private static extern int NetShareEnum(string serverName, int level, out IntPtr bufptr, int prefMaxLen, out uint entriesRead, out uint totalEntries, ref uint resumeHandle); internal static List<string> GetFileShares(string machine, bool ignoreHidden) { #if UNIX return new List<string>(); #else IntPtr shBuf; uint numEntries; uint totalEntries; uint resumeHandle = 0; int result = NetShareEnum(machine, 1, out shBuf, MAX_PREFERRED_LENGTH, out numEntries, out totalEntries, ref resumeHandle); var shares = new List<string>(); if (result == NERR_Success || result == ERROR_MORE_DATA) { for (int i = 0; i < numEntries; ++i) { IntPtr curInfoPtr = (IntPtr)((long)shBuf + (Marshal.SizeOf<SHARE_INFO_1>() * i)); SHARE_INFO_1 shareInfo = Marshal.PtrToStructure<SHARE_INFO_1>(curInfoPtr); if ((shareInfo.type & STYPE_MASK) != STYPE_DISKTREE) continue; if (ignoreHidden && shareInfo.netname.EndsWith('$')) continue; shares.Add(shareInfo.netname); } } return shares; #endif } private static bool CheckFileExtension(string path, HashSet<string> extension) { if (extension == null || extension.Count == 0) return true; var ext = System.IO.Path.GetExtension(path); return ext == null || extension.Contains(ext); } #endregion Filenames #region Variable /// <summary> /// </summary> /// <param name="variableName"></param> /// <returns></returns> public static IEnumerable<CompletionResult> CompleteVariable(string variableName) { var runspace = Runspace.DefaultRunspace; if (runspace == null) { // No runspace, just return no results. return CommandCompletion.EmptyCompletionResult; } var helper = new PowerShellExecutionHelper(PowerShell.Create(RunspaceMode.CurrentRunspace)); var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext; return CompleteVariable(new CompletionContext { WordToComplete = variableName, Helper = helper, ExecutionContext = executionContext }); } private static readonly string[] s_variableScopes = new string[] { "Global:", "Local:", "Script:", "Private:" }; private static readonly char[] s_charactersRequiringQuotes = new char[] { '-', '`', '&', '@', '\'', '"', '#', '{', '}', '(', ')', '$', ',', ';', '|', '<', '>', ' ', '.', '\\', '/', '\t', '^', }; internal static List<CompletionResult> CompleteVariable(CompletionContext context) { HashSet<string> hashedResults = new HashSet<string>(StringComparer.OrdinalIgnoreCase); List<CompletionResult> results = new List<CompletionResult>(); var wordToComplete = context.WordToComplete; var colon = wordToComplete.IndexOf(':'); var lastAst = context.RelatedAsts?.Last(); var variableAst = lastAst as VariableExpressionAst; var prefix = variableAst != null && variableAst.Splatted ? "@" : "$"; // Look for variables in the input (e.g. parameters, etc.) before checking session state - these // variables might not exist in session state yet. var wildcardPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); if (lastAst != null) { Ast parent = lastAst.Parent; var findVariablesVisitor = new FindVariablesVisitor { CompletionVariableAst = lastAst }; while (parent != null) { if (parent is IParameterMetadataProvider) { findVariablesVisitor.Top = parent; parent.Visit(findVariablesVisitor); } parent = parent.Parent; } foreach (Tuple<string, Ast> varAst in findVariablesVisitor.VariableSources) { Ast astTarget = null; string userPath = null; VariableExpressionAst variableDefinitionAst = varAst.Item2 as VariableExpressionAst; if (variableDefinitionAst != null) { userPath = varAst.Item1; astTarget = varAst.Item2.Parent; } else { CommandAst commandParameterAst = varAst.Item2 as CommandAst; if (commandParameterAst != null) { userPath = varAst.Item1; astTarget = varAst.Item2; } } if (string.IsNullOrEmpty(userPath)) { Diagnostics.Assert(false, "Found a variable source but it was an unknown AST type."); } if (wildcardPattern.IsMatch(userPath)) { var completedName = (userPath.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + userPath : prefix + "{" + userPath + "}"; var tooltip = userPath; var ast = astTarget; while (ast != null) { var parameterAst = ast as ParameterAst; if (parameterAst != null) { var typeConstraint = parameterAst.Attributes.OfType<TypeConstraintAst>().FirstOrDefault(); if (typeConstraint != null) { tooltip = StringUtil.Format("{0}${1}", typeConstraint.Extent.Text, userPath); } break; } var assignmentAst = ast.Parent as AssignmentStatementAst; if (assignmentAst != null) { if (assignmentAst.Left == ast) { tooltip = ast.Extent.Text; } break; } var commandAst = ast as CommandAst; if (commandAst != null) { PSTypeName discoveredType = AstTypeInference.InferTypeOf(ast, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).FirstOrDefault<PSTypeName>(); if (discoveredType != null) { tooltip = StringUtil.Format("[{0}]${1}", discoveredType.Name, userPath); } break; } ast = ast.Parent; } AddUniqueVariable(hashedResults, results, completedName, userPath, tooltip); } } } string pattern; string provider; if (colon == -1) { pattern = "variable:" + wordToComplete + "*"; provider = string.Empty; } else { provider = wordToComplete.Substring(0, colon + 1); if (s_variableScopes.Contains(provider, StringComparer.OrdinalIgnoreCase)) { pattern = string.Concat("variable:", wordToComplete.AsSpan(colon + 1), "*"); } else { pattern = wordToComplete + "*"; } } var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", pattern) .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); Exception exceptionThrown; var psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psobjs != null) { foreach (dynamic psobj in psobjs) { var name = psobj.Name as string; if (!string.IsNullOrEmpty(name)) { var tooltip = name; var variable = PSObject.Base(psobj) as PSVariable; if (variable != null) { var value = variable.Value; if (value != null) { tooltip = StringUtil.Format("[{0}]${1}", ToStringCodeMethods.Type(value.GetType(), dropNamespaces: true), name); } } var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + provider + name : prefix + "{" + provider + name + "}"; AddUniqueVariable(hashedResults, results, completedName, name, tooltip); } } } if (colon == -1 && "env".StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) { powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-Item").AddParameter("Path", "env:*") .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Key"); psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psobjs != null) { foreach (dynamic psobj in psobjs) { var name = psobj.Name as string; if (!string.IsNullOrEmpty(name)) { name = "env:" + name; var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + name : prefix + "{" + name + "}"; AddUniqueVariable(hashedResults, results, completedName, name, "[string]" + name); } } } } // Return variables already in session state first, because we can sometimes give better information, // like the variables type. foreach (var specialVariable in s_specialVariablesCache.Value) { if (wildcardPattern.IsMatch(specialVariable)) { var completedName = (specialVariable.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + specialVariable : prefix + "{" + specialVariable + "}"; AddUniqueVariable(hashedResults, results, completedName, specialVariable, specialVariable); } } if (colon == -1) { // If no drive was specified, then look for matching drives/scopes pattern = wordToComplete + "*"; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Management\\Get-PSDrive").AddParameter("Name", pattern) .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object").AddParameter("Property", "Name"); psobjs = powerShellExecutionHelper.ExecuteCurrentPowerShell(out exceptionThrown); if (psobjs != null) { foreach (var psobj in psobjs) { var driveInfo = PSObject.Base(psobj) as PSDriveInfo; if (driveInfo != null) { var name = driveInfo.Name; if (name != null && !string.IsNullOrWhiteSpace(name) && name.Length > 1) { var completedName = (name.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + name + ":" : prefix + "{" + name + ":}"; var tooltip = string.IsNullOrEmpty(driveInfo.Description) ? name : driveInfo.Description; AddUniqueVariable(hashedResults, results, completedName, name, tooltip); } } } } var scopePattern = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); foreach (var scope in s_variableScopes) { if (scopePattern.IsMatch(scope)) { var completedName = (scope.IndexOfAny(s_charactersRequiringQuotes) == -1) ? prefix + scope : prefix + "{" + scope + "}"; AddUniqueVariable(hashedResults, results, completedName, scope, scope); } } } return results; } private static void AddUniqueVariable(HashSet<string> hashedResults, List<CompletionResult> results, string completionText, string listItemText, string tooltip) { if (!hashedResults.Contains(completionText)) { hashedResults.Add(completionText); results.Add(new CompletionResult(completionText, listItemText, CompletionResultType.Variable, tooltip)); } } private sealed class FindVariablesVisitor : AstVisitor { internal Ast Top; internal Ast CompletionVariableAst; internal readonly List<Tuple<string, Ast>> VariableSources = new List<Tuple<string, Ast>>(); public override AstVisitAction VisitVariableExpression(VariableExpressionAst variableExpressionAst) { if (variableExpressionAst != CompletionVariableAst) { VariableSources.Add(new Tuple<string, Ast>(variableExpressionAst.VariablePath.UserPath, variableExpressionAst)); } return AstVisitAction.Continue; } public override AstVisitAction VisitCommand(CommandAst commandAst) { // MSFT: 784739 Stack overflow during tab completion of pipeline variable // $null | % -pv p { $p<TAB> -> In this case $p is pipelinevariable // and is used in the same command. PipelineVariables are not available // in the command they are assigned in. Hence the following code ignores // if the variable being completed is in the command extent. if ((commandAst != CompletionVariableAst) && (!CompletionVariableAst.Extent.IsWithin(commandAst.Extent))) { string[] desiredParameters = new string[] { "PV", "PipelineVariable", "OV", "OutVariable" }; StaticBindingResult bindingResult = StaticParameterBinder.BindCommand(commandAst, false, desiredParameters); if (bindingResult != null) { ParameterBindingResult parameterBindingResult; foreach (string commandVariableParameter in desiredParameters) { if (bindingResult.BoundParameters.TryGetValue(commandVariableParameter, out parameterBindingResult)) { VariableSources.Add(new Tuple<string, Ast>((string)parameterBindingResult.ConstantValue, commandAst)); } } } } return AstVisitAction.Continue; } public override AstVisitAction VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return functionDefinitionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; } public override AstVisitAction VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return scriptBlockExpressionAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; } public override AstVisitAction VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return scriptBlockAst != Top ? AstVisitAction.SkipChildren : AstVisitAction.Continue; } } private static readonly Lazy<SortedSet<string>> s_specialVariablesCache = new Lazy<SortedSet<string>>(BuildSpecialVariablesCache); private static SortedSet<string> BuildSpecialVariablesCache() { var result = new SortedSet<string>(); foreach (var member in typeof(SpecialVariables).GetFields(BindingFlags.NonPublic | BindingFlags.Static)) { if (member.FieldType.Equals(typeof(string))) { result.Add((string)member.GetValue(null)); } } return result; } #endregion Variables #region Comments internal static List<CompletionResult> CompleteComment(CompletionContext context, ref int replacementIndex, ref int replacementLength) { if (context.WordToComplete.StartsWith("<#", StringComparison.Ordinal)) { return CompleteCommentHelp(context, ref replacementIndex, ref replacementLength); } // Complete #requires statements if (context.WordToComplete.StartsWith("#requires ", StringComparison.OrdinalIgnoreCase)) { return CompleteRequires(context, ref replacementIndex, ref replacementLength); } var results = new List<CompletionResult>(); // Complete the history entries Match matchResult = Regex.Match(context.WordToComplete, @"^#([\w\-]*)$"); if (!matchResult.Success) { return results; } string wordToComplete = matchResult.Groups[1].Value; Collection<PSObject> psobjs; int entryId; if (Regex.IsMatch(wordToComplete, @"^[0-9]+$") && LanguagePrimitives.TryConvertTo(wordToComplete, out entryId)) { context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)).AddParameter("Id", entryId); psobjs = context.Helper.ExecuteCurrentPowerShell(out _); if (psobjs != null && psobjs.Count == 1) { var historyInfo = PSObject.Base(psobjs[0]) as HistoryInfo; if (historyInfo != null) { var commandLine = historyInfo.CommandLine; if (!string.IsNullOrEmpty(commandLine)) { // var tooltip = "Id: " + historyInfo.Id + "\n" + // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); } } } return results; } wordToComplete = "*" + wordToComplete + "*"; context.Helper.AddCommandWithPreferenceSetting("Get-History", typeof(GetHistoryCommand)); psobjs = context.Helper.ExecuteCurrentPowerShell(out _); var pattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); if (psobjs != null) { for (int index = psobjs.Count - 1; index >= 0; index--) { var psobj = psobjs[index]; if (!(PSObject.Base(psobj) is HistoryInfo historyInfo)) continue; var commandLine = historyInfo.CommandLine; if (!string.IsNullOrEmpty(commandLine) && pattern.IsMatch(commandLine)) { // var tooltip = "Id: " + historyInfo.Id + "\n" + // "ExecutionStatus: " + historyInfo.ExecutionStatus + "\n" + // "StartExecutionTime: " + historyInfo.StartExecutionTime + "\n" + // "EndExecutionTime: " + historyInfo.EndExecutionTime + "\n"; // Use the commandLine as the Tooltip in case the commandLine is multiple lines of scripts results.Add(new CompletionResult(commandLine, commandLine, CompletionResultType.History, commandLine)); } } } return results; } private static List<CompletionResult> CompleteRequires(CompletionContext context, ref int replacementIndex, ref int replacementLength) { var results = new List<CompletionResult>(); int cursorIndex = context.CursorPosition.ColumnNumber - 1; string lineToCursor = context.CursorPosition.Line.Substring(0, cursorIndex); // RunAsAdministrator must be the last parameter in a Requires statement so no completion if the cursor is after the parameter. if (lineToCursor.Contains(" -RunAsAdministrator", StringComparison.OrdinalIgnoreCase)) { return results; } // Regex to find parameter like " -Parameter1" or " -" MatchCollection hashtableKeyMatches = Regex.Matches(lineToCursor, @"\s+-([A-Za-z]+|$)"); if (hashtableKeyMatches.Count == 0) { return results; } Group currentParameterMatch = hashtableKeyMatches[^1].Groups[1]; // Complete the parameter if the cursor is at a parameter if (currentParameterMatch.Index + currentParameterMatch.Length == cursorIndex) { string currentParameterPrefix = currentParameterMatch.Value; replacementIndex = context.CursorPosition.Offset - currentParameterPrefix.Length; replacementLength = currentParameterPrefix.Length; // Produce completions for all parameters that begin with the prefix we've found, // but which haven't already been specified in the line we need to complete foreach (KeyValuePair<string, string> parameter in s_requiresParameters) { if (parameter.Key.StartsWith(currentParameterPrefix, StringComparison.OrdinalIgnoreCase) && !context.CursorPosition.Line.Contains($" -{parameter.Key}", StringComparison.OrdinalIgnoreCase)) { results.Add(new CompletionResult(parameter.Key, parameter.Key, CompletionResultType.ParameterName, parameter.Value)); } } return results; } // Regex to find parameter values (any text that appears after various delimiters) hashtableKeyMatches = Regex.Matches(lineToCursor, @"(\s+|,|;|{|\""|'|=)(\w+|$)"); string currentValue; if (hashtableKeyMatches.Count == 0) { currentValue = string.Empty; } else { currentValue = hashtableKeyMatches[^1].Groups[2].Value; } replacementIndex = context.CursorPosition.Offset - currentValue.Length; replacementLength = currentValue.Length; // Complete PSEdition parameter values if (currentParameterMatch.Value.Equals("PSEdition", StringComparison.OrdinalIgnoreCase)) { foreach (KeyValuePair<string, string> psEditionEntry in s_requiresPSEditions) { if (psEditionEntry.Key.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase)) { results.Add(new CompletionResult(psEditionEntry.Key, psEditionEntry.Key, CompletionResultType.ParameterValue, psEditionEntry.Value)); } } return results; } // Complete Modules module specification values if (currentParameterMatch.Value.Equals("Modules", StringComparison.OrdinalIgnoreCase)) { int hashtableStart = lineToCursor.LastIndexOf("@{"); int hashtableEnd = lineToCursor.LastIndexOf('}'); bool insideHashtable = hashtableStart != -1 && (hashtableEnd == -1 || hashtableEnd < hashtableStart); // If not inside a hashtable, try to complete a module simple name if (!insideHashtable) { context.WordToComplete = currentValue; return CompleteModuleName(context, true); } string hashtableString = lineToCursor.Substring(hashtableStart); // Regex to find hashtable keys with or without quotes hashtableKeyMatches = Regex.Matches(hashtableString, @"(@{|;)\s*(?:'|\""|\w*)\w*"); // Build the list of keys we might want to complete, based on what's already been provided var moduleSpecKeysToComplete = new HashSet<string>(s_requiresModuleSpecKeys.Keys); bool sawModuleNameLast = false; foreach (Match existingHashtableKeyMatch in hashtableKeyMatches) { string existingHashtableKey = existingHashtableKeyMatch.Value.TrimStart(s_hashtableKeyPrefixes); if (string.IsNullOrEmpty(existingHashtableKey)) { continue; } // Remove the existing key we just saw moduleSpecKeysToComplete.Remove(existingHashtableKey); // We need to remember later if we saw "ModuleName" as the last hashtable key, for completions if (sawModuleNameLast = existingHashtableKey.Equals("ModuleName", StringComparison.OrdinalIgnoreCase)) { continue; } // "RequiredVersion" is mutually exclusive with "ModuleVersion" and "MaximumVersion" if (existingHashtableKey.Equals("ModuleVersion", StringComparison.OrdinalIgnoreCase) || existingHashtableKey.Equals("MaximumVersion", StringComparison.OrdinalIgnoreCase)) { moduleSpecKeysToComplete.Remove("RequiredVersion"); continue; } if (existingHashtableKey.Equals("RequiredVersion", StringComparison.OrdinalIgnoreCase)) { moduleSpecKeysToComplete.Remove("ModuleVersion"); moduleSpecKeysToComplete.Remove("MaximumVersion"); continue; } } Group lastHashtableKeyPrefixGroup = hashtableKeyMatches[^1].Groups[0]; // If we're not completing a key for the hashtable, try to complete module names, but nothing else bool completingHashtableKey = lastHashtableKeyPrefixGroup.Index + lastHashtableKeyPrefixGroup.Length == hashtableString.Length; if (!completingHashtableKey) { if (sawModuleNameLast) { context.WordToComplete = currentValue; return CompleteModuleName(context, true); } return results; } // Now try to complete hashtable keys foreach (string moduleSpecKey in moduleSpecKeysToComplete) { if (moduleSpecKey.StartsWith(currentValue, StringComparison.OrdinalIgnoreCase)) { results.Add(new CompletionResult(moduleSpecKey, moduleSpecKey, CompletionResultType.ParameterValue, s_requiresModuleSpecKeys[moduleSpecKey])); } } } return results; } private static readonly IReadOnlyDictionary<string, string> s_requiresParameters = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase) { { "Modules", "Specifies PowerShell modules that the script requires." }, { "PSEdition", "Specifies a PowerShell edition that the script requires." }, { "RunAsAdministrator", "Specifies that PowerShell must be running as administrator on Windows." }, { "Version", "Specifies the minimum version of PowerShell that the script requires." }, }; private static readonly IReadOnlyDictionary<string, string> s_requiresPSEditions = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase) { { "Core", "Specifies that the script requires PowerShell Core to run." }, { "Desktop", "Specifies that the script requires Windows PowerShell to run." }, }; private static readonly IReadOnlyDictionary<string, string> s_requiresModuleSpecKeys = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase) { { "ModuleName", "Required. Specifies the module name." }, { "GUID", "Optional. Specifies the GUID of the module." }, { "ModuleVersion", "Specifies a minimum acceptable version of the module." }, { "RequiredVersion", "Specifies an exact, required version of the module." }, { "MaximumVersion", "Specifies the maximum acceptable version of the module." }, }; private static readonly char[] s_hashtableKeyPrefixes = new[] { '@', '{', ';', '"', '\'', ' ', }; private static List<CompletionResult> CompleteCommentHelp(CompletionContext context, ref int replacementIndex, ref int replacementLength) { // Finds comment keywords like ".DESCRIPTION" MatchCollection usedKeywords = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.)\w*", RegexOptions.Multiline); if (usedKeywords.Count == 0) { return null; } // Last keyword at or before the cursor Match lineKeyword = null; for (int i = usedKeywords.Count - 1; i >= 0; i--) { Match keyword = usedKeywords[i]; if (context.CursorPosition.Offset >= keyword.Index + context.TokenAtCursor.Extent.StartOffset) { lineKeyword = keyword; break; } } if (lineKeyword is null) { return null; } // Cursor is within or at the start/end of the keyword if (context.CursorPosition.Offset <= lineKeyword.Index + lineKeyword.Length + context.TokenAtCursor.Extent.StartOffset) { replacementIndex = context.TokenAtCursor.Extent.StartOffset + lineKeyword.Index; replacementLength = lineKeyword.Value.Length; var validKeywords = new HashSet<String>(s_commentHelpKeywords.Keys, StringComparer.OrdinalIgnoreCase); foreach (Match keyword in usedKeywords) { if (keyword == lineKeyword || s_commentHelpAllowedDuplicateKeywords.Contains(keyword.Value)) { continue; } validKeywords.Remove(keyword.Value); } var result = new List<CompletionResult>(); foreach (string keyword in validKeywords) { if (keyword.StartsWith(lineKeyword.Value, StringComparison.OrdinalIgnoreCase)) { result.Add(new CompletionResult(keyword, keyword, CompletionResultType.Keyword, s_commentHelpKeywords[keyword])); } } return result.Count > 0 ? result : null; } // Finds the argument for the keyword (any characters following the keyword, ignoring leading/trailing whitespace). For example "C:\New folder" Match keywordArgument = Regex.Match(context.CursorPosition.Line, @"(?<=^\s*\.\w+\s+)\S.*(?<=\S)"); int lineStartIndex = lineKeyword.Index - context.CursorPosition.Line.IndexOf(lineKeyword.Value) + context.TokenAtCursor.Extent.StartOffset; int argumentIndex = keywordArgument.Success ? keywordArgument.Index : context.CursorPosition.ColumnNumber - 1; replacementIndex = lineStartIndex + argumentIndex; replacementLength = keywordArgument.Value.Length; if (lineKeyword.Value.Equals("PARAMETER", StringComparison.OrdinalIgnoreCase)) { return CompleteCommentParameterValue(context, keywordArgument.Value); } if (lineKeyword.Value.Equals("FORWARDHELPTARGETNAME", StringComparison.OrdinalIgnoreCase)) { var result = new List<CompletionResult>(CompleteCommand(keywordArgument.Value, "*", CommandTypes.All)); return result.Count > 0 ? result : null; } if (lineKeyword.Value.Equals("FORWARDHELPCATEGORY", StringComparison.OrdinalIgnoreCase)) { var result = new List<CompletionResult>(); foreach (string category in s_commentHelpForwardCategories) { if (category.StartsWith(keywordArgument.Value, StringComparison.OrdinalIgnoreCase)) { result.Add(new CompletionResult(category)); } } return result.Count > 0 ? result : null; } if (lineKeyword.Value.Equals("REMOTEHELPRUNSPACE", StringComparison.OrdinalIgnoreCase)) { var result = new List<CompletionResult>(); foreach (CompletionResult variable in CompleteVariable(keywordArgument.Value)) { // ListItemText is used because it excludes the "$" as expected by REMOTEHELPRUNSPACE. result.Add(new CompletionResult(variable.ListItemText, variable.ListItemText, variable.ResultType, variable.ToolTip)); } return result.Count > 0 ? result : null; } if (lineKeyword.Value.Equals("EXTERNALHELP", StringComparison.OrdinalIgnoreCase)) { context.WordToComplete = keywordArgument.Value; var result = new List<CompletionResult>(CompleteFilename(context, containerOnly: false, (new HashSet<string>() { ".xml" }))); return result.Count > 0 ? result : null; } return null; } private static readonly IReadOnlyDictionary<string, string> s_commentHelpKeywords = new SortedList<string, string>(StringComparer.OrdinalIgnoreCase) { { "SYNOPSIS", "A brief description of the function or script. This keyword can be used only once in each topic." }, { "DESCRIPTION", "A detailed description of the function or script. This keyword can be used only once in each topic." }, { "PARAMETER", ".PARAMETER <Parameter-Name>\nThe description of a parameter. Add a .PARAMETER keyword for each parameter in the function or script syntax." }, { "EXAMPLE", "A sample command that uses the function or script, optionally followed by sample output and a description. Repeat this keyword for each example." }, { "INPUTS", "The .NET types of objects that can be piped to the function or script. You can also include a description of the input objects." }, { "OUTPUTS", "The .NET type of the objects that the cmdlet returns. You can also include a description of the returned objects." }, { "NOTES", "Additional information about the function or script." }, { "LINK", "The name of a related topic. Repeat the .LINK keyword for each related topic. The .Link keyword content can also include a URI to an online version of the same help topic." }, { "COMPONENT", "The name of the technology or feature that the function or script uses, or to which it is related." }, { "ROLE", "The name of the user role for the help topic." }, { "FUNCTIONALITY", "The keywords that describe the intended use of the function." }, { "FORWARDHELPTARGETNAME", ".FORWARDHELPTARGETNAME <Command-Name>\nRedirects to the help topic for the specified command." }, { "FORWARDHELPCATEGORY", ".FORWARDHELPCATEGORY <Category>\nSpecifies the help category of the item in .ForwardHelpTargetName" }, { "REMOTEHELPRUNSPACE", ".REMOTEHELPRUNSPACE <PSSession-variable>\nSpecifies a session that contains the help topic. Enter a variable that contains a PSSession object." }, { "EXTERNALHELP", ".EXTERNALHELP <XML Help File>\nThe .ExternalHelp keyword is required when a function or script is documented in XML files." } }; private static readonly HashSet<string> s_commentHelpAllowedDuplicateKeywords = new(StringComparer.OrdinalIgnoreCase) { "PARAMETER", "EXAMPLE", "LINK" }; private static readonly string[] s_commentHelpForwardCategories = new string[] { "Alias", "Cmdlet", "HelpFile", "Function", "Provider", "General", "FAQ", "Glossary", "ScriptCommand", "ExternalScript", "Filter", "All" }; private static FunctionDefinitionAst GetCommentHelpFunctionTarget(CompletionContext context) { if (context.TokenAtCursor.Kind != TokenKind.Comment) { return null; } Ast lastAst = context.RelatedAsts[^1]; Ast firstAstAfterComment = lastAst.Find(ast => ast.Extent.StartOffset >= context.TokenAtCursor.Extent.EndOffset, searchNestedScriptBlocks: false); // Comment-based help can apply to a following function definition if it starts within 2 lines int commentEndLine = context.TokenAtCursor.Extent.EndLineNumber + 2; if (lastAst is NamedBlockAst) { // Helpblock before function inside advanced function if (firstAstAfterComment is not null && firstAstAfterComment.Extent.StartLineNumber <= commentEndLine && firstAstAfterComment is FunctionDefinitionAst outerHelpFunctionDefAst) { return outerHelpFunctionDefAst; } // Helpblock inside function if (lastAst.Parent.Parent is FunctionDefinitionAst innerHelpFunctionDefAst) { return innerHelpFunctionDefAst; } } if (lastAst is ScriptBlockAst) { // Helpblock before function if (firstAstAfterComment is not null && firstAstAfterComment.Extent.StartLineNumber <= commentEndLine && firstAstAfterComment is NamedBlockAst block && block.Statements.Count > 0 && block.Statements[0] is FunctionDefinitionAst statement) { return statement; } // Advanced function with help inside if (lastAst.Parent is FunctionDefinitionAst advFuncDefAst) { return advFuncDefAst; } } return null; } private static List<CompletionResult> CompleteCommentParameterValue(CompletionContext context, string wordToComplete) { FunctionDefinitionAst foundFunction = GetCommentHelpFunctionTarget(context); ReadOnlyCollection<ParameterAst> foundParameters = null; if (foundFunction is not null) { foundParameters = foundFunction.Parameters ?? foundFunction.Body.ParamBlock?.Parameters; } else if (context.RelatedAsts[^1] is ScriptBlockAst scriptAst) { // The helpblock is for a script file foundParameters = scriptAst.ParamBlock?.Parameters; } if (foundParameters is null || foundParameters.Count == 0) { return null; } var parametersToShow = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (ParameterAst parameter in foundParameters) { if (parameter.Name.VariablePath.UserPath.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) { parametersToShow.Add(parameter.Name.VariablePath.UserPath); } } MatchCollection usedParameters = Regex.Matches(context.TokenAtCursor.Text, @"(?<=^\s*\.parameter\s+)\w.*(?<=\S)", RegexOptions.Multiline | RegexOptions.IgnoreCase); foreach (Match parameter in usedParameters) { if (wordToComplete.Equals(parameter.Value, StringComparison.OrdinalIgnoreCase)) { continue; } parametersToShow.Remove(parameter.Value); } var result = new List<CompletionResult>(); foreach (string parameter in parametersToShow) { result.Add(new CompletionResult(parameter)); } return result.Count > 0 ? result : null; } #endregion Comments #region Members // List of extension methods <MethodName, Signature> private static readonly List<Tuple<string, string>> s_extensionMethods = new List<Tuple<string, string>> { new Tuple<string, string>("Where", "Where({ expression } [, mode [, numberToReturn]])"), new Tuple<string, string>("ForEach", "ForEach(expression [, arguments...])") }; // List of DSC collection-value variables private static readonly HashSet<string> s_dscCollectionVariables = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "SelectedNodes", "AllNodes" }; internal static List<CompletionResult> CompleteMember(CompletionContext context, bool @static) { // If we get here, we know that either: // * the cursor appeared immediately after a member access token ('.' or '::'). // * the parent of the ast on the cursor was a member expression. // // In the first case, we have 2 possibilities: // * the last ast is an error ast because no member name was entered and we were in expression context // * the last ast is a string constant, with something like: echo $foo. var results = new List<CompletionResult>(); var lastAst = context.RelatedAsts.Last(); var lastAstAsMemberExpr = lastAst as MemberExpressionAst; Ast memberNameCandidateAst = null; ExpressionAst targetExpr = null; if (lastAstAsMemberExpr != null) { // If the cursor is not inside the member name in the member expression, assume // that the user had incomplete input, but the parser got lucky and succeeded parsing anyway. if (context.TokenAtCursor.Extent.StartOffset >= lastAstAsMemberExpr.Member.Extent.StartOffset) { memberNameCandidateAst = lastAstAsMemberExpr.Member; } targetExpr = lastAstAsMemberExpr.Expression; } else { memberNameCandidateAst = lastAst; } var memberNameAst = memberNameCandidateAst as StringConstantExpressionAst; var memberName = "*"; if (memberNameAst != null) { // Make sure to correctly handle: echo $foo. if (!memberNameAst.Value.Equals(".", StringComparison.OrdinalIgnoreCase) && !memberNameAst.Value.Equals("::", StringComparison.OrdinalIgnoreCase)) { memberName = memberNameAst.Value + "*"; } } else if (lastAst is not ErrorExpressionAst && targetExpr == null) { // I don't think we can complete anything interesting return results; } var commandAst = lastAst.Parent as CommandAst; if (commandAst != null) { int i; for (i = commandAst.CommandElements.Count - 1; i >= 0; --i) { if (commandAst.CommandElements[i] == lastAst) { break; } } var nextToLastAst = commandAst.CommandElements[i - 1]; var nextToLastExtent = nextToLastAst.Extent; var lastExtent = lastAst.Extent; if (nextToLastExtent.EndLineNumber == lastExtent.StartLineNumber && nextToLastExtent.EndColumnNumber == lastExtent.StartColumnNumber) { targetExpr = nextToLastAst as ExpressionAst; } } else if (lastAst.Parent is MemberExpressionAst) { // If 'targetExpr' has already been set, we should skip this step. This is for some member completion // cases in ISE. In ISE, we may add a new statement in the middle of existing statements as follows: // $xml = New-Object Xml // $xml. // $xml.Save("C:\data.xml") // In this example, we add $xml. between two existing statements, and the 'lastAst' in this case is // a MemberExpressionAst '$xml.$xml', whose parent is still a MemberExpressionAst '$xml.$xml.Save'. // But here we DO NOT want to re-assign 'targetExpr' to be '$xml.$xml'. 'targetExpr' in this case // should be '$xml'. if (targetExpr == null) { var memberExprAst = (MemberExpressionAst)lastAst.Parent; targetExpr = memberExprAst.Expression; } } else if (lastAst.Parent is BinaryExpressionAst && context.TokenAtCursor.Kind.Equals(TokenKind.Multiply)) { var memberExprAst = ((BinaryExpressionAst)lastAst.Parent).Left as MemberExpressionAst; if (memberExprAst != null) { targetExpr = memberExprAst.Expression; if (memberExprAst.Member is StringConstantExpressionAst) { memberName = ((StringConstantExpressionAst)memberExprAst.Member).Value + "*"; } } } if (targetExpr == null) { // Not sure what we have, but we're not looking for members. return results; } if (IsSplattedVariable(targetExpr)) { // It's splatted variable, member expansion is not useful return results; } CompleteMemberHelper(@static, memberName, targetExpr, context, results); if (results.Count == 0) { PSTypeName[] inferredTypes = null; if (@static) { var typeExpr = targetExpr as TypeExpressionAst; if (typeExpr != null) { inferredTypes = new[] { new PSTypeName(typeExpr.TypeName) }; } } else { inferredTypes = AstTypeInference.InferTypeOf(targetExpr, context.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval).ToArray(); } if (inferredTypes != null && inferredTypes.Length > 0) { // Use inferred types if we have any CompleteMemberByInferredType(context.TypeInferenceContext, inferredTypes, results, memberName, filter: null, isStatic: @static); } else { // Handle special DSC collection variables to complete the extension methods 'Where' and 'ForEach' // e.g. Configuration foo { node $AllNodes.<tab> --> $AllNodes.Where( var variableAst = targetExpr as VariableExpressionAst; var memberExprAst = targetExpr as MemberExpressionAst; bool shouldAddExtensionMethods = false; // We complete against extension methods 'Where' and 'ForEach' for the following DSC variables // $SelectedNodes, $AllNodes, $ConfigurationData.AllNodes if (variableAst != null) { // Handle $SelectedNodes and $AllNodes var variablePath = variableAst.VariablePath; if (variablePath.IsVariable && s_dscCollectionVariables.Contains(variablePath.UserPath) && IsInDscContext(variableAst)) { shouldAddExtensionMethods = true; } } else if (memberExprAst != null) { // Handle $ConfigurationData.AllNodes var member = memberExprAst.Member as StringConstantExpressionAst; if (IsConfigurationDataVariable(memberExprAst.Expression) && member != null && string.Equals("AllNodes", member.Value, StringComparison.OrdinalIgnoreCase) && IsInDscContext(memberExprAst)) { shouldAddExtensionMethods = true; } } if (shouldAddExtensionMethods) { CompleteExtensionMethods(memberName, results); } } if (results.Count == 0) { // Handle '$ConfigurationData' specially to complete 'AllNodes' for it if (IsConfigurationDataVariable(targetExpr) && IsInDscContext(targetExpr)) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); if (pattern.IsMatch("AllNodes")) { results.Add(new CompletionResult("AllNodes", "AllNodes", CompletionResultType.Property, "AllNodes")); } } } } return results; } /// <summary> /// Complete members against extension methods 'Where' and 'ForEach' /// </summary> private static void CompleteExtensionMethods(string memberName, List<CompletionResult> results) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); CompleteExtensionMethods(pattern, results); } /// <summary> /// Complete members against extension methods 'Where' and 'ForEach' based on the given pattern. /// </summary> private static void CompleteExtensionMethods(WildcardPattern pattern, List<CompletionResult> results) { results.AddRange(from member in s_extensionMethods where pattern.IsMatch(member.Item1) select new CompletionResult(member.Item1 + "(", member.Item1, CompletionResultType.Method, member.Item2)); } /// <summary> /// Verify if an expression Ast is representing the $ConfigurationData variable. /// </summary> private static bool IsConfigurationDataVariable(ExpressionAst targetExpr) { var variableExpr = targetExpr as VariableExpressionAst; if (variableExpr != null) { var varPath = variableExpr.VariablePath; if (varPath.IsVariable && varPath.UserPath.Equals("ConfigurationData", StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } /// <summary> /// Verify if an expression Ast is within a configuration definition. /// </summary> private static bool IsInDscContext(ExpressionAst expression) { return Ast.GetAncestorAst<ConfigurationDefinitionAst>(expression) != null; } private static void CompleteFormatViewByInferredType(CompletionContext context, string[] inferredTypeNames, List<CompletionResult> results, string commandName) { var typeInfoDB = context.TypeInferenceContext.ExecutionContext.FormatDBManager.GetTypeInfoDataBase(); if (typeInfoDB is null) { return; } Type controlBodyType = commandName switch { "Format-Table" => typeof(TableControlBody), "Format-List" => typeof(ListControlBody), "Format-Wide" => typeof(WideControlBody), "Format-Custom" => typeof(ComplexControlBody), _ => null }; Diagnostics.Assert(controlBodyType is not null, "This should never happen unless a new Format-* cmdlet is added"); var wordToComplete = context.WordToComplete; var quote = HandleDoubleAndSingleQuote(ref wordToComplete); WildcardPattern viewPattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var uniqueNames = new HashSet<string>(); foreach (ViewDefinition viewDefinition in typeInfoDB.viewDefinitionsSection.viewDefinitionList) { if (viewDefinition?.appliesTo is not null && controlBodyType == viewDefinition.mainControl.GetType()) { foreach (TypeOrGroupReference applyTo in viewDefinition.appliesTo.referenceList) { foreach (string inferredTypeName in inferredTypeNames) { // We use 'StartsWith()' because 'applyTo.Name' can look like "System.Diagnostics.Process#IncludeUserName". if (applyTo.name.StartsWith(inferredTypeName, StringComparison.OrdinalIgnoreCase) && uniqueNames.Add(viewDefinition.name) && viewPattern.IsMatch(viewDefinition.name)) { string completionText = viewDefinition.name; // If the string is quoted or if it contains characters that need quoting, quote it in single quotes if (quote != string.Empty || viewDefinition.name.IndexOfAny(s_charactersRequiringQuotes) != -1) { completionText = "'" + completionText.Replace("'", "''") + "'"; } results.Add(new CompletionResult(completionText, viewDefinition.name, CompletionResultType.Text, viewDefinition.name)); } } } } } } internal static void CompleteMemberByInferredType(TypeInferenceContext context, IEnumerable<PSTypeName> inferredTypes, List<CompletionResult> results, string memberName, Func<object, bool> filter, bool isStatic, HashSet<string> excludedMembers = null) { bool extensionMethodsAdded = false; HashSet<string> typeNameUsed = new HashSet<string>(StringComparer.OrdinalIgnoreCase); WildcardPattern memberNamePattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (var psTypeName in inferredTypes) { if (typeNameUsed.Contains(psTypeName.Name)) { continue; } typeNameUsed.Add(psTypeName.Name); var members = context.GetMembersByInferredType(psTypeName, isStatic, filter); foreach (var member in members) { AddInferredMember(member, memberNamePattern, results, excludedMembers); } // Check if we need to complete against the extension methods 'Where' and 'ForEach' if (!extensionMethodsAdded && psTypeName.Type != null && IsStaticTypeEnumerable(psTypeName.Type)) { // Complete extension methods 'Where' and 'ForEach' for Enumerable types extensionMethodsAdded = true; CompleteExtensionMethods(memberNamePattern, results); } } if (results.Count > 0) { // Sort the results var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", new[] { "ResultType", "ListItemText" }) .AddParameter("Unique"); Exception unused; var sortedResults = powerShellExecutionHelper.ExecuteCurrentPowerShell(out unused, results); results.Clear(); results.AddRange(sortedResults.Select(static psobj => PSObject.Base(psobj) as CompletionResult)); } } private static void AddInferredMember(object member, WildcardPattern memberNamePattern, List<CompletionResult> results, HashSet<string> excludedMembers) { string memberName = null; bool isMethod = false; Func<string> getToolTip = null; var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { memberName = propertyInfo.Name; getToolTip = () => ToStringCodeMethods.Type(propertyInfo.PropertyType) + " " + memberName + " { " + (propertyInfo.GetGetMethod() != null ? "get; " : string.Empty) + (propertyInfo.GetSetMethod() != null ? "set; " : string.Empty) + "}"; } var fieldInfo = member as FieldInfo; if (fieldInfo != null) { memberName = fieldInfo.Name; getToolTip = () => ToStringCodeMethods.Type(fieldInfo.FieldType) + " " + memberName; } var methodCacheEntry = member as DotNetAdapter.MethodCacheEntry; if (methodCacheEntry != null) { memberName = methodCacheEntry[0].method.Name; isMethod = true; getToolTip = () => string.Join("\n", methodCacheEntry.methodInformationStructures.Select(static m => m.methodDefinition)); } var psMemberInfo = member as PSMemberInfo; if (psMemberInfo != null) { memberName = psMemberInfo.Name; isMethod = member is PSMethodInfo; getToolTip = psMemberInfo.ToString; } var cimProperty = member as CimPropertyDeclaration; if (cimProperty != null) { memberName = cimProperty.Name; isMethod = false; getToolTip = () => GetCimPropertyToString(cimProperty); } var memberAst = member as MemberAst; if (memberAst != null) { memberName = memberAst is CompilerGeneratedMemberFunctionAst ? "new" : memberAst.Name; isMethod = memberAst is FunctionMemberAst || memberAst is CompilerGeneratedMemberFunctionAst; getToolTip = memberAst.GetTooltip; } if (memberName == null || !memberNamePattern.IsMatch(memberName) || (excludedMembers is not null && excludedMembers.Contains(memberName))) { return; } var completionResultType = isMethod ? CompletionResultType.Method : CompletionResultType.Property; var completionText = isMethod ? memberName + "(" : memberName; results.Add(new CompletionResult(completionText, memberName, completionResultType, getToolTip())); } private static string GetCimPropertyToString(CimPropertyDeclaration cimProperty) { string type; switch (cimProperty.CimType) { case Microsoft.Management.Infrastructure.CimType.DateTime: case Microsoft.Management.Infrastructure.CimType.Instance: case Microsoft.Management.Infrastructure.CimType.Reference: case Microsoft.Management.Infrastructure.CimType.DateTimeArray: case Microsoft.Management.Infrastructure.CimType.InstanceArray: case Microsoft.Management.Infrastructure.CimType.ReferenceArray: type = "CimInstance#" + cimProperty.CimType.ToString(); break; default: type = ToStringCodeMethods.Type(CimConverter.GetDotNetType(cimProperty.CimType)); break; } bool isReadOnly = ((cimProperty.Flags & CimFlags.ReadOnly) == CimFlags.ReadOnly); return type + " " + cimProperty.Name + " { get; " + (isReadOnly ? "}" : "set; }"); } private static bool IsWriteablePropertyMember(object member) { var propertyInfo = member as PropertyInfo; if (propertyInfo != null) { return propertyInfo.CanWrite; } var psPropertyInfo = member as PSPropertyInfo; if (psPropertyInfo != null) { return psPropertyInfo.IsSettable; } return false; } internal static bool IsPropertyMember(object member) { return member is PropertyInfo || member is FieldInfo || member is PSPropertyInfo || member is CimPropertyDeclaration || member is PropertyMemberAst; } private static bool IsMemberHidden(object member) { var psMemberInfo = member as PSMemberInfo; if (psMemberInfo != null) return psMemberInfo.IsHidden; var memberInfo = member as MemberInfo; if (memberInfo != null) return memberInfo.GetCustomAttributes(typeof(HiddenAttribute), false).Length > 0; var propertyMemberAst = member as PropertyMemberAst; if (propertyMemberAst != null) return propertyMemberAst.IsHidden; var functionMemberAst = member as FunctionMemberAst; if (functionMemberAst != null) return functionMemberAst.IsHidden; return false; } private static bool IsConstructor(object member) { var psMethod = member as PSMethod; if (psMethod != null) { var methodCacheEntry = psMethod.adapterData as DotNetAdapter.MethodCacheEntry; if (methodCacheEntry != null) { return methodCacheEntry.methodInformationStructures[0].method.IsConstructor; } } return false; } #endregion Members #region Types private abstract class TypeCompletionBase { internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix); internal abstract CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove); internal static string RemoveBackTick(string typeName) { var backtick = typeName.LastIndexOf('`'); return backtick == -1 ? typeName : typeName.Substring(0, backtick); } } /// <summary> /// In OneCore PS, there is no way to retrieve all loaded assemblies. But we have the type catalog dictionary /// which contains the full type names of all available CoreCLR .NET types. We can extract the necessary info /// from the full type names to make type name auto-completion work. /// This type represents a non-generic type for type name completion. It only contains information that can be /// inferred from the full type name. /// </summary> private class TypeCompletionInStringFormat : TypeCompletionBase { /// <summary> /// Get the full type name of the type represented by this instance. /// </summary> internal string FullTypeName; /// <summary> /// Get the short type name of the type represented by this instance. /// </summary> internal string ShortTypeName { get { if (_shortTypeName == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); int lastPlusIndex = FullTypeName.LastIndexOf('+'); _shortTypeName = lastPlusIndex != -1 ? FullTypeName.Substring(lastPlusIndex + 1) : FullTypeName.Substring(lastDotIndex + 1); } return _shortTypeName; } } private string _shortTypeName; /// <summary> /// Get the namespace of the type represented by this instance. /// </summary> internal string Namespace { get { if (_namespace == null) { int lastDotIndex = FullTypeName.LastIndexOf('.'); _namespace = FullTypeName.Substring(0, lastDotIndex); } return _namespace; } } private string _namespace; /// <summary> /// Construct the CompletionResult based on the information of this instance. /// </summary> internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { return GetCompletionResult(keyMatched, prefix, suffix, null); } /// <summary> /// Construct the CompletionResult based on the information of this instance. /// </summary> internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove) { string completion = string.IsNullOrEmpty(namespaceToRemove) ? FullTypeName : FullTypeName.Substring(namespaceToRemove.Length + 1); string listItem = ShortTypeName; string tooltip = FullTypeName; return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip); } } /// <summary> /// In OneCore PS, there is no way to retrieve all loaded assemblies. But we have the type catalog dictionary /// which contains the full type names of all available CoreCLR .NET types. We can extract the necessary info /// from the full type names to make type name auto-completion work. /// This type represents a generic type for type name completion. It only contains information that can be /// inferred from the full type name. /// </summary> private sealed class GenericTypeCompletionInStringFormat : TypeCompletionInStringFormat { /// <summary> /// Get the number of generic type arguments required by the type represented by this instance. /// </summary> private int GenericArgumentCount { get { if (_genericArgumentCount == 0) { var backtick = FullTypeName.LastIndexOf('`'); var argCount = FullTypeName.Substring(backtick + 1); _genericArgumentCount = LanguagePrimitives.ConvertTo<int>(argCount); } return _genericArgumentCount; } } private int _genericArgumentCount = 0; /// <summary> /// Construct the CompletionResult based on the information of this instance. /// </summary> internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { return GetCompletionResult(keyMatched, prefix, suffix, null); } /// <summary> /// Construct the CompletionResult based on the information of this instance. /// </summary> internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove) { string fullNameWithoutBacktip = RemoveBackTick(FullTypeName); string completion = string.IsNullOrEmpty(namespaceToRemove) ? fullNameWithoutBacktip : fullNameWithoutBacktip.Substring(namespaceToRemove.Length + 1); string typeName = RemoveBackTick(ShortTypeName); var listItem = typeName + "<>"; var tooltip = new StringBuilder(); tooltip.Append(fullNameWithoutBacktip); tooltip.Append('['); for (int i = 0; i < GenericArgumentCount; i++) { if (i != 0) tooltip.Append(", "); tooltip.Append(GenericArgumentCount == 1 ? "T" : string.Format(CultureInfo.InvariantCulture, "T{0}", i + 1)); } tooltip.Append(']'); return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip.ToString()); } } /// <summary> /// This type represents a non-generic type for type name completion. It contains the actual type instance. /// </summary> private class TypeCompletion : TypeCompletionBase { internal Type Type; protected string GetTooltipPrefix() { if (typeof(Delegate).IsAssignableFrom(Type)) return "Delegate "; if (Type.IsInterface) return "Interface "; if (Type.IsClass) return "Class "; if (Type.IsEnum) return "Enum "; if (typeof(ValueType).IsAssignableFrom(Type)) return "Struct "; return string.Empty; // what other interesting types are there? } internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { return GetCompletionResult(keyMatched, prefix, suffix, null); } internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove) { string completion = ToStringCodeMethods.Type(Type, false, keyMatched); // If the completion included a namespace and ToStringCodeMethods.Type found // an accelerator, then just use the type's FullName instead because the user // probably didn't want the accelerator. if (keyMatched.Contains('.') && !completion.Contains('.')) { completion = Type.FullName; } if (!string.IsNullOrEmpty(namespaceToRemove) && completion.Equals(Type.FullName, StringComparison.OrdinalIgnoreCase)) { // Remove the namespace only if the completion text contains namespace completion = completion.Substring(namespaceToRemove.Length + 1); } string listItem = Type.Name; string tooltip = GetTooltipPrefix() + Type.FullName; return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip); } } /// <summary> /// This type represents a generic type for type name completion. It contains the actual type instance. /// </summary> private sealed class GenericTypeCompletion : TypeCompletion { internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { return GetCompletionResult(keyMatched, prefix, suffix, null); } internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove) { string fullNameWithoutBacktip = RemoveBackTick(Type.FullName); string completion = string.IsNullOrEmpty(namespaceToRemove) ? fullNameWithoutBacktip : fullNameWithoutBacktip.Substring(namespaceToRemove.Length + 1); string typeName = RemoveBackTick(Type.Name); var listItem = typeName + "<>"; var tooltip = new StringBuilder(); tooltip.Append(GetTooltipPrefix()); tooltip.Append(fullNameWithoutBacktip); tooltip.Append('['); var genericParameters = Type.GetGenericArguments(); for (int i = 0; i < genericParameters.Length; i++) { if (i != 0) tooltip.Append(", "); tooltip.Append(genericParameters[i].Name); } tooltip.Append(']'); return new CompletionResult(prefix + completion + suffix, listItem, CompletionResultType.Type, tooltip.ToString()); } } /// <summary> /// This type represents a namespace for namespace completion. /// </summary> private sealed class NamespaceCompletion : TypeCompletionBase { internal string Namespace; internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix) { var listItemText = Namespace; var dotIndex = listItemText.LastIndexOf('.'); if (dotIndex != -1) { listItemText = listItemText.Substring(dotIndex + 1); } return new CompletionResult(prefix + Namespace + suffix, listItemText, CompletionResultType.Namespace, "Namespace " + Namespace); } internal override CompletionResult GetCompletionResult(string keyMatched, string prefix, string suffix, string namespaceToRemove) { return GetCompletionResult(keyMatched, prefix, suffix); } } private sealed class TypeCompletionMapping { // The Key is the string we'll be searching on. It could complete to various things. internal string Key; internal List<TypeCompletionBase> Completions = new List<TypeCompletionBase>(); } private static TypeCompletionMapping[][] s_typeCache; private static TypeCompletionMapping[][] InitializeTypeCache() { #region Process_TypeAccelerators var entries = new Dictionary<string, TypeCompletionMapping>(StringComparer.OrdinalIgnoreCase); foreach (var type in TypeAccelerators.Get) { TypeCompletionMapping entry; var typeCompletionInstance = new TypeCompletion { Type = type.Value }; if (entries.TryGetValue(type.Key, out entry)) { // Check if this accelerator type is already included in the mapping entry referenced by the same key. Type acceleratorType = type.Value; bool typeAlreadyIncluded = entry.Completions.Any( item => { var typeCompletion = item as TypeCompletion; return typeCompletion != null && typeCompletion.Type == acceleratorType; }); // If it's already included, skip it. // This may happen when an accelerator name is the same as the short name of the type it represents, // and aslo that type has more than one accelerator names. For example: // "float" -> System.Single // "single" -> System.Single if (typeAlreadyIncluded) { continue; } // If this accelerator type is not included in the mapping entry, add it in. // This may happen when an accelerator name happens to be the short name of a different type (rare case). entry.Completions.Add(typeCompletionInstance); } else { entries.Add(type.Key, new TypeCompletionMapping { Key = type.Key, Completions = { typeCompletionInstance } }); } // If the full type name has already been included, then we know for sure that the short type name has also been included. string fullTypeName = type.Value.FullName; if (entries.ContainsKey(fullTypeName)) { continue; } // Otherwise, add the mapping from full type name to the type entries.Add(fullTypeName, new TypeCompletionMapping { Key = fullTypeName, Completions = { typeCompletionInstance } }); // If the short type name is the same as the accelerator name, then skip it to avoid duplication. string shortTypeName = type.Value.Name; if (type.Key.Equals(shortTypeName, StringComparison.OrdinalIgnoreCase)) { continue; } // Otherwise, add a new mapping entry, or put the TypeCompletion instance in the existing mapping entry. // For example, this may happen if both System.TimeoutException and System.ServiceProcess.TimeoutException // are in the TypeAccelerator cache. if (!entries.TryGetValue(shortTypeName, out entry)) { entry = new TypeCompletionMapping { Key = shortTypeName }; entries.Add(shortTypeName, entry); } entry.Completions.Add(typeCompletionInstance); } #endregion Process_TypeAccelerators #region Process_CoreCLR_TypeCatalog // In CoreCLR, we have namespace-qualified type names of all available .NET Core types stored in TypeCatalog. // Populate the type completion cache using the namespace-qualified type names. foreach (string fullTypeName in ClrFacade.AvailableDotNetTypeNames) { var typeCompInString = new TypeCompletionInStringFormat { FullTypeName = fullTypeName }; HandleNamespace(entries, typeCompInString.Namespace); HandleType(entries, fullTypeName, typeCompInString.ShortTypeName, null); } #endregion Process_CoreCLR_TypeCatalog #region Process_LoadedAssemblies foreach (Assembly assembly in ClrFacade.GetAssemblies()) { // Ignore the assemblies that are already covered by the type catalog if (ClrFacade.AvailableDotNetAssemblyNames.Contains(assembly.FullName)) { continue; } try { foreach (Type type in assembly.GetTypes()) { // Ignore non-public types if (!TypeResolver.IsPublic(type)) { continue; } HandleNamespace(entries, type.Namespace); HandleType(entries, type.FullName, type.Name, type); } } catch (ReflectionTypeLoadException) { } } #endregion Process_LoadedAssemblies var grouping = entries.Values.GroupBy(static t => t.Key.Count(c => c == '.')).OrderBy(static g => g.Key).ToArray(); var localTypeCache = new TypeCompletionMapping[grouping.Last().Key + 1][]; foreach (var group in grouping) { localTypeCache[group.Key] = group.ToArray(); } Interlocked.Exchange(ref s_typeCache, localTypeCache); return localTypeCache; } /// <summary> /// Handle namespace when initializing the type cache. /// </summary> /// <param name="entryCache">The TypeCompletionMapping dictionary.</param> /// <param name="namespace">The namespace.</param> private static void HandleNamespace(Dictionary<string, TypeCompletionMapping> entryCache, string @namespace) { if (string.IsNullOrEmpty(@namespace)) { return; } int dotIndex = 0; while (dotIndex != -1) { dotIndex = @namespace.IndexOf('.', dotIndex + 1); string subNamespace = dotIndex != -1 ? @namespace.Substring(0, dotIndex) : @namespace; TypeCompletionMapping entry; if (!entryCache.TryGetValue(subNamespace, out entry)) { entry = new TypeCompletionMapping { Key = subNamespace, Completions = { new NamespaceCompletion { Namespace = subNamespace } } }; entryCache.Add(subNamespace, entry); } else if (!entry.Completions.OfType<NamespaceCompletion>().Any()) { entry.Completions.Add(new NamespaceCompletion { Namespace = subNamespace }); } } } /// <summary> /// Handle a type when initializing the type cache. /// </summary> /// <param name="entryCache">The TypeCompletionMapping dictionary.</param> /// <param name="fullTypeName">The full type name.</param> /// <param name="shortTypeName">The short type name.</param> /// <param name="actualType">The actual type object. It may be null if we are handling type information from the CoreCLR TypeCatalog.</param> private static void HandleType(Dictionary<string, TypeCompletionMapping> entryCache, string fullTypeName, string shortTypeName, Type actualType) { if (string.IsNullOrEmpty(fullTypeName)) { return; } TypeCompletionBase typeCompletionBase = null; var backtick = fullTypeName.LastIndexOf('`'); var plusChar = fullTypeName.LastIndexOf('+'); bool isGenericTypeDefinition = backtick != -1; bool isNested = plusChar != -1; if (isGenericTypeDefinition) { // Nested generic types aren't useful for completion. if (isNested) { return; } typeCompletionBase = actualType != null ? (TypeCompletionBase)new GenericTypeCompletion { Type = actualType } : new GenericTypeCompletionInStringFormat { FullTypeName = fullTypeName }; // Remove the backtick, we only want 1 generic in our results for types like Func or Action. fullTypeName = fullTypeName.Substring(0, backtick); shortTypeName = shortTypeName.Substring(0, shortTypeName.LastIndexOf('`')); } else { typeCompletionBase = actualType != null ? (TypeCompletionBase)new TypeCompletion { Type = actualType } : new TypeCompletionInStringFormat { FullTypeName = fullTypeName }; } // If the full type name has already been included, then we know for sure that the short type // name and the accelerator type names (if there are any) have also been included. TypeCompletionMapping entry; if (!entryCache.TryGetValue(fullTypeName, out entry)) { entry = new TypeCompletionMapping { Key = fullTypeName, Completions = { typeCompletionBase } }; entryCache.Add(fullTypeName, entry); // Add a new mapping entry, or put the TypeCompletion instance in the existing mapping entry of the shortTypeName. // For example, this may happen to System.ServiceProcess.TimeoutException when System.TimeoutException is already in the cache. if (!entryCache.TryGetValue(shortTypeName, out entry)) { entry = new TypeCompletionMapping { Key = shortTypeName }; entryCache.Add(shortTypeName, entry); } entry.Completions.Add(typeCompletionBase); } } internal static List<CompletionResult> CompleteNamespace(CompletionContext context, string prefix = "", string suffix = "") { var localTypeCache = s_typeCache ?? InitializeTypeCache(); var results = new List<CompletionResult>(); var wordToComplete = context.WordToComplete; var dots = wordToComplete.Count(static c => c == '.'); if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; } var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); foreach (var entry in localTypeCache[dots].Where(e => e.Completions.OfType<NamespaceCompletion>().Any() && pattern.IsMatch(e.Key))) { foreach (var completion in entry.Completions) { results.Add(completion.GetCompletionResult(entry.Key, prefix, suffix)); } } results.Sort(static (c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } /// <summary> /// Complete a typename. /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static IEnumerable<CompletionResult> CompleteType(string typeName) { // When completing types, we don't care about the runspace, types are visible across the appdomain var powershell = (Runspace.DefaultRunspace == null) ? PowerShell.Create() : PowerShell.Create(RunspaceMode.CurrentRunspace); var helper = new PowerShellExecutionHelper(powershell); var executionContext = helper.CurrentPowerShell.Runspace.ExecutionContext; return CompleteType(new CompletionContext { WordToComplete = typeName, Helper = helper, ExecutionContext = executionContext }); } internal static List<CompletionResult> CompleteType(CompletionContext context, string prefix = "", string suffix = "") { var localTypeCache = s_typeCache ?? InitializeTypeCache(); var results = new List<CompletionResult>(); var completionTextSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); var wordToComplete = context.WordToComplete; var dots = wordToComplete.Count(static c => c == '.'); if (dots >= localTypeCache.Length || localTypeCache[dots] == null) { return results; } var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); foreach (var entry in localTypeCache[dots].Where(e => pattern.IsMatch(e.Key))) { foreach (var completion in entry.Completions) { string namespaceToRemove = GetNamespaceToRemove(context, completion); var completionResult = completion.GetCompletionResult(entry.Key, prefix, suffix, namespaceToRemove); // We might get the same completion result twice. For example, the type cache has: // DscResource->System.Management.Automation.DscResourceAttribute (from accelerator) // DscResourceAttribute->System.Management.Automation.DscResourceAttribute (from short type name) // input '[DSCRes' can match both of them, but they actually resolves to the same completion text 'DscResource'. if (!completionTextSet.Contains(completionResult.CompletionText)) { results.Add(completionResult); completionTextSet.Add(completionResult.CompletionText); } } } // this is a temporary fix. Only the type defined in the same script get complete. Need to use using Module when that is available. if (context.RelatedAsts != null && context.RelatedAsts.Count > 0) { var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; var typeAsts = scriptBlockAst.FindAll(static ast => ast is TypeDefinitionAst, false).Cast<TypeDefinitionAst>(); foreach (var typeAst in typeAsts.Where(ast => pattern.IsMatch(ast.Name))) { string toolTipPrefix = string.Empty; if (typeAst.IsInterface) toolTipPrefix = "Interface "; else if (typeAst.IsClass) toolTipPrefix = "Class "; else if (typeAst.IsEnum) toolTipPrefix = "Enum "; results.Add(new CompletionResult(prefix + typeAst.Name + suffix, typeAst.Name, CompletionResultType.Type, toolTipPrefix + typeAst.Name)); } } results.Sort(static (c1, c2) => string.Compare(c1.ListItemText, c2.ListItemText, StringComparison.OrdinalIgnoreCase)); return results; } private static string GetNamespaceToRemove(CompletionContext context, TypeCompletionBase completion) { if (completion is NamespaceCompletion || context.RelatedAsts == null || context.RelatedAsts.Count == 0) { return null; } var typeCompletion = completion as TypeCompletion; string typeNameSpace = typeCompletion != null ? typeCompletion.Type.Namespace : ((TypeCompletionInStringFormat)completion).Namespace; var scriptBlockAst = (ScriptBlockAst)context.RelatedAsts[0]; var matchingNsStates = scriptBlockAst.UsingStatements.Where(s => s.UsingStatementKind == UsingStatementKind.Namespace && typeNameSpace != null && typeNameSpace.StartsWith(s.Name.Value, StringComparison.OrdinalIgnoreCase)); string ns = string.Empty; foreach (var nsState in matchingNsStates) { if (nsState.Name.Extent.Text.Length > ns.Length) { ns = nsState.Name.Extent.Text; } } return ns; } #endregion Types #region Help Topics internal static List<CompletionResult> CompleteHelpTopics(CompletionContext context) { var results = new List<CompletionResult>(); string userHelpDir = HelpUtils.GetUserHomeHelpSearchPath(); string appHelpDir = Utils.GetApplicationBase(Utils.DefaultPowerShellShellID); string currentCulture = CultureInfo.CurrentCulture.Name; //search for help files for the current culture + en-US as fallback var searchPaths = new string[] { Path.Combine(userHelpDir, currentCulture), Path.Combine(appHelpDir, currentCulture), Path.Combine(userHelpDir, "en-US"), Path.Combine(appHelpDir, "en-US") }.Distinct(); string wordToComplete = context.WordToComplete + "*"; try { var wildcardPattern = WildcardPattern.Get(wordToComplete, WildcardOptions.IgnoreCase); foreach (var dir in searchPaths) { var currentDir = new DirectoryInfo(dir); if (currentDir.Exists) { foreach (var file in currentDir.EnumerateFiles("about_*.help.txt")) { if (wildcardPattern.IsMatch(file.Name)) { string topicName = file.Name.Substring(0, file.Name.LastIndexOf(".help.txt")); results.Add(new CompletionResult(topicName)); } } } } } catch (Exception) { } return results; } #endregion Help Topics #region Statement Parameters internal static List<CompletionResult> CompleteStatementFlags(TokenKind kind, string wordToComplete) { switch (kind) { case TokenKind.Switch: Diagnostics.Assert(!string.IsNullOrEmpty(wordToComplete) && wordToComplete[0].IsDash(), "the word to complete should start with '-'"); wordToComplete = wordToComplete.Substring(1); bool withColon = wordToComplete.EndsWith(':'); wordToComplete = withColon ? wordToComplete.Remove(wordToComplete.Length - 1) : wordToComplete; string enumString = LanguagePrimitives.EnumSingleTypeConverter.EnumValues(typeof(SwitchFlags)); string separator = CultureInfo.CurrentUICulture.TextInfo.ListSeparator; string[] enumArray = enumString.Split(separator, StringSplitOptions.RemoveEmptyEntries); var pattern = WildcardPattern.Get(wordToComplete + "*", WildcardOptions.IgnoreCase); var enumList = new List<string>(); var result = new List<CompletionResult>(); CompletionResult fullMatch = null; foreach (string value in enumArray) { if (value.Equals(SwitchFlags.None.ToString(), StringComparison.OrdinalIgnoreCase)) { continue; } if (wordToComplete.Equals(value, StringComparison.OrdinalIgnoreCase)) { string completionText = withColon ? "-" + value + ":" : "-" + value; fullMatch = new CompletionResult(completionText, value, CompletionResultType.ParameterName, value); continue; } if (pattern.IsMatch(value)) { enumList.Add(value); } } if (fullMatch != null) { result.Add(fullMatch); } enumList.Sort(); result.AddRange(from entry in enumList let completionText = withColon ? "-" + entry + ":" : "-" + entry select new CompletionResult(completionText, entry, CompletionResultType.ParameterName, entry)); return result; default: break; } return null; } #endregion Statement Parameters #region Hashtable Keys /// <summary> /// Generate auto complete results for hashtable key within a Dynamickeyword. /// Results are generated based on properties of a DynamicKeyword matches given identifier. /// For example, following "D" matches "DestinationPath" /// /// Configuration /// { /// File /// { /// D^ /// } /// } /// </summary> /// <param name="completionContext"></param> /// <param name="ast"></param> /// <param name="hashtableAst"></param> /// <returns></returns> internal static List<CompletionResult> CompleteHashtableKeyForDynamicKeyword( CompletionContext completionContext, DynamicKeywordStatementAst ast, HashtableAst hashtableAst) { Diagnostics.Assert(ast.Keyword != null, "DynamicKeywordStatementAst.Keyword can never be null"); List<CompletionResult> results = null; var dynamicKeywordProperties = ast.Keyword.Properties; var memberPattern = completionContext.WordToComplete + "*"; // // Capture all existing properties in hashtable // var propertiesName = new List<string>(); int cursorOffset = completionContext.CursorPosition.Offset; foreach (var keyValueTuple in hashtableAst.KeyValuePairs) { var propName = keyValueTuple.Item1 as StringConstantExpressionAst; // Exclude the property name at cursor if (propName != null && propName.Extent.EndOffset != cursorOffset) { propertiesName.Add(propName.Value); } } if (dynamicKeywordProperties.Count > 0) { // Excludes existing properties in the hashtable statement var tempProperties = dynamicKeywordProperties.Where(p => !propertiesName.Contains(p.Key, StringComparer.OrdinalIgnoreCase)); if (tempProperties != null && tempProperties.Any()) { results = new List<CompletionResult>(); // Filter by name var wildcardPattern = WildcardPattern.Get(memberPattern, WildcardOptions.IgnoreCase); var matchedResults = tempProperties.Where(p => wildcardPattern.IsMatch(p.Key)); if (matchedResults == null || !matchedResults.Any()) { // Fallback to all non-exist properties in the hashtable statement matchedResults = tempProperties; } foreach (var p in matchedResults) { string psTypeName = LanguagePrimitives.ConvertTypeNameToPSTypeName(p.Value.TypeConstraint); if (psTypeName == "[]" || string.IsNullOrEmpty(psTypeName)) { psTypeName = "[" + p.Value.TypeConstraint + "]"; } if (string.Equals(psTypeName, "[MSFT_Credential]", StringComparison.OrdinalIgnoreCase)) { psTypeName = "[pscredential]"; } results.Add(new CompletionResult( p.Key + " = ", p.Key, CompletionResultType.Property, psTypeName)); } } } return results; } internal static List<CompletionResult> CompleteHashtableKey(CompletionContext completionContext, HashtableAst hashtableAst) { int cursorOffset = completionContext.CursorPosition.Offset; string wordToComplete = completionContext.WordToComplete; var excludedKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var keyPair in hashtableAst.KeyValuePairs) { // Exclude all existing keys, except the key the cursor is currently at if (!(cursorOffset >= keyPair.Item1.Extent.StartOffset && cursorOffset <= keyPair.Item1.Extent.EndOffset)) { excludedKeys.Add(keyPair.Item1.Extent.Text); } } var typeAst = hashtableAst.Parent as ConvertExpressionAst; if (typeAst != null) { var result = new List<CompletionResult>(); CompleteMemberByInferredType( completionContext.TypeInferenceContext, AstTypeInference.InferTypeOf(typeAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval), result, wordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); return result; } // hashtable arguments sometimes have expected keys. Examples: // new-object System.Drawing.Point -prop @{ X=1; Y=1 } // dir | sort-object -prop @{Expression=... ; Ascending=... } // format-table -Property // Expression // FormatString // Label // Width // Alignment // format-list -Property // Expression // FormatString // Label // format-custom -Property // Expression // Depth // format-* -GroupBy // Expression // FormatString // Label // // Find out if we are in a command argument. Consider the following possibilities: // cmd @{} // cmd -foo @{} // cmd -foo:@{} // cmd @{},@{} // cmd -foo @{},@{} // cmd -foo:@{},@{} var ast = hashtableAst.Parent; // Handle completion for hashtable within DynamicKeyword statement var dynamicKeywordStatementAst = ast as DynamicKeywordStatementAst; if (dynamicKeywordStatementAst != null) { return CompleteHashtableKeyForDynamicKeyword(completionContext, dynamicKeywordStatementAst, hashtableAst); } if (ast is ArrayLiteralAst) { ast = ast.Parent; } if (ast is CommandParameterAst) { ast = ast.Parent; } var commandAst = ast as CommandAst; if (commandAst != null) { var binding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, null, bindingType: PseudoParameterBinder.BindingType.ArgumentCompletion); if (binding == null) { return null; } string parameterName = null; foreach (var boundArg in binding.BoundArguments) { var astPair = boundArg.Value as AstPair; if (astPair != null) { if (astPair.Argument == hashtableAst) { parameterName = boundArg.Key; break; } continue; } var astArrayPair = boundArg.Value as AstArrayPair; if (astArrayPair != null) { if (astArrayPair.Argument.Contains(hashtableAst)) { parameterName = boundArg.Key; break; } continue; } } if (parameterName != null) { if (parameterName.Equals("GroupBy", StringComparison.OrdinalIgnoreCase)) { switch (binding.CommandName) { case "Format-Table": case "Format-List": case "Format-Wide": case "Format-Custom": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); } return null; } if (parameterName.Equals("Property", StringComparison.OrdinalIgnoreCase)) { switch (binding.CommandName) { case "New-Object": var inferredType = AstTypeInference.InferTypeOf(commandAst, completionContext.TypeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); var result = new List<CompletionResult>(); CompleteMemberByInferredType( completionContext.TypeInferenceContext, inferredType, result, completionContext.WordToComplete + "*", IsWriteablePropertyMember, isStatic: false, excludedKeys); return result; case "Select-Object": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Name", "Expression"); case "Sort-Object": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Ascending", "Descending"); case "Group-Object": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression"); case "Format-Table": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label", "Width", "Alignment"); case "Format-List": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString", "Label"); case "Format-Wide": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "FormatString"); case "Format-Custom": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "Expression", "Depth"); case "Set-CimInstance": case "New-CimInstance": var results = new List<CompletionResult>(); NativeCompletionCimCommands(parameterName, binding.BoundArguments, results, commandAst, completionContext, excludedKeys, binding.CommandName); // this method adds a null CompletionResult to the list but we don't want that here. if (results.Count > 1) { results.RemoveAt(results.Count - 1); return results; } return null; } } if (parameterName.Equals("FilterHashtable", StringComparison.OrdinalIgnoreCase)) { switch (binding.CommandName) { case "Get-WinEvent": return GetSpecialHashTableKeyMembers(excludedKeys, wordToComplete, "LogName", "ProviderName", "Path", "Keywords", "ID", "Level", "StartTime", "EndTime", "UserID", "Data", "SuppressHashFilter"); } } if (parameterName.Equals("Arguments", StringComparison.OrdinalIgnoreCase)) { switch (binding.CommandName) { case "Invoke-CimMethod": var result = new List<CompletionResult>(); NativeCompletionCimCommands(parameterName, binding.BoundArguments, result, commandAst, completionContext, excludedKeys, binding.CommandName); // this method adds a null CompletionResult to the list but we don't want that here. if (result.Count > 1) { result.RemoveAt(result.Count - 1); return result; } return null; } } } } if (ast.Parent is AssignmentStatementAst assignment && assignment.Left is VariableExpressionAst assignmentVar) { var firstSplatUse = completionContext.RelatedAsts[0].Find( currentAst => currentAst.Extent.StartOffset > hashtableAst.Extent.EndOffset && currentAst is VariableExpressionAst splatVar && splatVar.Splatted && splatVar.VariablePath.UserPath.Equals(assignmentVar.VariablePath.UserPath, StringComparison.OrdinalIgnoreCase), searchNestedScriptBlocks: true) as VariableExpressionAst; if (firstSplatUse is not null && firstSplatUse.Parent is CommandAst command) { var binding = new PseudoParameterBinder() .DoPseudoParameterBinding( command, pipeArgumentType: null, paramAstAtCursor: null, PseudoParameterBinder.BindingType.ParameterCompletion); if (binding is null) { return null; } var results = new List<CompletionResult>(); foreach (var parameter in binding.UnboundParameters) { if (!excludedKeys.Contains(parameter.Parameter.Name) && (wordToComplete is null || parameter.Parameter.Name.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase))) { results.Add(new CompletionResult(parameter.Parameter.Name, parameter.Parameter.Name, CompletionResultType.ParameterName, $"[{parameter.Parameter.Type.Name}]")); } } if (results.Count > 0) { return results; } } } return null; } private static List<CompletionResult> GetSpecialHashTableKeyMembers(HashSet<string> excludedKeys, string wordToComplete, params string[] keys) { var result = new List<CompletionResult>(); foreach (string key in keys) { if ((string.IsNullOrEmpty(wordToComplete) || key.StartsWith(wordToComplete, StringComparison.OrdinalIgnoreCase)) && !excludedKeys.Contains(key)) { result.Add(new CompletionResult(key, key, CompletionResultType.Property, key)); } } if (result.Count == 0) { return null; } return result; } #endregion Hashtable Keys #region Helpers internal static bool IsPathSafelyExpandable(ExpandableStringExpressionAst expandableStringAst, string extraText, ExecutionContext executionContext, out string expandedString) { expandedString = null; // Expand the string if its type is DoubleQuoted or BareWord var constType = expandableStringAst.StringConstantType; if (constType == StringConstantType.DoubleQuotedHereString) { return false; } Diagnostics.Assert( constType == StringConstantType.BareWord || (constType == StringConstantType.DoubleQuoted && expandableStringAst.Extent.Text[0].IsDoubleQuote()), "the string to be expanded should be either BareWord or DoubleQuoted"); var varValues = new List<string>(); foreach (ExpressionAst nestedAst in expandableStringAst.NestedExpressions) { if (!(nestedAst is VariableExpressionAst variableAst)) { return false; } string strValue = CombineVariableWithPartialPath(variableAst, null, executionContext); if (strValue != null) { varValues.Add(strValue); } else { return false; } } var formattedString = string.Format(CultureInfo.InvariantCulture, expandableStringAst.FormatExpression, varValues.ToArray()); string quote = (constType == StringConstantType.DoubleQuoted) ? "\"" : string.Empty; expandedString = quote + formattedString + extraText + quote; return true; } internal static string CombineVariableWithPartialPath(VariableExpressionAst variableAst, string extraText, ExecutionContext executionContext) { var varPath = variableAst.VariablePath; if (varPath.IsVariable || varPath.DriveName.Equals("env", StringComparison.OrdinalIgnoreCase)) { try { // We check the strict mode inside GetVariableValue object value = VariableOps.GetVariableValue(varPath, executionContext, variableAst); var strValue = (value == null) ? string.Empty : value as string; if (strValue == null) { object baseObj = PSObject.Base(value); if (baseObj is string || baseObj.GetType().IsPrimitive) { strValue = LanguagePrimitives.ConvertTo<string>(value); } } if (strValue != null) { return strValue + extraText; } } catch (Exception) { } } return null; } internal static string HandleDoubleAndSingleQuote(ref string wordToComplete) { string quote = string.Empty; if (!string.IsNullOrEmpty(wordToComplete) && (wordToComplete[0].IsSingleQuote() || wordToComplete[0].IsDoubleQuote())) { char frontQuote = wordToComplete[0]; int length = wordToComplete.Length; if (length == 1) { wordToComplete = string.Empty; quote = frontQuote.IsSingleQuote() ? "'" : "\""; } else if (length > 1) { if ((wordToComplete[length - 1].IsDoubleQuote() && frontQuote.IsDoubleQuote()) || (wordToComplete[length - 1].IsSingleQuote() && frontQuote.IsSingleQuote())) { wordToComplete = wordToComplete.Substring(1, length - 2); quote = frontQuote.IsSingleQuote() ? "'" : "\""; } else if (!wordToComplete[length - 1].IsDoubleQuote() && !wordToComplete[length - 1].IsSingleQuote()) { wordToComplete = wordToComplete.Substring(1); quote = frontQuote.IsSingleQuote() ? "'" : "\""; } } } return quote; } internal static bool IsSplattedVariable(Ast targetExpr) { if (targetExpr is VariableExpressionAst && ((VariableExpressionAst)targetExpr).Splatted) { // It's splatted variable, member expansion is not useful return true; } return false; } internal static void CompleteMemberHelper( bool @static, string memberName, ExpressionAst targetExpr, CompletionContext context, List<CompletionResult> results) { object value; if (SafeExprEvaluator.TrySafeEval(targetExpr, context.ExecutionContext, out value) && value != null) { if (targetExpr is ArrayExpressionAst && value is not object[]) { // When the array contains only one element, the evaluation result would be that element. We wrap it into an array value = new[] { value }; } // Instead of Get-Member, we access the members directly and send as input to the pipe. var powerShellExecutionHelper = context.Helper; powerShellExecutionHelper .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Core\\Where-Object") .AddParameter("Property", "Name") .AddParameter("Like") .AddParameter("Value", memberName) .AddCommandWithPreferenceSetting("Microsoft.PowerShell.Utility\\Sort-Object") .AddParameter("Property", new object[] { "MemberType", "Name" }); IEnumerable members; if (@static) { if (!(PSObject.Base(value) is Type type)) { return; } members = PSObject.DotNetStaticAdapter.BaseGetMembers<PSMemberInfo>(type); } else { members = PSObject.AsPSObject(value).Members; } var sortedMembers = powerShellExecutionHelper.ExecuteCurrentPowerShell(out _, members); foreach (var member in sortedMembers) { var memberInfo = (PSMemberInfo)PSObject.Base(member); if (memberInfo.IsHidden) { continue; } var completionText = memberInfo.Name; // Handle scenarios like this: $aa | add-member 'a b' 23; $aa.a<tab> if (completionText.IndexOfAny(s_charactersRequiringQuotes) != -1) { completionText = completionText.Replace("'", "''"); completionText = "'" + completionText + "'"; } var isMethod = memberInfo is PSMethodInfo; if (isMethod) { var isSpecial = (memberInfo is PSMethod) && ((PSMethod)memberInfo).IsSpecial; if (isSpecial) continue; completionText += '('; } string tooltip = memberInfo.ToString(); if (tooltip.Contains("),", StringComparison.Ordinal)) { var overloads = tooltip.Split("),", StringSplitOptions.RemoveEmptyEntries); var newTooltip = new StringBuilder(); foreach (var overload in overloads) { newTooltip.Append(overload.Trim() + ")\r\n"); } newTooltip.Remove(newTooltip.Length - 3, 3); tooltip = newTooltip.ToString(); } results.Add( new CompletionResult(completionText, memberInfo.Name, isMethod ? CompletionResultType.Method : CompletionResultType.Property, tooltip)); } var dictionary = PSObject.Base(value) as IDictionary; if (dictionary != null) { var pattern = WildcardPattern.Get(memberName, WildcardOptions.IgnoreCase); foreach (DictionaryEntry entry in dictionary) { if (!(entry.Key is string key)) continue; if (pattern.IsMatch(key)) { // Handle scenarios like this: $hashtable["abc#d"] = 100; $hashtable.ab<tab> if (key.IndexOfAny(s_charactersRequiringQuotes) != -1) { key = key.Replace("'", "''"); key = "'" + key + "'"; } results.Add(new CompletionResult(key, key, CompletionResultType.Property, key)); } } } if (!@static && IsValueEnumerable(PSObject.Base(value))) { // Complete extension methods 'Where' and 'ForEach' for Enumerable values CompleteExtensionMethods(memberName, results); } } } /// <summary> /// Check if a value is treated as Enumerable in powershell. /// </summary> private static bool IsValueEnumerable(object value) { object baseValue = PSObject.Base(value); if (baseValue == null || baseValue is string || baseValue is PSObject || baseValue is IDictionary || baseValue is System.Xml.XmlNode) { return false; } if (baseValue is IEnumerable || baseValue is IEnumerator || baseValue is DataTable) { return true; } return false; } /// <summary> /// Check if a strong type is treated as Enumerable in powershell. /// </summary> private static bool IsStaticTypeEnumerable(Type type) { if (type.Equals(typeof(string)) || typeof(IDictionary).IsAssignableFrom(type) || typeof(System.Xml.XmlNode).IsAssignableFrom(type)) { return false; } if (typeof(IEnumerable).IsAssignableFrom(type) || typeof(IEnumerator).IsAssignableFrom(type)) { return true; } return false; } private static bool CompletionRequiresQuotes(string completion, bool escape) { // If the tokenizer sees the completion as more than two tokens, or if there is some error, then // some form of quoting is necessary (if it's a variable, we'd need ${}, filenames would need [], etc.) Language.Token[] tokens; ParseError[] errors; Language.Parser.ParseInput(completion, out tokens, out errors); char[] charToCheck = escape ? new[] { '$', '[', ']', '`' } : new[] { '$', '`' }; // Expect no errors and 2 tokens (1 is for our completion, the other is eof) // Or if the completion is a keyword, we ignore the errors bool requireQuote = !(errors.Length == 0 && tokens.Length == 2); if ((!requireQuote && tokens[0] is StringToken) || (tokens.Length == 2 && (tokens[0].TokenFlags & TokenFlags.Keyword) != 0)) { requireQuote = false; var value = tokens[0].Text; if (value.IndexOfAny(charToCheck) != -1) requireQuote = true; } return requireQuote; } private static bool ProviderSpecified(string path) { var index = path.IndexOf(':'); return index != -1 && index + 1 < path.Length && path[index + 1] == ':'; } private static Type GetEffectiveParameterType(Type type) { var underlying = Nullable.GetUnderlyingType(type); return underlying ?? type; } /// <summary> /// Turn on the "LiteralPaths" option. /// </summary> /// <param name="completionContext"></param> /// <returns> /// Indicate whether the "LiteralPaths" option needs to be removed after operation /// </returns> private static bool TurnOnLiteralPathOption(CompletionContext completionContext) { bool clearLiteralPathsKey = false; if (completionContext.Options == null) { completionContext.Options = new Hashtable { { "LiteralPaths", true } }; clearLiteralPathsKey = true; } else if (!completionContext.Options.ContainsKey("LiteralPaths")) { // Dont escape '[',']','`' when the file name is treated as command name completionContext.Options.Add("LiteralPaths", true); clearLiteralPathsKey = true; } return clearLiteralPathsKey; } /// <summary> /// Return whether we need to add ampersand when it's necessary. /// </summary> /// <param name="context"></param> /// <param name="defaultChoice"></param> /// <returns></returns> internal static bool IsAmpersandNeeded(CompletionContext context, bool defaultChoice) { if (context.RelatedAsts != null && !string.IsNullOrEmpty(context.WordToComplete)) { var lastAst = context.RelatedAsts.Last(); var parent = lastAst.Parent as CommandAst; if (parent != null && parent.CommandElements.Count == 1 && ((!defaultChoice && parent.InvocationOperator == TokenKind.Unknown) || (defaultChoice && parent.InvocationOperator != TokenKind.Unknown))) { // - When the default choice is NOT to add ampersand, we only return true // when the invocation operator is NOT specified. // - When the default choice is to add ampersand, we only return false // when the invocation operator is specified. defaultChoice = !defaultChoice; } } return defaultChoice; } private sealed class ItemPathComparer : IComparer<PSObject> { public int Compare(PSObject x, PSObject y) { var xPathInfo = PSObject.Base(x) as PathInfo; var xFileInfo = PSObject.Base(x) as IO.FileSystemInfo; var xPathStr = PSObject.Base(x) as string; var yPathInfo = PSObject.Base(y) as PathInfo; var yFileInfo = PSObject.Base(y) as IO.FileSystemInfo; var yPathStr = PSObject.Base(y) as string; string xPath = null, yPath = null; if (xPathInfo != null) xPath = xPathInfo.ProviderPath; else if (xFileInfo != null) xPath = xFileInfo.FullName; else if (xPathStr != null) xPath = xPathStr; if (yPathInfo != null) yPath = yPathInfo.ProviderPath; else if (yFileInfo != null) yPath = yFileInfo.FullName; else if (yPathStr != null) yPath = yPathStr; if (string.IsNullOrEmpty(xPath) || string.IsNullOrEmpty(yPath)) Diagnostics.Assert(false, "Base object of item PSObject should be either PathInfo or FileSystemInfo"); return string.Compare(xPath, yPath, StringComparison.CurrentCultureIgnoreCase); } } private sealed class CommandNameComparer : IComparer<PSObject> { public int Compare(PSObject x, PSObject y) { string xName = null; string yName = null; object xObj = PSObject.Base(x); object yObj = PSObject.Base(y); var xCommandInfo = xObj as CommandInfo; xName = xCommandInfo != null ? xCommandInfo.Name : xObj as string; var yCommandInfo = yObj as CommandInfo; yName = yCommandInfo != null ? yCommandInfo.Name : yObj as string; if (xName == null || yName == null) Diagnostics.Assert(false, "Base object of Command PSObject should be either CommandInfo or string"); return string.Compare(xName, yName, StringComparison.OrdinalIgnoreCase); } } #endregion Helpers } /// <summary> /// This class is very similar to the restricted language checker, but it is meant to allow more things, yet still /// be considered "safe", at least in the sense that tab completion can rely on it to not do bad things. The primary /// use is for intellisense where you don't want to run arbitrary code, but you do want to know the values /// of various expressions so you can get the members. /// </summary> internal class SafeExprEvaluator : ICustomAstVisitor2 { internal static bool TrySafeEval(ExpressionAst ast, ExecutionContext executionContext, out object value) { if (!(bool)ast.Accept(new SafeExprEvaluator())) { value = null; return false; } try { // ConstrainedLanguage has already been applied as necessary when we construct CompletionContext Diagnostics.Assert(!(executionContext.HasRunspaceEverUsedConstrainedLanguageMode && executionContext.LanguageMode != PSLanguageMode.ConstrainedLanguage), "If the runspace has ever used constrained language mode, then the current language mode should already be set to constrained language"); // We're passing 'true' here for isTrustedInput, because SafeExprEvaluator ensures that the AST // has no dangerous side-effects such as arbitrary expression evaluation. It does require variable // access and a few other minor things, which staples of tab completion: // // $t = Get-Process // $t[0].MainModule.<TAB> // value = Compiler.GetExpressionValue(ast, true, executionContext); return true; } catch { value = null; return false; } } public object VisitErrorStatement(ErrorStatementAst errorStatementAst) { return false; } public object VisitErrorExpression(ErrorExpressionAst errorExpressionAst) { return false; } public object VisitScriptBlock(ScriptBlockAst scriptBlockAst) { return false; } public object VisitParamBlock(ParamBlockAst paramBlockAst) { return false; } public object VisitNamedBlock(NamedBlockAst namedBlockAst) { return false; } public object VisitTypeConstraint(TypeConstraintAst typeConstraintAst) { return false; } public object VisitAttribute(AttributeAst attributeAst) { return false; } public object VisitNamedAttributeArgument(NamedAttributeArgumentAst namedAttributeArgumentAst) { return false; } public object VisitParameter(ParameterAst parameterAst) { return false; } public object VisitFunctionDefinition(FunctionDefinitionAst functionDefinitionAst) { return false; } public object VisitIfStatement(IfStatementAst ifStmtAst) { return false; } public object VisitTrap(TrapStatementAst trapStatementAst) { return false; } public object VisitSwitchStatement(SwitchStatementAst switchStatementAst) { return false; } public object VisitDataStatement(DataStatementAst dataStatementAst) { return false; } public object VisitForEachStatement(ForEachStatementAst forEachStatementAst) { return false; } public object VisitDoWhileStatement(DoWhileStatementAst doWhileStatementAst) { return false; } public object VisitForStatement(ForStatementAst forStatementAst) { return false; } public object VisitWhileStatement(WhileStatementAst whileStatementAst) { return false; } public object VisitCatchClause(CatchClauseAst catchClauseAst) { return false; } public object VisitTryStatement(TryStatementAst tryStatementAst) { return false; } public object VisitBreakStatement(BreakStatementAst breakStatementAst) { return false; } public object VisitContinueStatement(ContinueStatementAst continueStatementAst) { return false; } public object VisitReturnStatement(ReturnStatementAst returnStatementAst) { return false; } public object VisitExitStatement(ExitStatementAst exitStatementAst) { return false; } public object VisitThrowStatement(ThrowStatementAst throwStatementAst) { return false; } public object VisitDoUntilStatement(DoUntilStatementAst doUntilStatementAst) { return false; } public object VisitAssignmentStatement(AssignmentStatementAst assignmentStatementAst) { return false; } // REVIEW: we could relax this to allow specific commands public object VisitCommand(CommandAst commandAst) { return false; } public object VisitCommandExpression(CommandExpressionAst commandExpressionAst) { return false; } public object VisitCommandParameter(CommandParameterAst commandParameterAst) { return false; } public object VisitFileRedirection(FileRedirectionAst fileRedirectionAst) { return false; } public object VisitMergingRedirection(MergingRedirectionAst mergingRedirectionAst) { return false; } public object VisitExpandableStringExpression(ExpandableStringExpressionAst expandableStringExpressionAst) { return false; } public object VisitAttributedExpression(AttributedExpressionAst attributedExpressionAst) { return false; } public object VisitBlockStatement(BlockStatementAst blockStatementAst) { return false; } public object VisitInvokeMemberExpression(InvokeMemberExpressionAst invokeMemberExpressionAst) { return false; } public object VisitUsingExpression(UsingExpressionAst usingExpressionAst) { return false; } public object VisitTypeDefinition(TypeDefinitionAst typeDefinitionAst) { return false; } public object VisitPropertyMember(PropertyMemberAst propertyMemberAst) { return false; } public object VisitFunctionMember(FunctionMemberAst functionMemberAst) { return false; } public object VisitBaseCtorInvokeMemberExpression(BaseCtorInvokeMemberExpressionAst baseCtorInvokeMemberExpressionAst) { return false; } public object VisitUsingStatement(UsingStatementAst usingStatementAst) { return false; } public object VisitDynamicKeywordStatement(DynamicKeywordStatementAst dynamicKeywordStatementAst) { return false; } public object VisitPipelineChain(PipelineChainAst pipelineChainAst) { return false; } public object VisitConfigurationDefinition(ConfigurationDefinitionAst configurationDefinitionAst) { return configurationDefinitionAst.Body.Accept(this); } public object VisitStatementBlock(StatementBlockAst statementBlockAst) { if (statementBlockAst.Traps != null) return false; // REVIEW: we could relax this to allow multiple statements if (statementBlockAst.Statements.Count > 1) return false; var pipeline = statementBlockAst.Statements.FirstOrDefault(); return pipeline != null && (bool)pipeline.Accept(this); } public object VisitPipeline(PipelineAst pipelineAst) { var expr = pipelineAst.GetPureExpression(); return expr != null && (bool)expr.Accept(this); } public object VisitTernaryExpression(TernaryExpressionAst ternaryExpressionAst) { return (bool)ternaryExpressionAst.Condition.Accept(this) && (bool)ternaryExpressionAst.IfTrue.Accept(this) && (bool)ternaryExpressionAst.IfFalse.Accept(this); } public object VisitBinaryExpression(BinaryExpressionAst binaryExpressionAst) { return (bool)binaryExpressionAst.Left.Accept(this) && (bool)binaryExpressionAst.Right.Accept(this); } public object VisitUnaryExpression(UnaryExpressionAst unaryExpressionAst) { return (bool)unaryExpressionAst.Child.Accept(this); } public object VisitConvertExpression(ConvertExpressionAst convertExpressionAst) { return (bool)convertExpressionAst.Child.Accept(this); } public object VisitConstantExpression(ConstantExpressionAst constantExpressionAst) { return true; } public object VisitStringConstantExpression(StringConstantExpressionAst stringConstantExpressionAst) { return true; } public object VisitSubExpression(SubExpressionAst subExpressionAst) { return subExpressionAst.SubExpression.Accept(this); } public object VisitVariableExpression(VariableExpressionAst variableExpressionAst) { return true; } public object VisitTypeExpression(TypeExpressionAst typeExpressionAst) { return true; } public object VisitMemberExpression(MemberExpressionAst memberExpressionAst) { return (bool)memberExpressionAst.Expression.Accept(this) && (bool)memberExpressionAst.Member.Accept(this); } public object VisitIndexExpression(IndexExpressionAst indexExpressionAst) { return (bool)indexExpressionAst.Target.Accept(this) && (bool)indexExpressionAst.Index.Accept(this); } public object VisitArrayExpression(ArrayExpressionAst arrayExpressionAst) { return arrayExpressionAst.SubExpression.Accept(this); } public object VisitArrayLiteral(ArrayLiteralAst arrayLiteralAst) { return arrayLiteralAst.Elements.All(e => (bool)e.Accept(this)); } public object VisitHashtable(HashtableAst hashtableAst) { foreach (var keyValuePair in hashtableAst.KeyValuePairs) { if (!(bool)keyValuePair.Item1.Accept(this)) return false; if (!(bool)keyValuePair.Item2.Accept(this)) return false; } return true; } public object VisitScriptBlockExpression(ScriptBlockExpressionAst scriptBlockExpressionAst) { return true; } public object VisitParenExpression(ParenExpressionAst parenExpressionAst) { return parenExpressionAst.Pipeline.Accept(this); } } /// <summary> /// Completes with the property names of the InputObject. /// </summary> internal class PropertyNameCompleter : IArgumentCompleter { private readonly string _parameterNameOfInput; /// <summary> /// Initializes a new instance of the <see cref="PropertyNameCompleter"/> class. /// </summary> public PropertyNameCompleter() { _parameterNameOfInput = "InputObject"; } /// <summary> /// Initializes a new instance of the <see cref="PropertyNameCompleter"/> class. /// </summary> /// <param name="parameterNameOfInput">The name of the property of the input object for which to complete with property names.</param> public PropertyNameCompleter(string parameterNameOfInput) { _parameterNameOfInput = parameterNameOfInput; } IEnumerable<CompletionResult> IArgumentCompleter.CompleteArgument( string commandName, string parameterName, string wordToComplete, CommandAst commandAst, IDictionary fakeBoundParameters) { if (commandAst.Parent is not PipelineAst pipelineAst) { return null; } int i; for (i = 0; i < pipelineAst.PipelineElements.Count; i++) { if (pipelineAst.PipelineElements[i] == commandAst) { break; } } var typeInferenceContext = new TypeInferenceContext(); IEnumerable<PSTypeName> prevType; if (i == 0) { var parameterAst = (CommandParameterAst)commandAst.Find(ast => ast is CommandParameterAst cpa && cpa.ParameterName == "PropertyName", false); var pseudoBinding = new PseudoParameterBinder().DoPseudoParameterBinding(commandAst, null, parameterAst, PseudoParameterBinder.BindingType.ParameterCompletion); if (!pseudoBinding.BoundArguments.TryGetValue(_parameterNameOfInput, out var pair) || !pair.ArgumentSpecified) { return null; } if (pair is AstPair astPair && astPair.Argument != null) { prevType = AstTypeInference.InferTypeOf(astPair.Argument, typeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } return null; } else { prevType = AstTypeInference.InferTypeOf(pipelineAst.PipelineElements[i - 1], typeInferenceContext, TypeInferenceRuntimePermissions.AllowSafeEval); } var result = new List<CompletionResult>(); CompletionCompleters.CompleteMemberByInferredType(typeInferenceContext, prevType, result, wordToComplete + "*", filter: CompletionCompleters.IsPropertyMember, isStatic: false); return result; } } }
JamesWTruher/PowerShell-1
src/System.Management.Automation/engine/CommandCompletion/CompletionCompleters.cs
C#
mit
361,440
<!DOCTYPE html> <html lang="en"> <head> <!-- SEO n' stuff --> <meta name="title" content="Shapr โ€“ ร˜yvind Nordbรธ"> <meta name="description" content="Introducing Shapr, a smart rubberband that tracks all your vitals. It's the personal coach that knows everything about your health, that can always tell you what to do to progress efficiently. Itโ€™s constantly monitoring your health, and translates that into data you can understand."> <!-- Facebook --> <meta property="og:title" content="Shapr โ€“ ร˜yvind Nordbรธ"> <!-- 1200x650px --> <meta property="og:image" content="http://oyvind.co/facebook/shapr/Shapr_FB.jpg"> <meta property="og:url" content="http://oyvind.co/shapr"> <meta property="og:description" content="Introducing Shapr, a smart rubberband that tracks all your vitals. It's the personal coach that knows everything about your health, that can always tell you what to do to progress efficiently. Itโ€™s constantly monitoring your health, and translates that into data you can understand."> <!-- Twitter --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:url" content="http://oyvind.co/shapr"> <meta name="twitter:title" content="Shapr โ€“ ร˜yvind Nordbรธ"> <meta property="twitter:description" content="Introducing Shapr, a smart rubberband that tracks all your vitals. It's the personal coach that knows everything about your health, that can always tell you what to do to progress efficiently. Itโ€™s constantly monitoring your health, and translates that into data you can understand."> <!-- 280x150px @ <1MB --> <meta name="twitter:image" content="http://oyvind.co/twitter/shapr/Shapr_Twitter.jpg"> <!-- Everything else --> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shapr</title> <link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-glyphicons.css" rel="stylesheet"> <link rel="stylesheet" href="/../css/fonts/fonts.css"> <link rel="stylesheet" href="/../css/bootstrap.min.css"> <link rel="stylesheet" href="/../shapr/shapr.css"> <!-- Yes, I do know HTML/CSS. (Some JavaScript) Find my code on http://github.com/onordbo --> </head> <body class="fade-body"> <div class="container"> <!-- Back --> <div class="col-md-12 text-center back-top"><a href="/../index.html"><span class="glyphicon glyphicon-hand-left text-center" aria-hidden="true"></span><p>Back to front</p></a></div> <div class="col-md-12 body-text"> <h1 class="text-center">Shapr</h1> <h2 class="text-center">Your personal fitness coach.</h2> <h2 class="text-center">Everywhere.</h2> </div> </div> <!-- Hero image and call to action --> <div class="hero"> <div class="container"></div> </div> <div class="container"> <div class="col-md-12"> <!-- Body text --> <h3>Note:</h3> <h4>App Concept, User Interface Design, Wearable Technology</h4> <p class="body-text">This is the creative task for my Digital Media Creative admission to Hyper Island, and it is <span class="italic">currently</span> only a concept. The task was to create a digital solution/service/product that were set ten years into the future.</p> <h3>Problem:</h3> <p class="body-text">I had this problem when I started working out, five months ago. I didnโ€™t know anything about exercising right, or fitness in general. I just gambled about in the gym on the machines, assuming that if I wore myself out every time, I would just naturally progress. And in essence you can, but itโ€™s not very effective, and if you're doing it wrong, you can hurt yourself. <span class="bold">A lot.</span></p> <p class="body-text">The world is already filled with a vast amount of wearable fitness technology, wristbands, apps, dongles, etc. They do all sorts of amazing things and track all sorts of data. But what good does that data do if you donโ€™t understand it?</p> <h3>Solution:</h3> <p class="body-text">Introducing Shapr, a smart rubberband that tracks all your vitals. It's the personal coach that knows everything about your health, that can always tell you what to do to progress efficiently. Itโ€™s constantly monitoring your health, and translates that into data you can understand, so you can focus on the important parts; <span class="bold">like actually going to the gym.</span></p> </div> </div> <!-- Onboarding --> <div class="container-fluid"> <ul> <h3>User Onboarding and Setup</h3> <p class="body-text">This is what the first-time setup could look like:</p> <li><img src="img/on1.png" draggable="false"></li> <li><img src="img/on2.png" draggable="false"></li> <li><img src="img/on3.png" draggable="false"></li> </ul> </div> <!-- Workout session example --> <div class="container-fluid"> <ul> <h3>Active Workout Session</h3> <p class="body-text">This is what an active workout program could look like:</p> <li><img src="img/1.png" draggable="false"></li> <li><img src="img/2.png" draggable="false"></li> <li><img src="img/3.png" draggable="false"></li> <li><img src="img/4.png" draggable="false"></li> </ul> </div> <div class="container"> <div class="col-md-12 below"> <p class="body-text">Shapr tracks data like running speed, heart rate, oxygen saturation, calories burned etc, etc, just like everything else. But what it then does is crunch all that data into a format that anyone can <span class="bold">understand.</span></p> <p class="body-text">I donโ€™t how many push-ups I should do when I work out, but my body does! Sadly, it doesnโ€™t talk to me. Shapr aims to deliver a fully autonomous workout program, that simply tells you what to do, based on your current health. No research required.</p> </div> </div> <div class="container"> <div class="col-md-12"> <h3>Frictionless, automated calendars:</h3> <p class="body-text">Whatโ€™s really great about Shapr, is that you donโ€™t have to worry about planning your workout schedule. Itโ€™s fully automated, and if you skip a workout, Shapr will simply recalibrate what youโ€™ll do for next session.</p> </div> </div> <!-- Automated calendars --> <div class="container-fluid"> <img id="calendar" src="img/calendar.png"> </div> <div class="container"> <div class="col-md-12"> <!-- Conclusion --> <h3>Conclusion:</h3> <p class="body-text">In conclusion, the possibilities for increased life expectancy with Shapr could be amazing. Real-time lifestyle feedback paired with simple digestible information might just be the next big thing to nudge people into a more healthy lifestyle.</p> </div> </div> <!-- Buttons --> <div class="container text-center buttons"> <!-- Project --> <a href="../dated"> <div id="newProject" class="blueButton"> <p>Give me more</p> </div> </a> <!-- Back --> <div class="back"> <a href="/../index.html"> <p id="back">Back to front</p> </a> </div> </div> <!-- Scripts --> <script src="/../js/title.js"></script> <script src="/../js/ga.js"></script> <script src="/../js/project.js"></script> </body> </html>
onordbo/oyvind.co
src/shapr/index.html
HTML
mit
7,703
require 'RMagick' module FilesHelper def self.store_avatar_to_cache(file) FileUtils.mkdir_p "#{RAILS_ROOT}/public/images/avatars/" image = Magick::Image::from_blob(file.content).first white_bg = Magick::Image.new(Configuration.avatar_size, Configuration.avatar_size) { self.format = 'JPEG' self.background_color = Configuration.avatar_bg_color } white_bg.composite!(image, Magick::CenterGravity, Magick::OverCompositeOp) data = white_bg.to_blob file_name = "#{RAILS_ROOT}/public/images/avatars/#{file.id}.jpg" f = File.open(file_name, 'wb') f.write(data) f.close if (not File.stat(file_name).size?) File.unlink(file_name) end data end def self.clear_avatar_cache(file) path = "#{RAILS_ROOT}/public/images/avatars/#{file.id}.jpg" if (File.exists?(path)) File.unlink(path) end end end
kuccello/forulio
app/helpers/files_helper.rb
Ruby
mit
956
<?php /* * This file is part of the Sylius package. * * (c) Paweล‚ Jฤ™drzejewski * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace spec\Sylius\Bundle\VariationBundle\Form\Type; use PhpSpec\ObjectBehavior; use Prophecy\Argument; use Sylius\Bundle\ResourceBundle\Form\EventSubscriber\AddCodeFormSubscriber; use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormTypeInterface; use Symfony\Component\OptionsResolver\OptionsResolver; /** * @author Paweล‚ Jฤ™drzejewski <pawel@sylius.org> * @author Gonzalo Vilaseca <gvilaseca@reiss.co.uk> */ class OptionTypeSpec extends ObjectBehavior { function let() { $this->beConstructedWith('Option', array(), 'server'); } function it_is_initializable() { $this->shouldHaveType('Sylius\Bundle\VariationBundle\Form\Type\OptionType'); } function it_is_a_form_type() { $this->shouldImplement(FormTypeInterface::class); } function it_builds_form_with_proper_fields(FormBuilder $builder) { $builder ->add('name', 'text', Argument::any()) ->shouldBeCalled() ->willReturn($builder) ; $builder ->add('translations', 'a2lix_translationsForms', Argument::any()) ->shouldBeCalled() ->willReturn($builder) ; $builder ->add('values', 'collection', Argument::any()) ->shouldBeCalled() ->willReturn($builder) ; $builder ->addEventSubscriber(Argument::type(AddCodeFormSubscriber::class)) ->shouldBeCalled() ->willReturn($builder) ; $this->buildForm($builder, array()); } function it_defines_assigned_data_class_and_validation_groups(OptionsResolver $resolver) { $resolver ->setDefaults(array( 'data_class' => 'Option', 'validation_groups' => array() )) ->shouldBeCalled(); $this->configureOptions($resolver); } function it_has_valid_name() { $this->getName()->shouldReturn('sylius_server_option'); } }
pfwd/Sylius
src/Sylius/Bundle/VariationBundle/spec/Form/Type/OptionTypeSpec.php
PHP
mit
2,255
<!DOCTYPE html> <meta charset="utf-8"> <title>window.external</title> <link rel="help" href="https://html.spec.whatwg.org/multipage/obsolete.html#dom-external"> <script src="/resources/testharness.js"></script> <script src="/resources/testharnessreport.js"></script> <script> "use strict"; test(() => { assert_exists(window, "external"); }, "window.external exists"); test(() => { assert_equals(window.external.AddSearchProvider(), undefined); assert_equals(window.external.IsSearchProviderInstalled(), undefined); }, "window.external SearchProvider methods are no-ops"); </script>
Zirro/jsdom
test/web-platform-tests/to-upstream/html/obsolete/requirements-for-implementations/other-elements-attributes-and-apis/window-external.html
HTML
mit
592
// Copyright (c) 2011-2021 The Bitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_QT_OPTIONSMODEL_H #define BITCOIN_QT_OPTIONSMODEL_H #include <cstdint> #include <qt/guiconstants.h> #include <QAbstractListModel> #include <assert.h> namespace interfaces { class Node; } extern const char *DEFAULT_GUI_PROXY_HOST; static constexpr uint16_t DEFAULT_GUI_PROXY_PORT = 9050; /** * Convert configured prune target MiB to displayed GB. Round up to avoid underestimating max disk usage. */ static inline int PruneMiBtoGB(int64_t mib) { return (mib * 1024 * 1024 + GB_BYTES - 1) / GB_BYTES; } /** * Convert displayed prune target GB to configured MiB. Round down so roundtrip GB -> MiB -> GB conversion is stable. */ static inline int64_t PruneGBtoMiB(int gb) { return gb * GB_BYTES / 1024 / 1024; } /** Interface from Qt to configuration data structure for Bitcoin client. To Qt, the options are presented as a list with the different options laid out vertically. This can be changed to a tree once the settings become sufficiently complex. */ class OptionsModel : public QAbstractListModel { Q_OBJECT public: explicit OptionsModel(QObject *parent = nullptr, bool resetSettings = false); enum OptionID { StartAtStartup, // bool ShowTrayIcon, // bool MinimizeToTray, // bool MapPortUPnP, // bool MapPortNatpmp, // bool MinimizeOnClose, // bool ProxyUse, // bool ProxyIP, // QString ProxyPort, // int ProxyUseTor, // bool ProxyIPTor, // QString ProxyPortTor, // int DisplayUnit, // BitcoinUnits::Unit ThirdPartyTxUrls, // QString Language, // QString UseEmbeddedMonospacedFont, // bool CoinControlFeatures, // bool SubFeeFromAmount, // bool ThreadsScriptVerif, // int Prune, // bool PruneSize, // int DatabaseCache, // int ExternalSignerPath, // QString SpendZeroConfChange, // bool Listen, // bool Server, // bool OptionIDRowCount, }; void Init(bool resetSettings = false); void Reset(); int rowCount(const QModelIndex & parent = QModelIndex()) const override; QVariant data(const QModelIndex & index, int role = Qt::DisplayRole) const override; bool setData(const QModelIndex & index, const QVariant & value, int role = Qt::EditRole) override; /** Updates current unit in memory, settings and emits displayUnitChanged(newUnit) signal */ void setDisplayUnit(const QVariant &value); /* Explicit getters */ bool getShowTrayIcon() const { return m_show_tray_icon; } bool getMinimizeToTray() const { return fMinimizeToTray; } bool getMinimizeOnClose() const { return fMinimizeOnClose; } int getDisplayUnit() const { return nDisplayUnit; } QString getThirdPartyTxUrls() const { return strThirdPartyTxUrls; } bool getUseEmbeddedMonospacedFont() const { return m_use_embedded_monospaced_font; } bool getCoinControlFeatures() const { return fCoinControlFeatures; } bool getSubFeeFromAmount() const { return m_sub_fee_from_amount; } const QString& getOverriddenByCommandLine() { return strOverriddenByCommandLine; } /* Explicit setters */ void SetPruneEnabled(bool prune, bool force = false); void SetPruneTargetGB(int prune_target_gb, bool force = false); /* Restart flag helper */ void setRestartRequired(bool fRequired); bool isRestartRequired() const; interfaces::Node& node() const { assert(m_node); return *m_node; } void setNode(interfaces::Node& node) { assert(!m_node); m_node = &node; } private: interfaces::Node* m_node = nullptr; /* Qt-only settings */ bool m_show_tray_icon; bool fMinimizeToTray; bool fMinimizeOnClose; QString language; int nDisplayUnit; QString strThirdPartyTxUrls; bool m_use_embedded_monospaced_font; bool fCoinControlFeatures; bool m_sub_fee_from_amount; /* settings that were overridden by command-line */ QString strOverriddenByCommandLine; // Add option to list of GUI options overridden through command line/config file void addOverriddenOption(const std::string &option); // Check settings version and upgrade default values if required void checkAndMigrate(); Q_SIGNALS: void displayUnitChanged(int unit); void coinControlFeaturesChanged(bool); void showTrayIconChanged(bool); void useEmbeddedMonospacedFontChanged(bool); }; #endif // BITCOIN_QT_OPTIONSMODEL_H
mm-s/bitcoin
src/qt/optionsmodel.h
C
mit
4,915
package uk.co.automatictester.lightning.core.reporters.junit; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import uk.co.automatictester.lightning.core.enums.TestResult; import uk.co.automatictester.lightning.core.exceptions.JunitReportGenerationException; import uk.co.automatictester.lightning.core.state.tests.TestSet; import uk.co.automatictester.lightning.core.tests.LightningTest; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.*; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import java.io.StringWriter; public class JunitReportGenerator { private final Document doc; private final TestSet testSet; public JunitReportGenerator(TestSet testSet) { this.testSet = testSet; DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db; try { db = dbf.newDocumentBuilder(); } catch (ParserConfigurationException e) { throw new JunitReportGenerationException(e); } doc = db.newDocument(); doc.setXmlStandalone(true); } public String generate() { generateXmlDocument(); return transformXmlDocumentToString(); } Element getTestsuite() { Element testsuite = doc.createElement("testsuite"); String testCount = String.valueOf(testSet.size()); String failCount = String.valueOf(testSet.failCount()); String errorCount = String.valueOf(testSet.errorCount()); testsuite.setAttribute("tests", testCount); testsuite.setAttribute("failures", failCount); testsuite.setAttribute("errors", errorCount); testsuite.setAttribute("time", "0"); testsuite.setAttribute("name", "Lightning"); return testsuite; } Element getTestcase(LightningTest test) { Element testcase = doc.createElement("testcase"); testcase.setAttribute("time", "0"); String testName = test.name(); testcase.setAttribute("name", testName); TestResult testResult = test.result(); Element resultElement = null; switch (testResult) { case FAIL: resultElement = doc.createElement("failure"); break; case ERROR: resultElement = doc.createElement("error"); break; } if (resultElement != null) { setCommonFailureData(resultElement, test); testcase.appendChild(resultElement); } return testcase; } private static void setCommonFailureData(Element element, LightningTest test) { String testType = test.type(); String actualResultDescription = test.actualResultDescription(); String testExecutionReport = test.getTestExecutionReport(); element.setAttribute("type", testType); element.setAttribute("message", actualResultDescription); element.setTextContent(testExecutionReport); } private void generateXmlDocument() { Element testsuite = getTestsuite(); Node rootElement = doc.appendChild(testsuite); testSet.get().forEach(test -> { Element testcase = getTestcase(test); rootElement.appendChild(testcase); }); } private String transformXmlDocumentToString() { Transformer transformer = transformer(); DOMSource source = new DOMSource(doc); StringWriter stringWriter = new StringWriter(); try { transformer.transform(source, new StreamResult(stringWriter)); } catch (TransformerException e) { throw new JunitReportGenerationException(e); } return stringWriter.toString(); } private Transformer transformer() { Transformer transformer; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); } catch (TransformerConfigurationException e) { throw new JunitReportGenerationException(e); } transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); return transformer; } }
deliverymind/lightning
lightning-core/src/main/java/uk/co/automatictester/lightning/core/reporters/junit/JunitReportGenerator.java
Java
mit
4,514
๏ปฟusing System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Autodesk.Revit.DB; using Autodesk.Revit.DB.IFC; using Revit.IFC.Common.Utility; using Revit.IFC.Common.Enums; using Revit.IFC.Import.Enums; using Revit.IFC.Import.Geometry; using Revit.IFC.Import.Utility; namespace Revit.IFC.Import.Data { public class IFCTriangulatedFaceSet : IFCRepresentationItem { IFCCartesianPointList3D m_Coordinates = null; IList<IList<double>> m_Normals = null; bool? m_Closed = null; IList<IList<int>> m_CoordIndex = null; IList<IList<int>> m_NormalIndex = null; protected IFCTriangulatedFaceSet() { } /// <summary> /// Coordinates attribute. This is an IFCCartesianPointList3D /// </summary> public IFCCartesianPointList3D Coordinates { get { return m_Coordinates; } protected set { m_Coordinates = value; } } /// <summary> /// List of Normals from the Normals attribute /// </summary> public IList<IList<double>> Normals { get { return m_Normals; } protected set { m_Normals = value; } } /// <summary> /// Closed attribute /// </summary> public bool? Closed { get { return m_Closed; } protected set { m_Closed = value; } } /// <summary> /// List of triangle indexes (index to vertices in the Coordinates attribute) /// </summary> public IList<IList<int>> CoordIndex { get { return m_CoordIndex; } protected set { m_CoordIndex = value; } } /// <summary> /// List of Normal indexes (index to the normals in the list of normals in the Normals attribute /// </summary> public IList<IList<int>> NormalIndex { get { return m_NormalIndex; } protected set { m_NormalIndex = value; } } protected IFCTriangulatedFaceSet(IFCAnyHandle item) { Process(item); } /// <summary> /// Process IfcTriangulatedFaceSet instance /// </summary> /// <param name="ifcTriangulatedFaceSet">the handle</param> protected override void Process(IFCAnyHandle ifcTriangulatedFaceSet) { base.Process(ifcTriangulatedFaceSet); // Process the IFCCartesianPointLIst3D IFCAnyHandle coordinates = IFCImportHandleUtil.GetRequiredInstanceAttribute(ifcTriangulatedFaceSet, "Coordinates", true); if (IFCAnyHandleUtil.IsSubTypeOf(coordinates, IFCEntityType.IfcCartesianPointList3D)) { IFCCartesianPointList3D coordList = IFCCartesianPointList3D.processIFCCartesianPointList3D(coordinates); if (coordList != null) Coordinates = coordList; } IList<IList<double>> normals = IFCImportHandleUtil.GetListOfListOfDoubleAttribute(ifcTriangulatedFaceSet, "Normals"); if (normals != null) if (normals.Count > 0) Normals = normals; bool? closed = IFCAnyHandleUtil.GetBooleanAttribute(ifcTriangulatedFaceSet, "Closed"); if (closed != null) Closed = closed; IList<IList<int>> coordIndex = IFCImportHandleUtil.GetListOfListOfIntegerAttribute(ifcTriangulatedFaceSet, "CoordIndex"); if (coordIndex != null) if (coordIndex.Count > 0) CoordIndex = coordIndex; IList<IList<int>> normalIndex = IFCImportHandleUtil.GetListOfListOfIntegerAttribute(ifcTriangulatedFaceSet, "NormalIndex"); if (normalIndex != null) if (normalIndex.Count > 0) NormalIndex = normalIndex; } protected override void CreateShapeInternal(IFCImportShapeEditScope shapeEditScope, Transform lcs, Transform scaledLcs, string guid) { using (BuilderScope bs = shapeEditScope.InitializeBuilder(IFCShapeBuilderType.TessellatedShapeBuilder)) { base.CreateShapeInternal(shapeEditScope, lcs, scaledLcs, guid); TessellatedShapeBuilderScope tsBuilderScope = bs as TessellatedShapeBuilderScope; tsBuilderScope.StartCollectingFaceSet(); // Create triangle face set from CoordIndex. We do not support the Normals yet at this point foreach (List<int> triIndex in CoordIndex) { // This is a defensive check in an unlikely situation that the index is larger than the data if (triIndex[0] > Coordinates.CoordList.Count || triIndex[1] > Coordinates.CoordList.Count || triIndex[2] > Coordinates.CoordList.Count) { continue; } tsBuilderScope.StartCollectingFace(GetMaterialElementId(shapeEditScope)); IList<XYZ> loopVertices = new List<XYZ>(); IList<double> v1 = Coordinates.CoordList[triIndex[0] - 1]; IList<double> v2 = Coordinates.CoordList[triIndex[1] - 1]; IList<double> v3 = Coordinates.CoordList[triIndex[2] - 1]; loopVertices.Add(new XYZ(v1[0], v1[1], v1[2])); loopVertices.Add(new XYZ(v2[0], v2[1], v2[2])); loopVertices.Add(new XYZ(v3[0], v3[1], v3[2])); IList<XYZ> transformedVertices = new List<XYZ>(); foreach (XYZ vertex in loopVertices) { // Need to apply the project unit scaling here XYZ scaledVertex = applyProjectUnitScaleVertex(vertex); transformedVertices.Add(scaledLcs.OfPoint(scaledVertex)); } // Check triangle that is too narrow (2 vertices are within the tolerance IList<XYZ> validVertices; IFCGeometryUtil.CheckAnyDistanceVerticesWithinTolerance(Id, shapeEditScope, transformedVertices, out validVertices); // We are going to catch any exceptions if the loop is invalid. // We are going to hope that we can heal the parent object in the TessellatedShapeBuilder. bool bPotentiallyAbortFace = false; int count = validVertices.Count; if (validVertices.Count < 3) { Importer.TheLog.LogComment(Id, "Too few distinct loop vertices (" + count + "), ignoring.", false); bPotentiallyAbortFace = true; } else { if (!tsBuilderScope.AddLoopVertices(Id, validVertices)) bPotentiallyAbortFace = true; } if (bPotentiallyAbortFace) tsBuilderScope.AbortCurrentFace(); else tsBuilderScope.StopCollectingFace(); } IList<GeometryObject> createdGeometries = tsBuilderScope.CreateGeometry(guid); if (createdGeometries != null) { foreach (GeometryObject createdGeometry in createdGeometries) { shapeEditScope.AddGeometry(IFCSolidInfo.Create(Id, createdGeometry)); } } } } /// <summary> /// Scale the vertex according to the Project unit /// </summary> /// <param name="vertex">the vertex</param> /// <returns></returns> private XYZ applyProjectUnitScaleVertex(XYZ vertex) { double x = IFCUnitUtil.ScaleLength(vertex.X); double y = IFCUnitUtil.ScaleLength(vertex.Y); double z = IFCUnitUtil.ScaleLength(vertex.Z); XYZ scaledVertex = new XYZ(x, y, z); return scaledVertex; } /// <summary> /// Start processing the IfcTriangulatedFaceSet /// </summary> /// <param name="ifcTriangulatedFaceSet">the handle</param> /// <returns></returns> public static IFCTriangulatedFaceSet ProcessIFCTriangulatedFaceSet(IFCAnyHandle ifcTriangulatedFaceSet) { if (IFCAnyHandleUtil.IsNullOrHasNoValue(ifcTriangulatedFaceSet)) { Importer.TheLog.LogNullError(IFCEntityType.IfcTriangulatedFaceSet); return null; } IFCEntity triangulatedFaceSet; if (!IFCImportFile.TheFile.EntityMap.TryGetValue(ifcTriangulatedFaceSet.StepId, out triangulatedFaceSet)) triangulatedFaceSet = new IFCTriangulatedFaceSet(ifcTriangulatedFaceSet); return (triangulatedFaceSet as IFCTriangulatedFaceSet); } } }
ivanifan/RevitCustomIFCexporter
trunk/2016/Source/Revit.IFC.Import/Data/IFCTriangulatedFaceSet.cs
C#
mit
9,102
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <link rel="stylesheet" href="../../../../style.css" type="text/css" media="screen"> <link rel="stylesheet" href="../../../../print.css" type="text/css" media="print"> <link rel="stylesheet" href="../../../../prettify.css" type="text/css"> <meta content="Timespan,com.google.analytics.utils.Timespan,sixmonths,thirtyminutes,twoyears" name="keywords"> <title>com.google.analytics.utils.Timespan</title> </head> <body> <script type="text/javascript" language="javascript" src="../../../../prettify.js"></script><script type="text/javascript" language="javascript" src="../../../../asdoc.js"></script><script type="text/javascript" language="javascript" src="../../../../cookies.js"></script><script type="text/javascript" language="javascript"> <!-- asdocTitle = 'Timespan - Google Analytics Tracking For Adobe Flash v1.0.1.319'; var baseRef = '../../../../'; window.onload = configPage; --></script> <table style="display:none" id="titleTable" cellspacing="0" cellpadding="0" class="titleTable"> <tr> <td align="left" class="titleTableTitle">Google Analytics Tracking For Adobe Flash</td><td align="right" class="titleTableTopNav"><a onclick="loadClassListFrame('../../../../all-classes.html')" href="../../../../package-summary.html">All&nbsp;Packages</a>&nbsp;|&nbsp;<a onclick="loadClassListFrame('../../../../all-classes.html')" href="../../../../class-summary.html">All&nbsp;Classes</a>&nbsp;|&nbsp;<a onclick="loadClassListFrame('../../../../index-list.html')" href="../../../../all-index-A.html">Index</a>&nbsp;|&nbsp;<a href="../../../../index.html?com/google/analytics/utils/Timespan.html&amp;com/google/analytics/utils/class-list.html" id="framesLink1">Frames</a><a onclick="parent.location=document.location" href="" style="display:none" id="noFramesLink1">No&nbsp;Frames</a></td><td rowspan="3" align="right" class="titleTableLogo"><img alt="Adobe Logo" title="Adobe Logo" class="logoImage" src="../../../../images/logo.jpg"></td> </tr> <tr class="titleTableRow2"> <td align="left" id="subTitle" class="titleTableSubTitle">Class&nbsp;Timespan</td><td align="right" id="subNav" class="titleTableSubNav"><a href="#propertySummary">Properties</a></td> </tr> <tr class="titleTableRow3"> <td colspan="2">&nbsp;</td> </tr> </table> <script type="text/javascript" language="javascript"> <!-- if (!isEclipse() || window.name != ECLIPSE_FRAME_NAME) {titleBar_setSubTitle("Classย Timespan"); titleBar_setSubNav(false,true,false,false,false,false,false,false,false,false,false,false,false,false);} --></script> <div class="MainContent"> <table cellspacing="0" cellpadding="0" class="classHeaderTable"> <tr> <td class="classHeaderTableLabel">Package</td><td><a onclick="javascript:loadClassListFrame('class-list.html')" href="package-detail.html">com.google.analytics.utils</a></td> </tr> <tr> <td class="classHeaderTableLabel">Class</td><td class="classSignature">public class Timespan</td> </tr> </table> <p></p> Utils to store "period of time" in seconds <p></p> <br> <hr> </div> <a name="propertySummary"></a> <div class="summarySection"> <div class="summaryTableTitle">Public Properties</div> <table id="summaryTableProperty" class="summaryTable " cellpadding="3" cellspacing="0"> <tr> <th>&nbsp;</th><th colspan="2">Property</th><th class="summaryTableOwnerCol">Defined&nbsp;by</th> </tr> <tr class=""> <td class="summaryTablePaddingCol">&nbsp;</td><td class="summaryTableInheritanceCol">&nbsp;</td><td class="summaryTableSignatureCol"><a class="signatureLink" href="#sixmonths">sixmonths</a> : Number = 15768000<div class="summaryTableDescription">[static] Six months of time in seconds.</div> </td><td class="summaryTableOwnerCol">Timespan</td> </tr> <tr class=""> <td class="summaryTablePaddingCol">&nbsp;</td><td class="summaryTableInheritanceCol">&nbsp;</td><td class="summaryTableSignatureCol"><a class="signatureLink" href="#thirtyminutes">thirtyminutes</a> : Number = 1800<div class="summaryTableDescription">[static] Thirty minutes of time in seconds.</div> </td><td class="summaryTableOwnerCol">Timespan</td> </tr> <tr class=""> <td class="summaryTablePaddingCol">&nbsp;</td><td class="summaryTableInheritanceCol">&nbsp;</td><td class="summaryTableSignatureCol"><a class="signatureLink" href="#twoyears">twoyears</a> : Number = 63072000<div class="summaryTableDescription">[static] Two year of time in seconds note: 63072000000 is the number of milliseconds in 2 year.</div> </td><td class="summaryTableOwnerCol">Timespan</td> </tr> </table> </div> <script type="text/javascript" language="javascript"> <!-- showHideInherited(); --></script> <div class="MainContent"> <a name="propertyDetail"></a> <div class="detailSectionHeader">Property detail</div> <a name="sixmonths"></a> <table cellspacing="0" cellpadding="0" class="detailHeader"> <tr> <td class="detailHeaderName">sixmonths</td><td class="detailHeaderType">property</td> </tr> </table> <div class="detailBody"> <code>public static var sixmonths:Number = 15768000</code><p> Six months of time in seconds. </p></div> <a name="thirtyminutes"></a> <table cellspacing="0" cellpadding="0" class="detailHeader"> <tr> <td class="detailHeaderName">thirtyminutes</td><td class="detailHeaderType">property</td><td class="detailHeaderRule">&nbsp;</td> </tr> </table> <div class="detailBody"> <code>public static var thirtyminutes:Number = 1800</code><p> Thirty minutes of time in seconds. </p></div> <a name="twoyears"></a> <table cellspacing="0" cellpadding="0" class="detailHeader"> <tr> <td class="detailHeaderName">twoyears</td><td class="detailHeaderType">property</td><td class="detailHeaderRule">&nbsp;</td> </tr> </table> <div class="detailBody"> <code>public static var twoyears:Number = 63072000</code><p> Two year of time in seconds note: 63072000000 is the number of milliseconds in 2 year. 2 (year) 365 (days / year) 24 (hours / day) 60 (min / hour) 60 (sec / min) x 1000 (millisec / sec) ----------- 63072000000 (millisec) </p></div> <br> <br> <hr> <br> <p></p> <center class="copyright">gaforflash v1.0.1.319 - generated the 04 December 2008</center> </div> </body> </html> <!--gaforflash v1.0.1.319 - generated the 04 December 2008-->
darian311/VillageDashFlash
trunk/TrackingExample/libs/gaforflash-1.0.1.319/doc/com/google/analytics/utils/Timespan.html
HTML
mit
6,564
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2013 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_CHAIN_PARAMS_H #define BITCOIN_CHAIN_PARAMS_H #include "bignum.h" #include "uint256.h" #include <vector> using namespace std; #define MESSAGE_START_SIZE 4 typedef unsigned char MessageStartChars[MESSAGE_START_SIZE]; class CAddress; class CBlock; struct CDNSSeedData { string name, host; CDNSSeedData(const string &strName, const string &strHost) : name(strName), host(strHost) {} }; /** * CChainParams defines various tweakable parameters of a given instance of the * Unpay system. There are three: the main network on which people trade goods * and services, the public test network which gets reset from time to time and * a regression test mode which is intended for private networks only. It has * minimal difficulty to ensure that blocks can be found instantly. */ class CChainParams { public: enum Network { MAIN, TESTNET, REGTEST, MAX_NETWORK_TYPES }; enum Base58Type { PUBKEY_ADDRESS, SCRIPT_ADDRESS, SECRET_KEY, // BIP16 EXT_PUBLIC_KEY, // BIP32 EXT_SECRET_KEY, // BIP32 EXT_COIN_TYPE, // BIP44 MAX_BASE58_TYPES }; const uint256& HashGenesisBlock() const { return hashGenesisBlock; } const MessageStartChars& MessageStart() const { return pchMessageStart; } const vector<unsigned char>& AlertKey() const { return vAlertPubKey; } int GetDefaultPort() const { return nDefaultPort; } const CBigNum& ProofOfWorkLimit() const { return bnProofOfWorkLimit; } int SubsidyHalvingInterval() const { return nSubsidyHalvingInterval; } virtual const CBlock& GenesisBlock() const = 0; virtual bool RequireRPCPassword() const { return true; } const string& DataDir() const { return strDataDir; } virtual Network NetworkID() const = 0; const vector<CDNSSeedData>& DNSSeeds() const { return vSeeds; } const std::vector<unsigned char> &Base58Prefix(Base58Type type) const { return base58Prefixes[type]; } virtual const vector<CAddress>& FixedSeeds() const = 0; int RPCPort() const { return nRPCPort; } protected: CChainParams() {} uint256 hashGenesisBlock; MessageStartChars pchMessageStart; // Raw pub key bytes for the broadcast alert signing key. vector<unsigned char> vAlertPubKey; int nDefaultPort; int nRPCPort; CBigNum bnProofOfWorkLimit; int nSubsidyHalvingInterval; string strDataDir; vector<CDNSSeedData> vSeeds; std::vector<unsigned char> base58Prefixes[MAX_BASE58_TYPES]; }; /** * Return the currently selected parameters. This won't change after app startup * outside of the unit tests. */ const CChainParams &Params(); /** Sets the params returned by Params() to those for the given network. */ void SelectParams(CChainParams::Network network); /** * Looks for -regtest or -testnet and then calls SelectParams as appropriate. * Returns false if an invalid combination is given. */ bool SelectParamsFromCommandLine(); inline bool TestNet() { // Note: it's deliberate that this returns "false" for regression test mode. return Params().NetworkID() == CChainParams::TESTNET; } inline bool RegTest() { return Params().NetworkID() == CChainParams::REGTEST; } #endif
basicincome/unpcoin-core
src/chainparams.h
C
mit
3,483
#!/bin/bash SPEC="Grid5k" # Check Grid5k.tla for semantical meaning K=${1-"04"} L=${2-"01"} N=${3-"10"} C=${4-"04"} MODEL='k'$K'_l'$L'_n'$N'_c'$C # Performance related properties WORKERS=${5-"$(nproc --all)"} HEAP_MEM=${6-"8G"} DIRECT_MEM=${7-"8g"} FPSET_IMPL="tlc2.tool.fp.OffHeapDiskFPSet" # TLC version REV=$(git rev-parse HEAD) # measure.sh's fs path #DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # TLC's code location TLATOOLS_HOME=../../tlatools/org.lamport.tlatools/ # Trap interrupts and exit instead of continuing the for loop below trap "echo Exited!; exit;" SIGINT SIGTERM ###################################### # Generate TLC's config on-the-fly cat > $MODEL.cfg <<EOF CONSTANT K = $K CONSTANT L = $L CONSTANT N = $N CONSTANT C = $C INIT Init NEXT Next INVARIANT Inv EOF # Repeat N times to even out noise... for i in {1..3}; do # For varying worker (core) counts... for ((w=$WORKERS; w > 0;w=w/2)); do # Output/log files JFR_OUTPUT_FILE=$REV'_w'$w'_i'$i.jfr TIME_OUTPUT_FILE=$REV-$w.txt TLC_OUTPUT_FILE=$REV-$i-$w-tlc.txt /usr/bin/time --append --output=$TIME_OUTPUT_FILE \ java \ -XX:+UseParallelGC \ -Xmx$HEAP_MEM -Xms$HEAP_MEM \ -XX:MaxDirectMemorySize=$DIRECT_MEM \ -Dtlc2.tool.fp.FPSet.impl=$FPSET_IMPL \ -Dtlc2.tool.ModelChecker.BAQueue=true \ -cp $TLATOOLS_HOME/class:$TLATOOLS_HOME/lib/*:$TLATOOLS_HOME/lib/javax.mail/*:$TLATOOLS_HOME/lib/gson/* \ -DspecName=$SPEC \ -DmodelName=$MODEL \ tlc2.TLC -deadlock -checkpoint 99999 -workers $w -config $MODEL $SPEC 2>&1 | tee $TLC_OUTPUT_FILE; # newer TLC versions support "-checkpoint 0", but 99999 suffices. # cleanup left-over states/ directory to free disk space rm -rf states/ # Notify user of completion cat $TLC_OUTPUT_FILE | mail -s "Model: $MODEL Workers: $w" $(id -u -n) done done
lemmy/tlaplus
general/performance/measure.sh
Shell
mit
2,013
/* Copyright 2014-2015 Glen Joseph Fernandes (glenjofe@gmail.com) Distributed under the Boost Software License, Version 1.0. (http://www.boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP #define BOOST_ALIGN_DETAIL_ALIGNED_ALLOC_HPP #include <boost/align/detail/is_alignment.hpp> #include <boost/align/align.hpp> #include <boost/align/alignment_of.hpp> #include <boost/assert.hpp> #include <cstdlib> namespace boost { namespace alignment { inline void* aligned_alloc(std::size_t alignment, std::size_t size) BOOST_NOEXCEPT { BOOST_ASSERT(detail::is_alignment(alignment)); enum { N = alignment_of<void*>::value }; if (alignment < N) { alignment = N; } std::size_t n = size + alignment - N; void* p = std::malloc(sizeof(void*) + n); if (p) { void* r = static_cast<char*>(p) + sizeof(void*); (void)align(alignment, size, r, n); *(static_cast<void**>(r) - 1) = p; p = r; } return p; } inline void aligned_free(void* ptr) BOOST_NOEXCEPT { if (ptr) { std::free(*(static_cast<void**>(ptr) - 1)); } } } /* alignment */ } /* boost */ #endif
SingularInversions/FaceGenBaseLibrary
source/LibTpBoost/boost_1_67_0/boost/align/detail/aligned_alloc.hpp
C++
mit
1,219
// VirtualWire.cpp // // Virtual Wire implementation for Arduino // See the README file in this directory fdor documentation // See also // ASH Transceiver Software Designer's Guide of 2002.08.07 // http://www.rfm.com/products/apnotes/tr_swg05.pdf // // Changes: // 1.5 2008-05-25: fixed a bug that could prevent messages with certain // bytes sequences being received (false message start detected) // 1.6 2011-09-10: Patch from David Bath to prevent unconditional reenabling of the receiver // at end of transmission. // // Author: Mike McCauley (mikem@airspayce.com) // Copyright (C) 2008 Mike McCauley // $Id: VirtualWire.cpp,v 1.14 2013/10/05 21:34:35 mikem Exp mikem $ #if defined(ARDUINO) #if (ARDUINO < 100) #include "WProgram.h" #endif #elif defined(__MSP430G2452__) || defined(__MSP430G2553__) // LaunchPad specific #include "legacymsp430.h" #include "Energia.h" #elif defined(MCU_STM32F103RE) // Maple etc #include <string.h> #else // error #error Platform not defined #endif #include "VirtualWire.h" #include <util/crc16.h> static uint8_t vw_tx_buf[(VW_MAX_MESSAGE_LEN * 2) + VW_HEADER_LEN] = {0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x38, 0x2c}; // Number of symbols in vw_tx_buf to be sent; static uint8_t vw_tx_len = 0; // Index of the next symbol to send. Ranges from 0 to vw_tx_len static uint8_t vw_tx_index = 0; // Bit number of next bit to send static uint8_t vw_tx_bit = 0; // Sample number for the transmitter. Runs 0 to 7 during one bit interval static uint8_t vw_tx_sample = 0; // Flag to indicated the transmitter is active static volatile uint8_t vw_tx_enabled = 0; // Total number of messages sent static uint16_t vw_tx_msg_count = 0; // The digital IO pin number of the press to talk, enables the transmitter hardware static uint8_t vw_ptt_pin = 10; static uint8_t vw_ptt_inverted = 0; // The digital IO pin number of the receiver data static uint8_t vw_rx_pin = 11; static uint8_t vw_rx_inverted = 0; // The digital IO pin number of the transmitter data static uint8_t vw_tx_pin = 12; // Current receiver sample static uint8_t vw_rx_sample = 0; // Last receiver sample static uint8_t vw_rx_last_sample = 0; // PLL ramp, varies between 0 and VW_RX_RAMP_LEN-1 (159) over // VW_RX_SAMPLES_PER_BIT (8) samples per nominal bit time. // When the PLL is synchronised, bit transitions happen at about the // 0 mark. static uint8_t vw_rx_pll_ramp = 0; // This is the integrate and dump integral. If there are <5 0 samples in the PLL cycle // the bit is declared a 0, else a 1 static uint8_t vw_rx_integrator = 0; // Flag indictate if we have seen the start symbol of a new message and are // in the processes of reading and decoding it static uint8_t vw_rx_active = 0; // Flag to indicate that a new message is available static volatile uint8_t vw_rx_done = 0; // Flag to indicate the receiver PLL is to run static uint8_t vw_rx_enabled = 0; // Last 12 bits received, so we can look for the start symbol static uint16_t vw_rx_bits = 0; // How many bits of message we have received. Ranges from 0 to 12 static uint8_t vw_rx_bit_count = 0; // The incoming message buffer static uint8_t vw_rx_buf[VW_MAX_MESSAGE_LEN]; // The incoming message expected length static uint8_t vw_rx_count = 0; // The incoming message buffer length received so far static volatile uint8_t vw_rx_len = 0; // Number of bad messages received and dropped due to bad lengths static uint8_t vw_rx_bad = 0; // Number of good messages received static uint8_t vw_rx_good = 0; // 4 bit to 6 bit symbol converter table // Used to convert the high and low nybbles of the transmitted data // into 6 bit symbols for transmission. Each 6-bit symbol has 3 1s and 3 0s // with at most 3 consecutive identical bits static uint8_t symbols[] = { 0xd, 0xe, 0x13, 0x15, 0x16, 0x19, 0x1a, 0x1c, 0x23, 0x25, 0x26, 0x29, 0x2a, 0x2c, 0x32, 0x34 }; // Cant really do this as a real C++ class, since we need to have // an ISR extern "C" { // Compute CRC over count bytes. // This should only be ever called at user level, not interrupt level uint16_t vw_crc(uint8_t *ptr, uint8_t count) { uint16_t crc = 0xffff; while (count-- > 0) crc = _crc_ccitt_update(crc, *ptr++); return crc; } // Convert a 6 bit encoded symbol into its 4 bit decoded equivalent uint8_t vw_symbol_6to4(uint8_t symbol) { uint8_t i; // Linear search :-( Could have a 64 byte reverse lookup table? for (i = 0; i < 16; i++) if (symbol == symbols[i]) return i; return 0; // Not found } // Set the output pin number for transmitter data void vw_set_tx_pin(uint8_t pin) { vw_tx_pin = pin; } // Set the pin number for input receiver data void vw_set_rx_pin(uint8_t pin) { vw_rx_pin = pin; } // Set the rx pin inverted void vw_set_rx_inverted(uint8_t inverted) { vw_rx_inverted = inverted; } // Set the output pin number for transmitter PTT enable void vw_set_ptt_pin(uint8_t pin) { vw_ptt_pin = pin; } // Set the ptt pin inverted (low to transmit) void vw_set_ptt_inverted(uint8_t inverted) { vw_ptt_inverted = inverted; } // Called 8 times per bit period // Phase locked loop tries to synchronise with the transmitter so that bit // transitions occur at about the time vw_rx_pll_ramp is 0; // Then the average is computed over each bit period to deduce the bit value void vw_pll() { // Integrate each sample if (vw_rx_sample) vw_rx_integrator++; if (vw_rx_sample != vw_rx_last_sample) { // Transition, advance if ramp > 80, retard if < 80 vw_rx_pll_ramp += ((vw_rx_pll_ramp < VW_RAMP_TRANSITION) ? VW_RAMP_INC_RETARD : VW_RAMP_INC_ADVANCE); vw_rx_last_sample = vw_rx_sample; } else { // No transition // Advance ramp by standard 20 (== 160/8 samples) vw_rx_pll_ramp += VW_RAMP_INC; } if (vw_rx_pll_ramp >= VW_RX_RAMP_LEN) { // Add this to the 12th bit of vw_rx_bits, LSB first // The last 12 bits are kept vw_rx_bits >>= 1; // Check the integrator to see how many samples in this cycle were high. // If < 5 out of 8, then its declared a 0 bit, else a 1; if (vw_rx_integrator >= 5) vw_rx_bits |= 0x800; vw_rx_pll_ramp -= VW_RX_RAMP_LEN; vw_rx_integrator = 0; // Clear the integral for the next cycle if (vw_rx_active) { // We have the start symbol and now we are collecting message bits, // 6 per symbol, each which has to be decoded to 4 bits if (++vw_rx_bit_count >= 12) { // Have 12 bits of encoded message == 1 byte encoded // Decode as 2 lots of 6 bits into 2 lots of 4 bits // The 6 lsbits are the high nybble uint8_t this_byte = (vw_symbol_6to4(vw_rx_bits & 0x3f)) << 4 | vw_symbol_6to4(vw_rx_bits >> 6); // The first decoded byte is the byte count of the following message // the count includes the byte count and the 2 trailing FCS bytes // REVISIT: may also include the ACK flag at 0x40 if (vw_rx_len == 0) { // The first byte is the byte count // Check it for sensibility. It cant be less than 4, since it // includes the bytes count itself and the 2 byte FCS vw_rx_count = this_byte; if (vw_rx_count < 4 || vw_rx_count > VW_MAX_MESSAGE_LEN) { // Stupid message length, drop the whole thing vw_rx_active = false; vw_rx_bad++; return; } } vw_rx_buf[vw_rx_len++] = this_byte; if (vw_rx_len >= vw_rx_count) { // Got all the bytes now vw_rx_active = false; vw_rx_good++; vw_rx_done = true; // Better come get it before the next one starts } vw_rx_bit_count = 0; } } // Not in a message, see if we have a start symbol else if (vw_rx_bits == 0xb38) { // Have start symbol, start collecting message vw_rx_active = true; vw_rx_bit_count = 0; vw_rx_len = 0; vw_rx_done = false; // Too bad if you missed the last message } } } #if defined(__arm__) && defined(CORE_TEENSY) // This allows the AVR interrupt code below to be run from an // IntervalTimer object. It must be above vw_setup(), so the // the TIMER1_COMPA_vect function name is defined. #ifdef SIGNAL #undef SIGNAL #endif #define SIGNAL(f) void f(void) #ifdef TIMER1_COMPA_vect #undef TIMER1_COMPA_vect #endif void TIMER1_COMPA_vect(void); #endif // Speed is in bits per sec RF rate #if defined(__MSP430G2452__) || defined(__MSP430G2553__) // LaunchPad specific void vw_setup(uint16_t speed) { // Calculate the counter overflow count based on the required bit speed // and CPU clock rate uint16_t ocr1a = (F_CPU / 8UL) / speed; // This code is for Energia/MSP430 TA0CCR0 = ocr1a; // Ticks for 62,5 us TA0CTL = TASSEL_2 + MC_1; // SMCLK, up mode TA0CCTL0 |= CCIE; // CCR0 interrupt enabled // Set up digital IO pins pinMode(vw_tx_pin, OUTPUT); pinMode(vw_rx_pin, INPUT); pinMode(vw_ptt_pin, OUTPUT); digitalWrite(vw_ptt_pin, vw_ptt_inverted); } #elif defined (ARDUINO) // Arduino specific // Common function for setting timer ticks @ prescaler values for speed // Returns prescaler index into {0, 1, 8, 64, 256, 1024} array // and sets nticks to compare-match value if lower than max_ticks // returns 0 & nticks = 0 on fault static uint8_t _timer_calc(uint16_t speed, uint16_t max_ticks, uint16_t *nticks) { // Clock divider (prescaler) values - 0/3333: error flag uint16_t prescalers[] = {0, 1, 8, 64, 256, 1024, 3333}; uint8_t prescaler=0; // index into array & return bit value unsigned long ulticks; // calculate by ntick overflow // Div-by-zero protection if (speed == 0) { // signal fault *nticks = 0; return 0; } // test increasing prescaler (divisor), decreasing ulticks until no overflow for (prescaler=1; prescaler < 7; prescaler += 1) { // Amount of time per CPU clock tick (in seconds) float clock_time = (1.0 / (float(F_CPU) / float(prescalers[prescaler]))); // Fraction of second needed to xmit one bit float bit_time = ((1.0 / float(speed)) / 8.0); // number of prescaled ticks needed to handle bit time @ speed ulticks = long(bit_time / clock_time); // Test if ulticks fits in nticks bitwidth (with 1-tick safety margin) if ((ulticks > 1) && (ulticks < max_ticks)) { break; // found prescaler } // Won't fit, check with next prescaler value } // Check for error if ((prescaler == 6) || (ulticks < 2) || (ulticks > max_ticks)) { // signal fault *nticks = 0; return 0; } *nticks = ulticks; return prescaler; } void vw_setup(uint16_t speed) { uint16_t nticks; // number of prescaled ticks needed uint8_t prescaler; // Bit values for CS0[2:0] #ifdef __AVR_ATtiny85__ // figure out prescaler value and counter match value prescaler = _timer_calc(speed, (uint8_t)-1, &nticks); if (!prescaler) { return; // fault } TCCR0A = 0; TCCR0A = _BV(WGM01); // Turn on CTC mode / Output Compare pins disconnected // convert prescaler index to TCCRnB prescaler bits CS00, CS01, CS02 TCCR0B = 0; TCCR0B = prescaler; // set CS00, CS01, CS02 (other bits not needed) // Number of ticks to count before firing interrupt OCR0A = uint8_t(nticks); // Set mask to fire interrupt when OCF0A bit is set in TIFR0 TIMSK |= _BV(OCIE0A); #elif defined(__arm__) && defined(CORE_TEENSY) // on Teensy 3.0 (32 bit ARM), use an interval timer IntervalTimer *t = new IntervalTimer(); t->begin(TIMER1_COMPA_vect, 125000.0 / (float)(speed)); #else // ARDUINO // This is the path for most Arduinos // figure out prescaler value and counter match value prescaler = _timer_calc(speed, (uint16_t)-1, &nticks); if (!prescaler) { return; // fault } TCCR1A = 0; // Output Compare pins disconnected TCCR1B = _BV(WGM12); // Turn on CTC mode // convert prescaler index to TCCRnB prescaler bits CS10, CS11, CS12 TCCR1B |= prescaler; // Caution: special procedures for setting 16 bit regs // is handled by the compiler OCR1A = nticks; // Enable interrupt #ifdef TIMSK1 // atmega168 TIMSK1 |= _BV(OCIE1A); #else // others TIMSK |= _BV(OCIE1A); #endif // TIMSK1 #endif // __AVR_ATtiny85__ // Set up digital IO pins pinMode(vw_tx_pin, OUTPUT); pinMode(vw_rx_pin, INPUT); pinMode(vw_ptt_pin, OUTPUT); digitalWrite(vw_ptt_pin, vw_ptt_inverted); } #elif defined(MCU_STM32F103RE) // Maple etc HardwareTimer timer(MAPLE_TIMER); void vw_setup(uint16_t speed) { // Set up digital IO pins pinMode(vw_tx_pin, OUTPUT); pinMode(vw_rx_pin, INPUT); pinMode(vw_ptt_pin, OUTPUT); digitalWrite(vw_ptt_pin, vw_ptt_inverted); // Pause the timer while we're configuring it timer.pause(); timer.setPeriod((1000000/8)/speed); // Set up an interrupt on channel 1 timer.setChannel1Mode(TIMER_OUTPUT_COMPARE); timer.setCompare(TIMER_CH1, 1); // Interrupt 1 count after each update void vw_Int_Handler(); // defined below timer.attachCompare1Interrupt(vw_Int_Handler); // Refresh the timer's count, prescale, and overflow timer.refresh(); // Start the timer counting timer.resume(); } #endif // Start the transmitter, call when the tx buffer is ready to go and vw_tx_len is // set to the total number of symbols to send void vw_tx_start() { vw_tx_index = 0; vw_tx_bit = 0; vw_tx_sample = 0; // Enable the transmitter hardware digitalWrite(vw_ptt_pin, true ^ vw_ptt_inverted); // Next tick interrupt will send the first bit vw_tx_enabled = true; } // Stop the transmitter, call when all bits are sent void vw_tx_stop() { // Disable the transmitter hardware digitalWrite(vw_ptt_pin, false ^ vw_ptt_inverted); digitalWrite(vw_tx_pin, false); // No more ticks for the transmitter vw_tx_enabled = false; } // Enable the receiver. When a message becomes available, vw_rx_done flag // is set, and vw_wait_rx() will return. void vw_rx_start() { if (!vw_rx_enabled) { vw_rx_enabled = true; vw_rx_active = false; // Never restart a partial message } } // Disable the receiver void vw_rx_stop() { vw_rx_enabled = false; } // Return true if the transmitter is active uint8_t vw_tx_active() { return vw_tx_enabled; } // Wait for the transmitter to become available // Busy-wait loop until the ISR says the message has been sent void vw_wait_tx() { while (vw_tx_enabled) ; } // Wait for the receiver to get a message // Busy-wait loop until the ISR says a message is available // can then call vw_get_message() void vw_wait_rx() { while (!vw_rx_done) ; } // Wait at most max milliseconds for the receiver to receive a message // Return the truth of whether there is a message uint8_t vw_wait_rx_max(unsigned long milliseconds) { unsigned long start = millis(); while (!vw_rx_done && ((millis() - start) < milliseconds)) ; return vw_rx_done; } // Wait until transmitter is available and encode and queue the message // into vw_tx_buf // The message is raw bytes, with no packet structure imposed // It is transmitted preceded a byte count and followed by 2 FCS bytes uint8_t vw_send(uint8_t* buf, uint8_t len) { uint8_t i; uint8_t index = 0; uint16_t crc = 0xffff; uint8_t *p = vw_tx_buf + VW_HEADER_LEN; // start of the message area uint8_t count = len + 3; // Added byte count and FCS to get total number of bytes if (len > VW_MAX_PAYLOAD) return false; // Wait for transmitter to become available vw_wait_tx(); // Encode the message length crc = _crc_ccitt_update(crc, count); p[index++] = symbols[count >> 4]; p[index++] = symbols[count & 0xf]; // Encode the message into 6 bit symbols. Each byte is converted into // 2 6-bit symbols, high nybble first, low nybble second for (i = 0; i < len; i++) { crc = _crc_ccitt_update(crc, buf[i]); p[index++] = symbols[buf[i] >> 4]; p[index++] = symbols[buf[i] & 0xf]; } // Append the fcs, 16 bits before encoding (4 6-bit symbols after encoding) // Caution: VW expects the _ones_complement_ of the CCITT CRC-16 as the FCS // VW sends FCS as low byte then hi byte crc = ~crc; p[index++] = symbols[(crc >> 4) & 0xf]; p[index++] = symbols[crc & 0xf]; p[index++] = symbols[(crc >> 12) & 0xf]; p[index++] = symbols[(crc >> 8) & 0xf]; // Total number of 6-bit symbols to send vw_tx_len = index + VW_HEADER_LEN; // Start the low level interrupt handler sending symbols vw_tx_start(); return true; } // Return true if there is a message available uint8_t vw_have_message() { return vw_rx_done; } // Get the last message received (without byte count or FCS) // Copy at most *len bytes, set *len to the actual number copied // Return true if there is a message and the FCS is OK uint8_t vw_get_message(uint8_t* buf, uint8_t* len) { uint8_t rxlen; // Message available? if (!vw_rx_done) return false; // Wait until vw_rx_done is set before reading vw_rx_len // then remove bytecount and FCS rxlen = vw_rx_len - 3; // Copy message (good or bad) if (*len > rxlen) *len = rxlen; memcpy(buf, vw_rx_buf + 1, *len); vw_rx_done = false; // OK, got that message thanks // Check the FCS, return goodness return (vw_crc(vw_rx_buf, vw_rx_len) == 0xf0b8); // FCS OK? } uint8_t vw_get_rx_good() { return vw_rx_good; } uint8_t vw_get_rx_bad() { return vw_rx_bad; } // This is the interrupt service routine called when timer1 overflows // Its job is to output the next bit from the transmitter (every 8 calls) // and to call the PLL code if the receiver is enabled //ISR(SIG_OUTPUT_COMPARE1A) #if defined (ARDUINO) // Arduino specific #undef TIMER_VECTOR #ifdef __AVR_ATtiny85__ #define TIMER_VECTOR TIM0_COMPA_vect #elif defined(__AVR_ATtiny84__) || defined(__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) // Why can't Atmel make consistent? #define TIMER_VECTOR TIM1_COMPA_vect #else // Assume Arduino Uno (328p or similar) #define TIMER_VECTOR TIMER1_COMPA_vect #endif // __AVR_ATtiny85__ ISR(TIMER_VECTOR) { if (vw_rx_enabled && !vw_tx_enabled) vw_rx_sample = digitalRead(vw_rx_pin) ^ vw_rx_inverted; // Do transmitter stuff first to reduce transmitter bit jitter due // to variable receiver processing if (vw_tx_enabled && vw_tx_sample++ == 0) { // Send next bit // Symbols are sent LSB first // Finished sending the whole message? (after waiting one bit period // since the last bit) if (vw_tx_index >= vw_tx_len) { vw_tx_stop(); vw_tx_msg_count++; } else { digitalWrite(vw_tx_pin, vw_tx_buf[vw_tx_index] & (1 << vw_tx_bit++)); if (vw_tx_bit >= 6) { vw_tx_bit = 0; vw_tx_index++; } } } if (vw_tx_sample > 7) vw_tx_sample = 0; if (vw_rx_enabled && !vw_tx_enabled) vw_pll(); } // LaunchPad or Maple: #elif defined(__MSP430G2452__) || defined(__MSP430G2553__) || defined(MCU_STM32F103RE) void vw_Int_Handler() { if (vw_rx_enabled && !vw_tx_enabled) vw_rx_sample = digitalRead(vw_rx_pin) ^ vw_rx_inverted; // Do transmitter stuff first to reduce transmitter bit jitter due // to variable receiver processing if (vw_tx_enabled && vw_tx_sample++ == 0) { // Send next bit // Symbols are sent LSB first // Finished sending the whole message? (after waiting one bit period // since the last bit) if (vw_tx_index >= vw_tx_len) { vw_tx_stop(); vw_tx_msg_count++; } else { digitalWrite(vw_tx_pin, vw_tx_buf[vw_tx_index] & (1 << vw_tx_bit++)); if (vw_tx_bit >= 6) { vw_tx_bit = 0; vw_tx_index++; } } } if (vw_tx_sample > 7) vw_tx_sample = 0; if (vw_rx_enabled && !vw_tx_enabled) vw_pll(); } #if defined(__MSP430G2452__) || defined(__MSP430G2553__) interrupt(TIMER0_A0_VECTOR) Timer_A_int(void) { vw_Int_Handler(); }; #endif #endif }
linhartr22/433_MHz_Wireless_TX-RX_Demo
libraries/VirtualWire/VirtualWire.cpp
C++
mit
20,068
// Copyright 2013-2015, The Gtk-rs Project Developers. // See the COPYRIGHT file at the top-level directory of this distribution. // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! GtkPlacesSidebar โ€” Sidebar that displays frequently-used places in the file system use ffi; use FFIWidget; use cast::GTK_PLACES_SIDEBAR; use glib::{to_bool, to_gboolean}; struct_Widget!(PlacesSidebar); impl PlacesSidebar { pub fn new() -> Option<PlacesSidebar> { let tmp_pointer = unsafe { ffi::gtk_places_sidebar_new() }; check_pointer!(tmp_pointer, PlacesSidebar) } pub fn set_open_flags(&self, flags: ::PlacesOpenFlags) { unsafe { ffi::gtk_places_sidebar_set_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget()), flags) } } pub fn get_open_flags(&self) -> ::PlacesOpenFlags { unsafe { ffi::gtk_places_sidebar_get_open_flags(GTK_PLACES_SIDEBAR(self.unwrap_widget())) } } pub fn set_show_desktop(&self, show_desktop: bool) { unsafe { ffi::gtk_places_sidebar_set_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_desktop)) } } pub fn get_show_desktop(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_desktop(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } pub fn set_show_connect_to_server(&self, show_connect_to_server: bool) { unsafe { ffi::gtk_places_sidebar_set_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_connect_to_server)) } } pub fn get_show_connect_to_server(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_connect_to_server(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } #[cfg(gtk_3_12)] pub fn set_local_only(&self, local_only: bool) { unsafe { ffi::gtk_places_sidebar_set_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(local_only)) } } #[cfg(gtk_3_12)] pub fn get_local_only(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_local_only(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } #[cfg(gtk_3_14)] pub fn set_show_enter_location(&self, show_enter_location: bool) { unsafe { ffi::gtk_places_sidebar_set_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()), to_gboolean(show_enter_location)) } } #[cfg(gtk_3_14)] pub fn get_show_enter_location(&self) -> bool { unsafe { to_bool(ffi::gtk_places_sidebar_get_show_enter_location(GTK_PLACES_SIDEBAR(self.unwrap_widget()))) } } } impl_drop!(PlacesSidebar); impl_TraitWidget!(PlacesSidebar); impl ::ContainerTrait for PlacesSidebar {} impl ::BinTrait for PlacesSidebar {} impl ::ScrolledWindowTrait for PlacesSidebar {}
LordSentox/gtk
src/widgets/places_sidebar.rs
Rust
mit
2,781
<?php /** * This file is automatically @generated by {@link BuildMetadataPHPFromXml}. * Please don't modify it directly. */ return array ( 'generalDesc' => array ( 'NationalNumberPattern' => '[268]\\d{8}', 'PossibleNumberPattern' => '\\d{9}', ), 'fixedLine' => array ( 'NationalNumberPattern' => '2696[0-4]\\d{4}', 'PossibleNumberPattern' => '\\d{9}', 'ExampleNumber' => '269601234', ), 'mobile' => array ( 'NationalNumberPattern' => '639\\d{6}', 'PossibleNumberPattern' => '\\d{9}', 'ExampleNumber' => '639123456', ), 'tollFree' => array ( 'NationalNumberPattern' => '80\\d{7}', 'PossibleNumberPattern' => '\\d{9}', 'ExampleNumber' => '801234567', ), 'premiumRate' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'sharedCost' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'personalNumber' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'voip' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'pager' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'uan' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'emergency' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'voicemail' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'shortCode' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'standardRate' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'carrierSpecific' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'noInternationalDialling' => array ( 'NationalNumberPattern' => 'NA', 'PossibleNumberPattern' => 'NA', ), 'id' => 'YT', 'countryCode' => 262, 'internationalPrefix' => '00', 'nationalPrefix' => '0', 'nationalPrefixForParsing' => '0', 'sameMobileAndFixedLinePattern' => false, 'numberFormat' => array ( ), 'intlNumberFormat' => array ( ), 'mainCountryForCode' => false, 'leadingDigits' => '269|63', 'leadingZeroPossible' => false, 'mobileNumberPortableRegion' => false, ); /* EOF */
phpManufaktur/kfContact
Library/libphonenumber/src/libphonenumber/data/PhoneNumberMetadata_YT.php
PHP
mit
2,437
import {CYCLE_STATES, PRACTICE, REFLECTION, COMPLETE} from 'src/common/models/cycle' import {userCan} from 'src/common/util' import getUser from 'src/server/actions/getUser' import assertUserIsMember from 'src/server/actions/assertUserIsMember' import createNextCycleForChapter from 'src/server/actions/createNextCycleForChapter' import {Cycle, getCyclesInStateForChapter, getLatestCycleForChapter} from 'src/server/services/dataService' import { LGCLIUsageError, LGNotAuthorizedError, LGForbiddenError, LGBadRequestError, } from 'src/server/util/error' const subcommands = { async init(args, {user}) { const mergedUser = await getUser(user.id) const currentCycle = await getLatestCycleForChapter(mergedUser.chapterId) if (currentCycle.state !== REFLECTION && currentCycle.state !== COMPLETE) { throw new LGBadRequestError('Failed to initialize a new cycle because the current cycle is still in progress.') } await _createCycle(mergedUser) return { text: '๐Ÿ”ƒ Initializing Cycle ... stand by.' } }, async launch(args, {user}) { await _changeCycleState(user, PRACTICE) return { text: '๐Ÿš€ Initiating Launch ... stand by.', } }, async reflect(args, {user}) { await _changeCycleState(user, REFLECTION) return { text: '๐Ÿค” Initiating Reflection... stand by.', } }, } export async function invoke(args, options) { if (args._.length >= 1) { const subcommand = args._[0] return await subcommands[subcommand](args.$[subcommand], options) } throw new LGCLIUsageError() } async function _createCycle(user) { if (!userCan(user, 'createCycle')) { throw new LGNotAuthorizedError() } const member = await assertUserIsMember(user.id) return await createNextCycleForChapter(member.chapterId) } async function _changeCycleState(user, newState) { const newStateIndex = CYCLE_STATES.indexOf(newState) if (!userCan(user, 'updateCycle')) { throw new LGNotAuthorizedError() } const member = await assertUserIsMember(user.id) if (newStateIndex === -1) { throw new LGBadRequestError(`Invalid cycle state ${newState}`) } if (newStateIndex === 0) { throw new LGForbiddenError(`You cannot change the cycle state back to ${newState}`) } const validOriginState = CYCLE_STATES[newStateIndex - 1] const cycles = await getCyclesInStateForChapter(member.chapterId, validOriginState) if (cycles.length === 0) { throw new LGForbiddenError(`No cycles for the chapter in ${validOriginState} state`) } return Cycle.get(cycles[0].id).updateWithTimestamp({state: newState}) }
LearnersGuild/echo
src/server/cliCommand/commands/cycle.js
JavaScript
mit
2,624
/***************************************************************************** ** Copyright (C) 1998-2001 Ljubomir Milanovic & Horst Wagner ** This file is part of the g2 library ** ** This library is free software; you can redistribute it and/or ** modify it under the terms of the GNU Lesser General Public ** License as published by the Free Software Foundation; either ** version 2.1 of the License, or (at your option) any later version. ** ** This library is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public ** License along with this library; if not, write to the Free Software ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ******************************************************************************/ #ifndef _G2_X11_H #define _G2_X11_H #if defined(__cplusplus) extern "C" { #endif int g2_open_X11(int width, int height); int g2_open_X11X(int width, int height, int x, int y, char *window_name, char *icon_name, char *icon_data, int icon_width, int icon_height); #if defined(__cplusplus) } /* end extern "C" */ #endif #endif /* _G2_X11_H */
lauringlab/CodonShuffle
lib/ViennaRNA-2.1.9/RNAforester/g2-0.70/src/X11/g2_X11.h
C
mit
1,375
//------------------------------------------------------------------------------------------------------- // VST Plug-Ins SDK // Version 2.4 $Date: 2006/01/12 09:05:31 $ // // Category : VST 2.x Classes // Filename : audioeffect.h // Created by : Steinberg Media Technologies // Description : Class AudioEffect (VST 1.0) // // ยฉ 2006, Steinberg Media Technologies, All Rights Reserved //------------------------------------------------------------------------------------------------------- #ifndef __audioeffect__ #define __audioeffect__ #include "pluginterfaces/vst2.x/aeffect.h" // "c" interface class AEffEditor; //------------------------------------------------------------------------------------------------------- /** VST Effect Base Class (VST 1.0). */ //------------------------------------------------------------------------------------------------------- class AudioEffect { public: //------------------------------------------------------------------------------------------------------- AudioEffect (audioMasterCallback audioMaster, VstInt32 numPrograms, VstInt32 numParams); ///< Create an \e AudioEffect object virtual ~AudioEffect (); ///< Destroy an \e AudioEffect object virtual VstIntPtr dispatcher (VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt); ///< Opcodes dispatcher //------------------------------------------------------------------------------------------------------- /// \name State Transitions //------------------------------------------------------------------------------------------------------- //@{ virtual void open () {} ///< Called when plug-in is initialized virtual void close () {} ///< Called when plug-in will be released virtual void suspend () {} ///< Called when plug-in is switched to off virtual void resume () {} ///< Called when plug-in is switched to on //@} //------------------------------------------------------------------------------------------------------- /// \name Processing //------------------------------------------------------------------------------------------------------- //@{ virtual void setSampleRate (float sampleRate) { this->sampleRate = sampleRate; } ///< Called when the sample rate changes (always in a suspend state) virtual void setBlockSize (VstInt32 blockSize) { this->blockSize = blockSize; } ///< Called when the Maximun block size changes (always in a suspend state). Note that the sampleFrames in Process Calls could be smaller than this block size, but NOT bigger. virtual void processReplacing (float** inputs, float** outputs, VstInt32 sampleFrames) = 0; ///< Process 32 bit (single precision) floats (always in a resume state) #if VST_2_4_EXTENSIONS virtual void processDoubleReplacing (double** inputs, double** outputs, VstInt32 sampleFrames) {} ///< Process 64 bit (double precision) floats (always in a resume state) \sa processReplacing #endif // VST_2_4_EXTENSIONS //@} //------------------------------------------------------------------------------------------------------- /// \name Parameters //------------------------------------------------------------------------------------------------------- //@{ virtual void setParameter (VstInt32 index, float value) {} ///< Called when a parameter changed virtual float getParameter (VstInt32 index) { return 0; } ///< Return the value of the parameter with \e index virtual void setParameterAutomated (VstInt32 index, float value);///< Called after a control has changed in the editor and when the associated parameter should be automated //@} //------------------------------------------------------------------------------------------------------- /// \name Programs and Persistence //------------------------------------------------------------------------------------------------------- //@{ virtual VstInt32 getProgram () { return curProgram; } ///< Return the index to the current program virtual void setProgram (VstInt32 program) { curProgram = program; } ///< Set the current program to \e program virtual void setProgramName (char* name) {} ///< Stuff the name field of the current program with \e name. Limited to #kVstMaxProgNameLen. virtual void getProgramName (char* name) { *name = 0; } ///< Stuff \e name with the name of the current program. Limited to #kVstMaxProgNameLen. virtual void getParameterLabel (VstInt32 index, char* label) { *label = 0; } ///< Stuff \e label with the units in which parameter \e index is displayed (i.e. "sec", "dB", "type", etc...). Limited to #kVstMaxParamStrLen. virtual void getParameterDisplay (VstInt32 index, char* text) { *text = 0; } ///< Stuff \e text with a string representation ("0.5", "-3", "PLATE", etc...) of the value of parameter \e index. Limited to #kVstMaxParamStrLen. virtual void getParameterName (VstInt32 index, char* text) { *text = 0; } ///< Stuff \e text with the name ("Time", "Gain", "RoomType", etc...) of parameter \e index. Limited to #kVstMaxParamStrLen. virtual VstInt32 getChunk (void** data, bool isPreset = false) { return 0; } ///< Host stores plug-in state. Returns the size in bytes of the chunk (plug-in allocates the data array) virtual VstInt32 setChunk (void* data, VstInt32 byteSize, bool isPreset = false) { return 0; } ///< Host restores plug-in state //@} //------------------------------------------------------------------------------------------------------- /// \name Internal Setup //------------------------------------------------------------------------------------------------------- //@{ virtual void setUniqueID (VstInt32 iD) { cEffect.uniqueID = iD; } ///< Must be called to set the plug-ins unique ID! virtual void setNumInputs (VstInt32 inputs) { cEffect.numInputs = inputs; } ///< Set the number of inputs the plug-in will handle. For a plug-in which could change its IO configuration, this number is the maximun available inputs. virtual void setNumOutputs (VstInt32 outputs) { cEffect.numOutputs = outputs; } ///< Set the number of outputs the plug-in will handle. For a plug-in which could change its IO configuration, this number is the maximun available ouputs. virtual void canProcessReplacing (bool state = true); ///< Tells that processReplacing() could be used. Mandatory in VST 2.4! #if VST_2_4_EXTENSIONS virtual void canDoubleReplacing (bool state = true); ///< Tells that processDoubleReplacing() is implemented. #endif // VST_2_4_EXTENSIONS virtual void programsAreChunks (bool state = true); ///< Program data is handled in formatless chunks (using getChunk-setChunks) virtual void setInitialDelay (VstInt32 delay); ///< Use to report the plug-in's latency (Group Delay) //@} //------------------------------------------------------------------------------------------------------- /// \name Editor //------------------------------------------------------------------------------------------------------- //@{ void setEditor (AEffEditor* editor); ///< Should be called if you want to define your own editor virtual AEffEditor* getEditor () { return editor; } ///< Returns the attached editor //@} //------------------------------------------------------------------------------------------------------- /// \name Inquiry //------------------------------------------------------------------------------------------------------- //@{ virtual AEffect* getAeffect () { return &cEffect; } ///< Returns the #AEffect structure virtual float getSampleRate () { return sampleRate; } ///< Returns the current sample rate virtual VstInt32 getBlockSize () { return blockSize; } ///< Returns the current Maximum block size //@} //------------------------------------------------------------------------------------------------------- /// \name Host Communication //------------------------------------------------------------------------------------------------------- //@{ virtual VstInt32 getMasterVersion (); ///< Returns the Host's version (for example 2400 for VST 2.4) virtual VstInt32 getCurrentUniqueId (); ///< Returns current unique identifier when loading shell plug-ins virtual void masterIdle (); ///< Give idle time to Host application virtual bool isInputConnected (VstInt32 input); ///< Returns the input's connection state virtual bool isOutputConnected (VstInt32 output); ///< Returns the output's connection state //@} //------------------------------------------------------------------------------------------------------- /// \name Tools (helpers) //------------------------------------------------------------------------------------------------------- //@{ virtual void dB2string (float value, char* text, VstInt32 maxLen); ///< Stuffs \e text with an amplitude on the [0.0, 1.0] scale converted to its value in decibels. virtual void Hz2string (float samples, char* text, VstInt32 maxLen); ///< Stuffs \e text with the frequency in Hertz that has a period of \e samples. virtual void ms2string (float samples, char* text, VstInt32 maxLen); ///< Stuffs \e text with the duration in milliseconds of \e samples frames. virtual void float2string (float value, char* text, VstInt32 maxLen); ///< Stuffs \e text with a string representation on the floating point \e value. virtual void int2string (VstInt32 value, char* text, VstInt32 maxLen); ///< Stuffs \e text with a string representation on the integer \e value. //@} //------------------------------------------------------------------------------------------------------- // Deprecated methods //------------------------------------------------------------------------------------------------------- /// @cond ignore virtual void DECLARE_VST_DEPRECATED (process) (float** inputs, float** outputs, VstInt32 sampleFrames) {} virtual float DECLARE_VST_DEPRECATED (getVu) () { return 0; } virtual void DECLARE_VST_DEPRECATED (hasVu) (bool state = true); virtual void DECLARE_VST_DEPRECATED (hasClip) (bool state = true); virtual void DECLARE_VST_DEPRECATED (canMono) (bool state = true); virtual void DECLARE_VST_DEPRECATED (setRealtimeQualities) (VstInt32 qualities); virtual void DECLARE_VST_DEPRECATED (setOfflineQualities) (VstInt32 qualities); /// @endcond //------------------------------------------------------------------------------------------------------- protected: audioMasterCallback audioMaster; ///< Host callback AEffEditor* editor; ///< Pointer to the plug-in's editor float sampleRate; ///< Current sample rate VstInt32 blockSize; ///< Maximum block size VstInt32 numPrograms; ///< Number of programs VstInt32 numParams; ///< Number of parameters VstInt32 curProgram; ///< Current program AEffect cEffect; ///< #AEffect object /// @cond ignore static VstIntPtr dispatchEffectClass (AEffect* e, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt); static float getParameterClass (AEffect* e, VstInt32 index); static void setParameterClass (AEffect* e, VstInt32 index, float value); static void DECLARE_VST_DEPRECATED (processClass) (AEffect* e, float** inputs, float** outputs, VstInt32 sampleFrames); static void processClassReplacing (AEffect* e, float** inputs, float** outputs, VstInt32 sampleFrames); #if VST_2_4_EXTENSIONS static void processClassDoubleReplacing (AEffect* e, double** inputs, double** outputs, VstInt32 sampleFrames); #endif // VST_2_4_EXTENSIONS /// @endcond }; #endif // __audioeffect__
JTriggerFish/protoplug
Frameworks/vstsdk2.4_minimal/public.sdk/source/vst2.x/audioeffect.h
C
mit
11,400
/** * Created by sunNode on 16/10/16. */ var should = require('should') var app = require('../app') var request = require('supertest') describe('upload temporyary testing', function () { it('uploadTemporyary should be return success', function (done) { request(app) .get('/admin/crawler') .end(function (err, res) { if (err) throw err should.exist(res.text) done() }) }) })
SensitiveMix/commerce
test/test-crawel.js
JavaScript
mit
463
module.exports = { str: "7.5.0" };
repuestos-365/server
client/node_modules/auth0-js/version.js
JavaScript
mit
35
<?php require 'database.php'; header("Content-Type: application/json"); // Since we are sending a JSON response here (not an HTML document), set the MIME Type to application/json session_start(); /*register*/ $username= $_POST['username']; $pwd= $_POST['password']; $_SESSION['username']= $username; $_SESSION['password']= $pwd; $pwd_hash= crypt($pwd); $stmt= $mysqli->prepare("insert into users (user_name, user_pass) values (?, ?)"); if (!$stmt){ printf("Query Prep Failed: %s\n", $mysqli->error); exit; } $stmt->bind_param('ss', $username, $pwd_hash); $stmt->execute(); $stmt->close(); echo json_encode(array( 'success' => true, 'message' => "you have been registered")); exit; ?>
Alex-Tran/CSE131Portal
insert.php
PHP
mit
723
module VagrantPlugins module DockerProvider module Cap module PublicAddress def self.public_address(machine) return nil if machine.state.id != :running ssh_info = machine.ssh_info return nil if !ssh_info ssh_info[:host] end end end end end
trivoallan/vagrant
plugins/providers/docker/cap/public_address.rb
Ruby
mit
321
#ifndef BOOST_SHARED_ARRAY_HPP_INCLUDED #define BOOST_SHARED_ARRAY_HPP_INCLUDED // // shared_array.hpp // // (C) Copyright Greg Colvin and Beman Dawes 1998, 1999. // Copyright (c) 2001, 2002 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. (See // accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) // // See http://www.boost.org/libs/smart_ptr/ for documentation. // #include <boost/smart_ptr/shared_array.hpp> #endif // #ifndef BOOST_SHARED_ARRAY_HPP_INCLUDED
SingularInversions/FaceGenBaseLibrary
source/LibTpBoost/boost_1_67_0/boost/shared_array.hpp
C++
mit
555
'use strict'; import React = require('react'); export class FontAwesomeIcon extends React.Component<{ path?: string }, {}> { // NOTES: SVG path data was obtained from: https://github.com/encharm/Font-Awesome-SVG-PNG/tree/master/black/svg // They assume a viewBox of '0 0 1792 1792'. // // Styling can be done in (S)CSS using the 'fa-svg' class (for icon height/width/alignment) and 'fa-svg-path' class (for fill color). public static paths = { CaretDown: 'M1408 704q0 26-19 45l-448 448q-19 19-45 19t-45-19l-448-448q-19-19-19-45t19-45 45-19h896q26 0 45 19t19 45z', CaretRight: 'M1152 896q0 26-19 45l-448 448q-19 19-45 19t-45-19-19-45v-896q0-26 19-45t45-19 45 19l448 448q19 19 19 45z', TimesCircle: 'M1277 1122q0-26-19-45l-181-181 181-181q19-19 19-45 0-27-19-46l-90-90q-19-19-46-19-26 0-45 19l-181 181-181-181q-19-19-45-19-27 0-46 19l-90 90q-19 19-19 46 0 26 19 45l181 181-181 181q-19 19-19 45 0 27 19 46l90 90q19 19 46 19 26 0 45-19l181-181 181 181q19 19 45 19 27 0 46-19l90-90q19-19 19-46zm387-226q0 209-103 385.5t-279.5 279.5-385.5 103-385.5-103-279.5-279.5-103-385.5 103-385.5 279.5-279.5 385.5-103 385.5 103 279.5 279.5 103 385.5z', Warning: 'M1024 1375v-190q0-14-9.5-23.5t-22.5-9.5h-192q-13 0-22.5 9.5t-9.5 23.5v190q0 14 9.5 23.5t22.5 9.5h192q13 0 22.5-9.5t9.5-23.5zm-2-374l18-459q0-12-10-19-13-11-24-11h-220q-11 0-24 11-10 7-10 21l17 457q0 10 10 16.5t24 6.5h185q14 0 23.5-6.5t10.5-16.5zm-14-934l768 1408q35 63-2 126-17 29-46.5 46t-63.5 17h-1536q-34 0-63.5-17t-46.5-46q-37-63-2-126l768-1408q17-31 47-49t65-18 65 18 47 49z' }; public render() { return <svg className='fa-svg' viewBox='0 0 1792 1792'><path className='fa-svg-path' d={this.props.path || ''}/></svg>; } }
Glimpse/Glimpse.Client.Prototype
src/shell/components/FontAwesomeIcon.tsx
TypeScript
mit
1,766
<div id="tx_trex_container" class="tx-editor-container"> <div id="tx_sidebar" class="tx-sidebar"> <div class="tx-sidebar-boundary"> <ul class="tx-bar tx-bar-left tx-nav-attach"> <li class="tx-list"> <div unselectable="on" id="tx_image" class="tx-image tx-btn-trans"> <a href="javascript:;" title="์‚ฌ์ง„" class="tx-text">์‚ฌ์ง„</a> </div> </li> <li class="tx-list"> <div unselectable="on" id="tx_file" class="tx-file tx-btn-trans"> <a href="javascript:;" title="ํŒŒ์ผ" class="tx-text">ํŒŒ์ผ</a> </div> </li> <li class="tx-list"> <div unselectable="on" id="tx_media" class="tx-media tx-btn-trans"> <a href="javascript:;" title="์™ธ๋ถ€์ปจํ…์ธ " class="tx-text">์™ธ๋ถ€์ปจํ…์ธ </a> </div> </li> </ul> <ul class="tx-bar tx-bar-right"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lrbg tx-fullscreen" id="tx_fullscreen"> <a href="javascript:;" class="tx-icon" title="๋„“๊ฒŒ์“ฐ๊ธฐ (Ctrl+M)">๋„“๊ฒŒ์“ฐ๊ธฐ</a> </div> </li> </ul> <ul class="tx-bar tx-bar-right tx-nav-opt"> <li class="tx-list"> <div unselectable="on" class="tx-switchtoggle" id="tx_switchertoggle"> <a href="javascript:;" title="์—๋””ํ„ฐ ํƒ€์ž…">์—๋””ํ„ฐ</a> </div> </li> </ul> </div> </div> <div id="tx_toolbar_basic" class="tx-toolbar tx-toolbar-basic"> <div class="tx-toolbar-boundary"> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div id="tx_fontfamily" unselectable="on" class="tx-slt-70bg tx-fontfamily"> <a href="javascript:;" title="๊ธ€๊ผด">๊ตด๋ฆผ</a> </div> <div id="tx_fontfamily_menu" class="tx-fontfamily-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div unselectable="on" class="tx-slt-42bg tx-fontsize" id="tx_fontsize"> <a href="javascript:;" title="๊ธ€์žํฌ๊ธฐ">9pt</a> </div> <div id="tx_fontsize_menu" class="tx-fontsize-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-font"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-bold" id="tx_bold"> <a href="javascript:;" class="tx-icon" title="๊ตต๊ฒŒ (Ctrl+B)">๊ตต๊ฒŒ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-underline" id="tx_underline"> <a href="javascript:;" class="tx-icon" title="๋ฐ‘์ค„ (Ctrl+U)">๋ฐ‘์ค„</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-italic" id="tx_italic"> <a href="javascript:;" class="tx-icon" title="๊ธฐ์šธ์ž„ (Ctrl+I)">๊ธฐ์šธ์ž„</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-strike" id="tx_strike"> <a href="javascript:;" class="tx-icon" title="์ทจ์†Œ์„  (Ctrl+D)">์ทจ์†Œ์„ </a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-slt-tbg tx-forecolor" id="tx_forecolor"> <a href="javascript:;" class="tx-icon" title="๊ธ€์ž์ƒ‰">๊ธ€์ž์ƒ‰</a> <a href="javascript:;" class="tx-arrow" title="๊ธ€์ž์ƒ‰ ์„ ํƒ">๊ธ€์ž์ƒ‰ ์„ ํƒ</a> </div> <div id="tx_forecolor_menu" class="tx-menu tx-forecolor-menu tx-colorpallete" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-slt-brbg tx-backcolor" id="tx_backcolor"> <a href="javascript:;" class="tx-icon" title="๊ธ€์ž ๋ฐฐ๊ฒฝ์ƒ‰">๊ธ€์ž ๋ฐฐ๊ฒฝ์ƒ‰</a> <a href="javascript:;" class="tx-arrow" title="๊ธ€์ž ๋ฐฐ๊ฒฝ์ƒ‰ ์„ ํƒ">๊ธ€์ž ๋ฐฐ๊ฒฝ์ƒ‰ ์„ ํƒ</a> </div> <div id="tx_backcolor_menu" class="tx-menu tx-backcolor-menu tx-colorpallete" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-align"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-alignleft" id="tx_alignleft"> <a href="javascript:;" class="tx-icon" title="์™ผ์ชฝ์ •๋ ฌ (Ctrl+,)">์™ผ์ชฝ์ •๋ ฌ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-aligncenter" id="tx_aligncenter"> <a href="javascript:;" class="tx-icon" title="๊ฐ€์šด๋ฐ์ •๋ ฌ (Ctrl+.)">๊ฐ€์šด๋ฐ์ •๋ ฌ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-alignright" id="tx_alignright"> <a href="javascript:;" class="tx-icon" title="์˜ค๋ฅธ์ชฝ์ •๋ ฌ (Ctrl+/)">์˜ค๋ฅธ์ชฝ์ •๋ ฌ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-alignfull" id="tx_alignfull"> <a href="javascript:;" class="tx-icon" title="์–‘์ชฝ์ •๋ ฌ">์–‘์ชฝ์ •๋ ฌ</a> </div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-tab"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-indent" id="tx_indent"> <a href="javascript:;" title="๋“ค์—ฌ์“ฐ๊ธฐ (Tab)" class="tx-icon">๋“ค์—ฌ์“ฐ๊ธฐ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-outdent" id="tx_outdent"> <a href="javascript:;" title="๋‚ด์–ด์“ฐ๊ธฐ (Shift+Tab)" class="tx-icon">๋‚ด์–ด์“ฐ๊ธฐ</a> </div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-list"> <li class="tx-list"> <div unselectable="on" class="tx-slt-31lbg tx-lineheight" id="tx_lineheight"> <a href="javascript:;" class="tx-icon" title="์ค„๊ฐ„๊ฒฉ">์ค„๊ฐ„๊ฒฉ</a> <a href="javascript:;" class="tx-arrow" title="์ค„๊ฐ„๊ฒฉ">์ค„๊ฐ„๊ฒฉ ์„ ํƒ</a> </div> <div id="tx_lineheight_menu" class="tx-lineheight-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-slt-31rbg tx-styledlist" id="tx_styledlist"> <a href="javascript:;" class="tx-icon" title="๋ฆฌ์ŠคํŠธ">๋ฆฌ์ŠคํŠธ</a> <a href="javascript:;" class="tx-arrow" title="๋ฆฌ์ŠคํŠธ">๋ฆฌ์ŠคํŠธ ์„ ํƒ</a> </div> <div id="tx_styledlist_menu" class="tx-styledlist-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-etc"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-emoticon" id="tx_emoticon"> <a href="javascript:;" class="tx-icon" title="์ด๋ชจํ‹ฐ์ฝ˜">์ด๋ชจํ‹ฐ์ฝ˜</a> </div> <div id="tx_emoticon_menu" class="tx-emoticon-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-link" id="tx_link"> <a href="javascript:;" class="tx-icon" title="๋งํฌ (Ctrl+K)">๋งํฌ</a> </div> <div id="tx_link_menu" class="tx-link-menu tx-menu"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-specialchar" id="tx_specialchar"> <a href="javascript:;" class="tx-icon" title="ํŠน์ˆ˜๋ฌธ์ž">ํŠน์ˆ˜๋ฌธ์ž</a> </div> <div id="tx_specialchar_menu" class="tx-specialchar-menu tx-menu"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-table" id="tx_table"> <a href="javascript:;" class="tx-icon" title="ํ‘œ๋งŒ๋“ค๊ธฐ">ํ‘œ๋งŒ๋“ค๊ธฐ</a> </div> <div id="tx_table_menu" class="tx-table-menu tx-menu" unselectable="on"> <div class="tx-menu-inner"> <div class="tx-menu-preview"></div> <div class="tx-menu-rowcol"></div> <div class="tx-menu-deco"></div> <div class="tx-menu-enter"></div> </div> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-horizontalrule" id="tx_horizontalrule"> <a href="javascript:;" class="tx-icon" title="๊ตฌ๋ถ„์„ ">๊ตฌ๋ถ„์„ </a> </div> <div id="tx_horizontalrule_menu" class="tx-horizontalrule-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-richtextbox" id="tx_richtextbox"> <a href="javascript:;" class="tx-icon" title="๊ธ€์ƒ์ž">๊ธ€์ƒ์ž</a> </div> <div id="tx_richtextbox_menu" class="tx-richtextbox-menu tx-menu"> <div class="tx-menu-header"> <div class="tx-menu-preview-area"> <div class="tx-menu-preview"></div> </div> <div class="tx-menu-switch"> <div class="tx-menu-simple tx-selected"><a><span>๊ฐ„๋‹จ ์„ ํƒ</span></a></div> <div class="tx-menu-advanced"><a><span>์ง์ ‘ ์„ ํƒ</span></a></div> </div> </div> <div class="tx-menu-inner"> </div> <div class="tx-menu-footer"> <img class="tx-menu-confirm" src="images/icon/editor/btn_confirm.gif?rv=1.0.1" alt=""/> <img class="tx-menu-cancel" hspace="3" src="images/icon/editor/btn_cancel.gif?rv=1.0.1" alt=""/> </div> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-quote" id="tx_quote"> <a href="javascript:;" class="tx-icon" title="์ธ์šฉ๊ตฌ (Ctrl+Q)">์ธ์šฉ๊ตฌ</a> </div> <div id="tx_quote_menu" class="tx-quote-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-background" id="tx_background"> <a href="javascript:;" class="tx-icon" title="๋ฐฐ๊ฒฝ์ƒ‰">๋ฐฐ๊ฒฝ์ƒ‰</a> </div> <div id="tx_background_menu" class="tx-menu tx-background-menu tx-colorpallete" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-dictionary" id="tx_dictionary"> <a href="javascript:;" class="tx-icon" title="์‚ฌ์ „">์‚ฌ์ „</a> </div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-undo"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-undo" id="tx_undo"> <a href="javascript:;" class="tx-icon" title="์‹คํ–‰์ทจ์†Œ (Ctrl+Z)">์‹คํ–‰์ทจ์†Œ</a> </div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-redo" id="tx_redo"> <a href="javascript:;" class="tx-icon" title="๋‹ค์‹œ์‹คํ–‰ (Ctrl+Y)">๋‹ค์‹œ์‹คํ–‰</a> </div> </li> </ul> <ul class="tx-bar tx-bar-right"> <li class="tx-list"> <div unselectable="on" class="tx-btn-nlrbg tx-advanced" id="tx_advanced"> <a href="javascript:;" class="tx-icon" title="ํˆด๋ฐ” ๋”๋ณด๊ธฐ">ํˆด๋ฐ” ๋”๋ณด๊ธฐ</a> </div> </li> </ul> </div> </div> <div id="tx_toolbar_advanced" class="tx-toolbar tx-toolbar-advanced"> <div class="tx-toolbar-boundary"> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div class="tx-tableedit-title"></div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-align"> <li class="tx-list"> <div unselectable="on" class="tx-btn-lbg tx-mergecells" id="tx_mergecells"> <a href="javascript:;" class="tx-icon2" title="๋ณ‘ํ•ฉ">๋ณ‘ํ•ฉ</a> </div> <div id="tx_mergecells_menu" class="tx-mergecells-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-bg tx-insertcells" id="tx_insertcells"> <a href="javascript:;" class="tx-icon2" title="์‚ฝ์ž…">์‚ฝ์ž…</a> </div> <div id="tx_insertcells_menu" class="tx-insertcells-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div unselectable="on" class="tx-btn-rbg tx-deletecells" id="tx_deletecells"> <a href="javascript:;" class="tx-icon2" title="์‚ญ์ œ">์‚ญ์ œ</a> </div> <div id="tx_deletecells_menu" class="tx-deletecells-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left tx-group-align"> <li class="tx-list"> <div id="tx_cellslinepreview" unselectable="on" class="tx-slt-70lbg tx-cellslinepreview"> <a href="javascript:;" title="์„  ๋ฏธ๋ฆฌ๋ณด๊ธฐ"></a> </div> <div id="tx_cellslinepreview_menu" class="tx-cellslinepreview-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div id="tx_cellslinecolor" unselectable="on" class="tx-slt-tbg tx-cellslinecolor"> <a href="javascript:;" class="tx-icon2" title="์„ ์ƒ‰">์„ ์ƒ‰</a> <div class="tx-colorpallete" unselectable="on"></div> </div> <div id="tx_cellslinecolor_menu" class="tx-cellslinecolor-menu tx-menu tx-colorpallete" unselectable="on"></div> </li> <li class="tx-list"> <div id="tx_cellslineheight" unselectable="on" class="tx-btn-bg tx-cellslineheight"> <a href="javascript:;" class="tx-icon2" title="๋‘๊ป˜">๋‘๊ป˜</a> </div> <div id="tx_cellslineheight_menu" class="tx-cellslineheight-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div id="tx_cellslinestyle" unselectable="on" class="tx-btn-bg tx-cellslinestyle"> <a href="javascript:;" class="tx-icon2" title="์Šคํƒ€์ผ">์Šคํƒ€์ผ</a> </div> <div id="tx_cellslinestyle_menu" class="tx-cellslinestyle-menu tx-menu" unselectable="on"></div> </li> <li class="tx-list"> <div id="tx_cellsoutline" unselectable="on" class="tx-btn-rbg tx-cellsoutline"> <a href="javascript:;" class="tx-icon2" title="ํ…Œ๋‘๋ฆฌ">ํ…Œ๋‘๋ฆฌ</a> </div> <div id="tx_cellsoutline_menu" class="tx-cellsoutline-menu tx-menu" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div id="tx_tablebackcolor" unselectable="on" class="tx-btn-lrbg tx-tablebackcolor" style="background-color:#9aa5ea;"> <a href="javascript:;" class="tx-icon2" title="ํ…Œ์ด๋ธ” ๋ฐฐ๊ฒฝ์ƒ‰">ํ…Œ์ด๋ธ” ๋ฐฐ๊ฒฝ์ƒ‰</a> </div> <div id="tx_tablebackcolor_menu" class="tx-tablebackcolor-menu tx-menu tx-colorpallete" unselectable="on"></div> </li> </ul> <ul class="tx-bar tx-bar-left"> <li class="tx-list"> <div id="tx_tabletemplate" unselectable="on" class="tx-btn-lrbg tx-tabletemplate"> <a href="javascript:;" class="tx-icon2" title="ํ…Œ์ด๋ธ” ์„œ์‹">ํ…Œ์ด๋ธ” ์„œ์‹</a> </div> <div id="tx_tabletemplate_menu" class="tx-tabletemplate-menu tx-menu tx-colorpallete" unselectable="on"></div> </li> </ul> </div> </div> <div id="tx_canvas" class="tx-canvas"> <div id="tx_loading" class="tx-loading"> <div><img src="images/icon/editor/loading2.png" width="113" height="21" align="absmiddle"/></div> </div> <div id="tx_canvas_wysiwyg_holder" class="tx-holder" style="display:block;"> <iframe id="tx_canvas_wysiwyg" name="tx_canvas_wysiwyg" allowtransparency="true" frameborder="0"></iframe> </div> <div class="tx-source-deco"> <div id="tx_canvas_source_holder" class="tx-holder"> <textarea id="tx_canvas_source" rows="30" cols="30"></textarea> </div> </div> <div id="tx_canvas_text_holder" class="tx-holder"> <textarea id="tx_canvas_text" rows="30" cols="30"></textarea> </div> </div> <div id="tx_resizer" class="tx-resize-bar"> <div class="tx-resize-bar-bg"></div> <img id="tx_resize_holder" src="images/icon/editor/skin/01/btn_drag01.gif" width="58" height="12" unselectable="on" alt=""/> </div> <div class="tx-side-bi" id="tx_side_bi"> <div style="text-align: right;"> <img hspace="4" height="14" width="78" align="absmiddle" src="images/icon/editor/editor_bi.png"/> </div> </div> <div id="tx_attach_div" class="tx-attach-div"> <div id="tx_attach_txt" class="tx-attach-txt">ํŒŒ์ผ ์ฒจ๋ถ€</div> <div id="tx_attach_box" class="tx-attach-box"> <div class="tx-attach-box-inner"> <div id="tx_attach_preview" class="tx-attach-preview"> <p></p> <img src="images/icon/editor/pn_preview.gif" width="147" height="108" unselectable="on"/> </div> <div class="tx-attach-main"> <div id="tx_upload_progress" class="tx-upload-progress"> <div>0%</div> <p>ํŒŒ์ผ์„ ์—…๋กœ๋“œํ•˜๋Š” ์ค‘์ž…๋‹ˆ๋‹ค.</p> </div> <ul class="tx-attach-top"> <li id="tx_attach_delete" class="tx-attach-delete"><a>์ „์ฒด์‚ญ์ œ</a></li> <li id="tx_attach_size" class="tx-attach-size"> ํŒŒ์ผ: <span id="tx_attach_up_size" class="tx-attach-size-up"></span>/ <span id="tx_attach_max_size"></span> </li> <li id="tx_attach_tools" class="tx-attach-tools"> </li> </ul> <ul id="tx_attach_list" class="tx-attach-list"></ul> </div> </div> </div> </div> </div>
CatsMiaow/KI_Board
www/editor/pages/template/simple.html
HTML
mit
18,109
module Emails module Projects def project_was_moved_email(project_id, user_id, old_path_with_namespace) @current_user = @user = User.find user_id @project = Project.find project_id @target_url = namespace_project_url(@project.namespace, @project) @old_path_with_namespace = old_path_with_namespace mail(to: @user.notification_email, subject: subject("้กน็›ฎ่ขซ็งปๅŠจ")) end def project_was_exported_email(current_user, project) @project = project mail(to: current_user.notification_email, subject: subject("้กน็›ฎ่ขซๅฏผๅ‡บ")) end def project_was_not_exported_email(current_user, project, errors) @project = project @errors = errors mail(to: current_user.notification_email, subject: subject("้กน็›ฎๅฏผๅ‡บ้”™่ฏฏ")) end def repository_push_email(project_id, opts = {}) @message = Gitlab::Email::Message::RepositoryPush.new(self, project_id, opts) # used in notify layout @target_url = @message.target_url @project = Project.find(project_id) @diff_notes_disabled = true add_project_headers headers['X-GitLab-Author'] = @message.author_username mail(from: sender(@message.author_id, @message.send_from_committer_email?), reply_to: @message.reply_to, subject: @message.subject) end end end
htve/GitlabForChinese
app/mailers/emails/projects.rb
Ruby
mit
1,406
import * as React from 'react'; interface DataTableProps { id?: string; value?: any[]; header?: any; footer?: any; style?: object; className?: string; tableStyle?: object; tableClassName?: string; paginator?: boolean; paginatorPosition?: string; alwaysShowPaginator?: boolean; paginatorTemplate?: string; paginatorLeft?: any; paginatorRight?: any; pageLinkSize?: number; paginatorDropdownAppendTo?: any; rowsPerPageOptions?: number[]; currentPageReportTemplate?: string; first?: number; rows?: number; totalRecords?: number; lazy?: boolean; sortField?: string; sortOrder?: number; multiSortMeta?: any[]; sortMode?: string; defaultSortOrder?: number; removableSort?: boolean; emptyMessage?: any; selectionMode?: string; selection?: any; contextMenuSelection?: any; compareSelectionBy?: string; dataKey?: string; metaKeySelection?: boolean; headerColumnGroup?: any; footerColumnGroup?: any; frozenHeaderColumnGroup?: any; frozenFooterColumnGroup?: any; expandedRows?: any[]; resizableColumns?: boolean; columnResizeMode?: string; reorderableColumns?: boolean; filters?: object; globalFilter?: any; filterLocale?: string; scrollable?: boolean; scrollHeight?: string; virtualScroll?: boolean; virtualScrollDelay?: number; virtualRowHeight?: number; frozenWidth?: string; frozenValue?: any[]; csvSeparator?: string; exportFilename?: string; rowGroupMode?: string; autoLayout?:boolean; loading?:boolean; loadingIcon?:string; tabIndex?:string; stateKey?:string; stateStorage?:string; groupField?:string; editMode?:string; expandableRowGroups?:boolean; rowHover?:boolean; showSelectionElement?(e: {data: any}): boolean; showReorderElement?(e: {data: any}): boolean; onSelectionChange?(e: {originalEvent: Event, value: any}): void; onContextMenuSelectionChange?(e: {originalEvent: Event, value: any}): void; rowExpansionTemplate?(data: any): JSX.Element | undefined; onRowToggle?(e: {data: any[]}): void; rowClassName?(rowData: any): object; rowGroupHeaderTemplate?(data: any, index: number): React.ReactNode | undefined; rowGroupFooterTemplate?(data: any, index: number): React.ReactNode | undefined; onColumnResizeEnd?(e: {element: HTMLElement, delta: number}): void; onSort?(e: {sortField: string, sortOrder: number, multiSortMeta: any}): void; onPage?(e: {first: number, rows: number}): void; onFilter?(e: {filters: any}): void; onVirtualScroll?(e: {first: number, rows: number}): void; onRowClick?(e: {originalEvent: Event, data: any, index: number}): void; onRowDoubleClick?(e: {originalEvent: Event, data: any, index: number}): void; onRowSelect?(e: {originalEvent: Event, data: any, type: string}): void; onRowUnselect?(e: {originalEvent: Event, data: any, type: string}): void; onRowExpand?(e: {originalEvent: Event, data: any}): void; onRowCollapse?(e: {originalEvent: Event, data: any}): void; onContextMenu?(e: {originalEvent: Event, data: any}): void; onColReorder?(e: {originalEvent: Event, dragIndex: number, dropIndex: number, columns: any}): void; onRowReorder?(e: {originalEvent: Event, value: any, dragIndex: number, dropIndex: number}): void; onValueChange?(value: any[]): void; rowEditorValidator?(rowData: any): boolean; onRowEditInit?(e: {originalEvent: Event, data: any, index: number}): void; onRowEditSave?(e: {originalEvent: Event, data: any, index: number}): void; onRowEditCancel?(e: {originalEvent: Event, data: any, index: number}): void; exportFunction?(e: {data: any, field: string}): any; customSaveState?(state: any): void; customRestoreState?(): any; onStateSave?(state: any): void; onStateRestore?(state: any): void; } export class DataTable extends React.Component<DataTableProps,any> { public reset():void; public exportCSV():void; public filter<T>(value:T, field:string, mode:string):void; public resetColumnOrder():void; public closeEditingCell():void; }
cdnjs/cdnjs
ajax/libs/primereact/5.0.2/components/datatable/DataTable.d.ts
TypeScript
mit
4,205
/** * AUTOMATICALLY GENERATED FILE, DO NOT EDIT MANUALLY! * Update this file by running `lerna run webpack-updater` in the monorepo root folder. */ var ClientSideRowModelModule = require('../../community-modules/client-side-row-model'); var GridCoreModule = require('../../community-modules/core'); var CsvExportModule = require('../../community-modules/csv-export'); var InfiniteRowModelModule = require('../../community-modules/infinite-row-model'); var agGrid = require('./dist/es6/main'); Object.keys(agGrid).forEach(function(key) { exports[key] = agGrid[key]; }); agGrid.ModuleRegistry.register(ClientSideRowModelModule.ClientSideRowModelModule); agGrid.ModuleRegistry.register(CsvExportModule.CsvExportModule); agGrid.ModuleRegistry.register(InfiniteRowModelModule.InfiniteRowModelModule);
ceolter/angular-grid
community-modules/all-modules/webpack-no-styles.js
JavaScript
mit
803
"use strict";var __importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0});const d3_selection_1=require("d3-selection"),d3_color_1=require("d3-color"),utils_1=__importDefault(require("../utils")),evaluate_1=__importDefault(require("../evaluate"));function scatter(t){const e=t.meta.xScale,r=t.meta.yScale;return function(l){l.each(function(l){let o,a;const c=l.index,i=utils_1.default.color(l,c),u=evaluate_1.default(t,l),n=[];for(o=0;o<u.length;o+=1)for(a=0;a<u[o].length;a+=1)n.push(u[o][a]);const s=d3_selection_1.select(this).selectAll(":scope > circle").data(n),_=s.enter().append("circle");s.merge(_).attr("fill",d3_color_1.hsl(i.toString()).brighter(1.5).hex()).attr("stroke",i).attr("opacity",.7).attr("r",1).attr("cx",function(t){return e(t[0])}).attr("cy",function(t){return r(t[1])}).attr(l.attr),s.exit().remove()})}}exports.default=scatter;
cdnjs/cdnjs
ajax/libs/function-plot/1.22.2/graph-types/scatter.min.js
JavaScript
mit
944
/* * * * (c) 2009-2019 ร˜ystein Moseng * * Accessibility component for chart info region and table. * * License: www.highcharts.com/license * * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!! * * */ 'use strict'; import H from '../../../parts/Globals.js'; var doc = H.win.document, format = H.format; import U from '../../../parts/Utilities.js'; var extend = U.extend, pick = U.pick; import AccessibilityComponent from '../AccessibilityComponent.js'; import ChartUtilities from '../utils/chartUtilities.js'; var unhideChartElementFromAT = ChartUtilities.unhideChartElementFromAT, getChartTitle = ChartUtilities.getChartTitle, getAxisDescription = ChartUtilities.getAxisDescription; import HTMLUtilities from '../utils/htmlUtilities.js'; var addClass = HTMLUtilities.addClass, setElAttrs = HTMLUtilities.setElAttrs, escapeStringForHTML = HTMLUtilities.escapeStringForHTML, stripHTMLTagsFromString = HTMLUtilities.stripHTMLTagsFromString, getElement = HTMLUtilities.getElement, visuallyHideElement = HTMLUtilities.visuallyHideElement; /* eslint-disable no-invalid-this, valid-jsdoc */ /** * @private */ function getTypeDescForMapChart(chart, formatContext) { return formatContext.mapTitle ? chart.langFormat('accessibility.chartTypes.mapTypeDescription', formatContext) : chart.langFormat('accessibility.chartTypes.unknownMap', formatContext); } /** * @private */ function getTypeDescForCombinationChart(chart, formatContext) { return chart.langFormat('accessibility.chartTypes.combinationChart', formatContext); } /** * @private */ function getTypeDescForEmptyChart(chart, formatContext) { return chart.langFormat('accessibility.chartTypes.emptyChart', formatContext); } /** * @private */ function buildTypeDescriptionFromSeries(chart, types, context) { var firstType = types[0], typeExplaination = chart.langFormat('accessibility.seriesTypeDescriptions.' + firstType, context), multi = chart.series && chart.series.length < 2 ? 'Single' : 'Multiple'; return (chart.langFormat('accessibility.chartTypes.' + firstType + multi, context) || chart.langFormat('accessibility.chartTypes.default' + multi, context)) + (typeExplaination ? ' ' + typeExplaination : ''); } /** * @private */ function getTableSummary(chart) { return chart.langFormat('accessibility.table.tableSummary', { chart: chart }); } /** * @private */ function stripEmptyHTMLTags(str) { return str.replace(/<(\w+)[^>]*?>\s*<\/\1>/g, ''); } /** * @private */ function enableSimpleHTML(str) { return str .replace(/&lt;(h[1-7]|p|div)&gt;/g, '<$1>') .replace(/&lt;&#x2F;(h[1-7]|p|div|a|button)&gt;/g, '</$1>') .replace(/&lt;(div|a|button) id=&quot;([a-zA-Z\-0-9#]*?)&quot;&gt;/g, '<$1 id="$2">'); } /** * @private */ function stringToSimpleHTML(str) { return stripEmptyHTMLTags(enableSimpleHTML(escapeStringForHTML(str))); } /** * Return simplified explaination of chart type. Some types will not be familiar * to most users, but in those cases we try to add an explaination of the type. * * @private * @function Highcharts.Chart#getTypeDescription * @param {Array<string>} types The series types in this chart. * @return {string} The text description of the chart type. */ H.Chart.prototype.getTypeDescription = function (types) { var firstType = types[0], firstSeries = this.series && this.series[0] || {}, formatContext = { numSeries: this.series.length, numPoints: firstSeries.points && firstSeries.points.length, chart: this, mapTitle: firstSeries.mapTitle }; if (!firstType) { return getTypeDescForEmptyChart(this, formatContext); } if (firstType === 'map') { return getTypeDescForMapChart(this, formatContext); } if (this.types.length > 1) { return getTypeDescForCombinationChart(this, formatContext); } return buildTypeDescriptionFromSeries(this, types, formatContext); }; /** * The InfoRegionsComponent class * * @private * @class * @name Highcharts.InfoRegionsComponent */ var InfoRegionsComponent = function () { }; InfoRegionsComponent.prototype = new AccessibilityComponent(); extend(InfoRegionsComponent.prototype, /** @lends Highcharts.InfoRegionsComponent */ { /** * Init the component * @private */ init: function () { var chart = this.chart, component = this; this.initRegionsDefinitions(); this.addEvent(chart, 'afterGetTable', function (e) { component.onDataTableCreated(e); }); this.addEvent(chart, 'afterViewData', function (tableDiv) { component.dataTableDiv = tableDiv; // Use small delay to give browsers & AT time to register new table setTimeout(function () { component.focusDataTable(); }, 300); }); }, /** * @private */ initRegionsDefinitions: function () { var component = this; this.screenReaderSections = { before: { element: null, buildContent: function (chart) { var formatter = chart.options.accessibility .screenReaderSection.beforeChartFormatter; return formatter ? formatter(chart) : component.defaultBeforeChartFormatter(chart); }, insertIntoDOM: function (el, chart) { chart.renderTo.insertBefore(el, chart.renderTo.firstChild); }, afterInserted: function () { if (typeof component.dataTableButtonId !== 'undefined') { component.initDataTableButton(component.dataTableButtonId); } } }, after: { element: null, buildContent: function (chart) { var formatter = chart.options.accessibility.screenReaderSection .afterChartFormatter; return formatter ? formatter(chart) : component.defaultAfterChartFormatter(); }, insertIntoDOM: function (el, chart) { chart.renderTo.insertBefore(el, chart.container.nextSibling); } } }; }, /** * Called on first render/updates to the chart, including options changes. */ onChartUpdate: function () { var component = this; this.linkedDescriptionElement = this.getLinkedDescriptionElement(); this.setLinkedDescriptionAttrs(); Object.keys(this.screenReaderSections).forEach(function (regionKey) { component.updateScreenReaderSection(regionKey); }); }, /** * @private */ getLinkedDescriptionElement: function () { var chartOptions = this.chart.options, linkedDescOption = chartOptions.accessibility.linkedDescription; if (!linkedDescOption) { return; } if (typeof linkedDescOption !== 'string') { return linkedDescOption; } var query = format(linkedDescOption, this.chart), queryMatch = doc.querySelectorAll(query); if (queryMatch.length === 1) { return queryMatch[0]; } }, /** * @private */ setLinkedDescriptionAttrs: function () { var el = this.linkedDescriptionElement; if (el) { el.setAttribute('aria-hidden', 'true'); addClass(el, 'highcharts-linked-description'); } }, /** * @private * @param {string} regionKey The name/key of the region to update */ updateScreenReaderSection: function (regionKey) { var chart = this.chart, region = this.screenReaderSections[regionKey], content = region.buildContent(chart), sectionDiv = region.element = (region.element || this.createElement('div')), hiddenDiv = (sectionDiv.firstChild || this.createElement('div')); this.setScreenReaderSectionAttribs(sectionDiv, regionKey); hiddenDiv.innerHTML = content; sectionDiv.appendChild(hiddenDiv); region.insertIntoDOM(sectionDiv, chart); visuallyHideElement(hiddenDiv); unhideChartElementFromAT(chart, hiddenDiv); if (region.afterInserted) { region.afterInserted(); } }, /** * @private * @param {Highcharts.HTMLDOMElement} sectionDiv The section element * @param {string} regionKey Name/key of the region we are setting attrs for */ setScreenReaderSectionAttribs: function (sectionDiv, regionKey) { var labelLangKey = ('accessibility.screenReaderSection.' + regionKey + 'RegionLabel'), chart = this.chart, labelText = chart.langFormat(labelLangKey, { chart: chart }), sectionId = 'highcharts-screen-reader-region-' + regionKey + '-' + chart.index; setElAttrs(sectionDiv, { id: sectionId, 'aria-label': labelText }); // Sections are wrapped to be positioned relatively to chart in case // elements inside are tabbed to. sectionDiv.style.position = 'relative'; if (chart.options.accessibility.landmarkVerbosity === 'all' && labelText) { sectionDiv.setAttribute('role', 'region'); } }, /** * @private * @return {string} */ defaultBeforeChartFormatter: function () { var chart = this.chart, format = chart.options.accessibility .screenReaderSection.beforeChartFormat, axesDesc = this.getAxesDescription(), dataTableButtonId = 'hc-linkto-highcharts-data-table-' + chart.index, context = { chartTitle: getChartTitle(chart), typeDescription: this.getTypeDescriptionText(), chartSubtitle: this.getSubtitleText(), chartLongdesc: this.getLongdescText(), xAxisDescription: axesDesc.xAxis, yAxisDescription: axesDesc.yAxis, viewTableButton: chart.getCSV ? this.getDataTableButtonText(dataTableButtonId) : '' }, formattedString = H.i18nFormat(format, context, chart); this.dataTableButtonId = dataTableButtonId; return stringToSimpleHTML(formattedString); }, /** * @private * @return {string} */ defaultAfterChartFormatter: function () { var chart = this.chart, format = chart.options.accessibility .screenReaderSection.afterChartFormat, context = { endOfChartMarker: this.getEndOfChartMarkerText() }, formattedString = H.i18nFormat(format, context, chart); return stringToSimpleHTML(formattedString); }, /** * @private * @return {string} */ getLinkedDescription: function () { var el = this.linkedDescriptionElement, content = el && el.innerHTML || ''; return stripHTMLTagsFromString(content); }, /** * @private * @return {string} */ getLongdescText: function () { var chartOptions = this.chart.options, captionOptions = chartOptions.caption, captionText = captionOptions && captionOptions.text, linkedDescription = this.getLinkedDescription(); return (chartOptions.accessibility.description || linkedDescription || captionText || ''); }, /** * @private * @return {string} */ getTypeDescriptionText: function () { var chart = this.chart; return chart.types ? chart.options.accessibility.typeDescription || chart.getTypeDescription(chart.types) : ''; }, /** * @private * @param {string} buttonId * @return {string} */ getDataTableButtonText: function (buttonId) { var chart = this.chart, buttonText = chart.langFormat('accessibility.table.viewAsDataTableButtonText', { chart: chart, chartTitle: getChartTitle(chart) }); return '<a id="' + buttonId + '">' + buttonText + '</a>'; }, /** * @private * @return {string} */ getSubtitleText: function () { var subtitle = (this.chart.options.subtitle); return stripHTMLTagsFromString(subtitle && subtitle.text || ''); }, /** * @private * @return {string} */ getEndOfChartMarkerText: function () { var chart = this.chart, markerText = chart.langFormat('accessibility.screenReaderSection.endOfChartMarker', { chart: chart }), id = 'highcharts-end-of-chart-marker-' + chart.index; return '<div id="' + id + '">' + markerText + '</div>'; }, /** * @private * @param {Highcharts.Dictionary<string>} e */ onDataTableCreated: function (e) { var chart = this.chart; if (chart.options.accessibility.enabled) { if (this.viewDataTableButton) { this.viewDataTableButton.setAttribute('aria-expanded', 'true'); } e.html = e.html.replace('<table ', '<table tabindex="0" summary="' + getTableSummary(chart) + '"'); } }, /** * @private */ focusDataTable: function () { var tableDiv = this.dataTableDiv, table = tableDiv && tableDiv.getElementsByTagName('table')[0]; if (table && table.focus) { table.focus(); } }, /** * Set attribs and handlers for default viewAsDataTable button if exists. * @private * @param {string} tableButtonId */ initDataTableButton: function (tableButtonId) { var el = this.viewDataTableButton = getElement(tableButtonId), chart = this.chart, tableId = tableButtonId.replace('hc-linkto-', ''); if (el) { setElAttrs(el, { role: 'button', tabindex: '-1', 'aria-expanded': !!getElement(tableId), href: '#' + tableId }); el.onclick = chart.options.accessibility .screenReaderSection.onViewDataTableClick || function () { chart.viewData(); }; } }, /** * Return object with text description of each of the chart's axes. * @private * @return {Highcharts.Dictionary<string>} */ getAxesDescription: function () { var chart = this.chart, shouldDescribeColl = function (collectionKey, defaultCondition) { var axes = chart[collectionKey]; return axes.length > 1 || axes[0] && pick(axes[0].options.accessibility && axes[0].options.accessibility.enabled, defaultCondition); }, hasNoMap = !!chart.types && chart.types.indexOf('map') < 0, hasCartesian = !!chart.hasCartesianSeries, showXAxes = shouldDescribeColl('xAxis', !chart.angular && hasCartesian && hasNoMap), showYAxes = shouldDescribeColl('yAxis', hasCartesian && hasNoMap), desc = {}; if (showXAxes) { desc.xAxis = this.getAxisDescriptionText('xAxis'); } if (showYAxes) { desc.yAxis = this.getAxisDescriptionText('yAxis'); } return desc; }, /** * @private * @param {string} collectionKey * @return {string} */ getAxisDescriptionText: function (collectionKey) { var component = this, chart = this.chart, axes = chart[collectionKey]; return chart.langFormat('accessibility.axis.' + collectionKey + 'Description' + (axes.length > 1 ? 'Plural' : 'Singular'), { chart: chart, names: axes.map(function (axis) { return getAxisDescription(axis); }), ranges: axes.map(function (axis) { return component.getAxisRangeDescription(axis); }), numAxes: axes.length }); }, /** * Return string with text description of the axis range. * @private * @param {Highcharts.Axis} axis The axis to get range desc of. * @return {string} A string with the range description for the axis. */ getAxisRangeDescription: function (axis) { var axisOptions = axis.options || {}; // Handle overridden range description if (axisOptions.accessibility && typeof axisOptions.accessibility.rangeDescription !== 'undefined') { return axisOptions.accessibility.rangeDescription; } // Handle category axes if (axis.categories) { return this.getCategoryAxisRangeDesc(axis); } // Use time range, not from-to? if (axis.isDatetimeAxis && (axis.min === 0 || axis.dataMin === 0)) { return this.getAxisTimeLengthDesc(axis); } // Just use from and to. // We have the range and the unit to use, find the desc format return this.getAxisFromToDescription(axis); }, /** * @private * @param {Highcharts.Axis} axis * @return {string} */ getCategoryAxisRangeDesc: function (axis) { var chart = this.chart; if (axis.dataMax && axis.dataMin) { return chart.langFormat('accessibility.axis.rangeCategories', { chart: chart, axis: axis, numCategories: axis.dataMax - axis.dataMin + 1 }); } return ''; }, /** * @private * @param {Highcharts.Axis} axis * @return {string} */ getAxisTimeLengthDesc: function (axis) { var chart = this.chart, range = {}, rangeUnit = 'Seconds'; range.Seconds = ((axis.max || 0) - (axis.min || 0)) / 1000; range.Minutes = range.Seconds / 60; range.Hours = range.Minutes / 60; range.Days = range.Hours / 24; ['Minutes', 'Hours', 'Days'].forEach(function (unit) { if (range[unit] > 2) { rangeUnit = unit; } }); var rangeValue = range[rangeUnit].toFixed(rangeUnit !== 'Seconds' && rangeUnit !== 'Minutes' ? 1 : 0 // Use decimals for days/hours ); // We have the range and the unit to use, find the desc format return chart.langFormat('accessibility.axis.timeRange' + rangeUnit, { chart: chart, axis: axis, range: rangeValue.replace('.0', '') }); }, /** * @private * @param {Highcharts.Axis} axis * @return {string} */ getAxisFromToDescription: function (axis) { var chart = this.chart, dateRangeFormat = chart.options.accessibility .screenReaderSection.axisRangeDateFormat, format = function (axisKey) { return axis.isDatetimeAxis ? chart.time.dateFormat(dateRangeFormat, axis[axisKey]) : axis[axisKey]; }; return chart.langFormat('accessibility.axis.rangeFromTo', { chart: chart, axis: axis, rangeFrom: format('min'), rangeTo: format('max') }); } }); export default InfoRegionsComponent;
cdnjs/cdnjs
ajax/libs/highcharts/8.0.0/es-modules/modules/accessibility/components/InfoRegionsComponent.js
JavaScript
mit
19,015
package mat.client.shared; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; import mat.shared.ConstantMessages; public class MeasureDetailsConstants { public static final String PROPORTION = ConstantMessages.PROPORTION_SCORING; public static final String RATIO = ConstantMessages.RATIO_SCORING; public static final String CONTINUOUS_VARIABLE = ConstantMessages.CONTINUOUS_VARIABLE_SCORING; public static final String COHORT = ConstantMessages.COHORT_SCORING; public enum MeasureDetailsItems implements MatDetailItem{ GENERAL_MEASURE_INFORMATION("General Measure Information", "General Measure Information"), COMPONENT_MEASURES("Component Measures","Component Measures"), STEWARD("Measure Steward / Developer", "Measure Steward and Measure Developer"), DESCRIPTION("Description", "Description"), COPYRIGHT("Copyright", "Copyright"), DISCLAIMER("Disclaimer", "Disclaimer"), MEASURE_TYPE("Measure Type", "Measure Type"), STRATIFICATION("Stratification", "Stratification"), RISK_ADJUSTMENT("Risk Adjustment", "Risk Adjustment"), RATE_AGGREGATION("Rate Aggregation", "Rate Aggregation"), RATIONALE("Rationale", "Rationale"), CLINICAL_RECOMMENDATION("Clinical Recommendation", "Clinical Recommendation Statement"), IMPROVEMENT_NOTATION("Improvement Notation", "Improvement Notation"), REFERENCES("References", "References"), DEFINITION("Definition", "Definition"), GUIDANCE("Guidance", "Guidance"), TRANSMISSION_FORMAT("Transmission Format", "Transmission Format"), POPULATIONS("Populations", "Populations"), SUPPLEMENTAL_DATA_ELEMENTS("Supplemental Data Elements", "Supplemental Data Elements"), MEASURE_SET("Measure Set", "Measure Set"); private String displayName; private String abbreviatedName; MeasureDetailsItems(String abbreviatedName, String displayName) { this.abbreviatedName = abbreviatedName; this.displayName = displayName; } public String displayName() { return displayName; } public String abbreviatedName() { return abbreviatedName; } } public enum PopulationItems implements MatDetailItem { INITIAL_POPULATION("Initial Population", "Initial Population", Stream.of(PROPORTION, RATIO, CONTINUOUS_VARIABLE, COHORT).collect(Collectors.toList())), MEASURE_POPULATION("Measure Population", "Measure Population", Stream.of(CONTINUOUS_VARIABLE).collect(Collectors.toList())), MEASURE_POPULATION_EXCLUSIONS("Measure Population Exclusions", "Measure Population Exclusions", Stream.of(CONTINUOUS_VARIABLE).collect(Collectors.toList())), DENOMINATOR("Denominator", "Denominator", Stream.of(PROPORTION, RATIO).collect(Collectors.toList())), DENOMINATOR_EXCLUSIONS("Denominator Exclusions", "Denominator Exclusions", Stream.of(PROPORTION, RATIO).collect(Collectors.toList())), NUMERATOR("Numerator", "Numerator", Stream.of(PROPORTION, RATIO).collect(Collectors.toList())), NUMERATOR_EXCLUSIONS("Numerator Exclusions", "Numerator Exclusions", Stream.of(PROPORTION, RATIO).collect(Collectors.toList())), DENOMINATOR_EXCEPTIONS("Denominator Exceptions", "Denominator Exceptions", Stream.of(PROPORTION).collect(Collectors.toList())), MEASURE_OBSERVATIONS("Measure Observations", "Measure Observations", Stream.of(CONTINUOUS_VARIABLE, RATIO).collect(Collectors.toList())); private String displayName; private String abbreviatedName; private List<String> measureTypes; PopulationItems(String abbreviatedName, String displayName, List<String> measureTypes) { this.abbreviatedName = abbreviatedName; this.displayName = displayName; this.measureTypes = measureTypes; } @Override public String displayName() { return "Populations > " + displayName; } @Override public String abbreviatedName() { return abbreviatedName; } public List<String> getApplicableMeasureTypes() { return measureTypes; } } }
MeasureAuthoringTool/MeasureAuthoringTool_Release
mat/src/main/java/mat/client/shared/MeasureDetailsConstants.java
Java
cc0-1.0
3,950
@echo off rem THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF rem ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO rem THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A rem PARTICULAR PURPOSE. rem rem Copyright (c) Microsoft Corporation. All rights reserved. setlocal set error=0 rem set FX_PATH=C:\devtools\DirectX_SDK\Utilities\bin\x86 set FX_PATH=C:\devtools\DirectX\Utilities\bin\x86 rem Particles call :CompileShader%1 Particles Particles vs VS_Main call :CompileShader%1 Particles Particles ps PS_Main echo. if %error% == 0 ( echo Shaders compiled ok ) else ( echo There were shader compilation errors! ) endlocal exit /b :CompileShader set fxc=%FX_PATH%\fxc /nologo %1.hlsl /T%3_4_0 /Zi /Zpc /Qstrip_reflect /Qstrip_debug /E%4 /Fh%1_%4.h /Vn%2_%4 echo. echo %fxc% %fxc% || set error=1 exit /b
amecky/ds_arena
src/particles/compile_shader.bat
Batchfile
cc0-1.0
865
#ifndef dplyr_tools_tools_H #define dplyr_tools_tools_H #include <tools/debug.h> #include <tools/hash.h> #include <tools/match.h> #include <tools/pointer_vector.h> #include <tools/collapse.h> #include <tools/Quosure.h> #include <tools/utils.h> #endif
ColumbusCollaboratory/electron-quick-start
R-Portable-Win/library/dplyr/include/tools/tools.h
C
cc0-1.0
253