repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
gcarq/freqtrade
freqtrade/exchange/exchange.py
59586
# pragma pylint: disable=W0603 """ Cryptocurrency Exchanges support """ import asyncio import inspect import logging from copy import deepcopy from datetime import datetime, timezone from math import ceil from typing import Any, Dict, List, Optional, Tuple import arrow import ccxt import ccxt.async_support as ccxt_async from ccxt.base.decimal_to_precision import (ROUND_DOWN, ROUND_UP, TICK_SIZE, TRUNCATE, decimal_to_precision) from pandas import DataFrame from freqtrade.constants import ListPairsWithTimeframes from freqtrade.data.converter import ohlcv_to_dataframe, trades_dict_to_list from freqtrade.exceptions import (DDosProtection, ExchangeError, InsufficientFundsError, InvalidOrderException, OperationalException, RetryableOrderError, TemporaryError) from freqtrade.exchange.common import (API_FETCH_ORDER_RETRY_COUNT, BAD_EXCHANGES, retrier, retrier_async) from freqtrade.misc import deep_merge_dicts, safe_value_fallback2 CcxtModuleType = Any logger = logging.getLogger(__name__) class Exchange: _config: Dict = {} # Parameters to add directly to ccxt sync/async initialization. _ccxt_config: Dict = {} # Parameters to add directly to buy/sell calls (like agreeing to trading agreement) _params: Dict = {} # Dict to specify which options each exchange implements # This defines defaults, which can be selectively overridden by subclasses using _ft_has # or by specifying them in the configuration. _ft_has_default: Dict = { "stoploss_on_exchange": False, "order_time_in_force": ["gtc"], "ohlcv_candle_limit": 500, "ohlcv_partial_candle": True, "trades_pagination": "time", # Possible are "time" or "id" "trades_pagination_arg": "since", "l2_limit_range": None, } _ft_has: Dict = {} def __init__(self, config: Dict[str, Any], validate: bool = True) -> None: """ Initializes this module with the given config, it does basic validation whether the specified exchange and pairs are valid. :return: None """ self._api: ccxt.Exchange = None self._api_async: ccxt_async.Exchange = None self._config.update(config) # Holds last candle refreshed time of each pair self._pairs_last_refresh_time: Dict[Tuple[str, str], int] = {} # Timestamp of last markets refresh self._last_markets_refresh: int = 0 # Holds candles self._klines: Dict[Tuple[str, str], DataFrame] = {} # Holds all open sell orders for dry_run self._dry_run_open_orders: Dict[str, Any] = {} if config['dry_run']: logger.info('Instance is running with dry_run enabled') logger.info(f"Using CCXT {ccxt.__version__}") exchange_config = config['exchange'] # Deep merge ft_has with default ft_has options self._ft_has = deep_merge_dicts(self._ft_has, deepcopy(self._ft_has_default)) if exchange_config.get('_ft_has_params'): self._ft_has = deep_merge_dicts(exchange_config.get('_ft_has_params'), self._ft_has) logger.info("Overriding exchange._ft_has with config params, result: %s", self._ft_has) # Assign this directly for easy access self._ohlcv_candle_limit = self._ft_has['ohlcv_candle_limit'] self._ohlcv_partial_candle = self._ft_has['ohlcv_partial_candle'] self._trades_pagination = self._ft_has['trades_pagination'] self._trades_pagination_arg = self._ft_has['trades_pagination_arg'] # Initialize ccxt objects ccxt_config = self._ccxt_config.copy() ccxt_config = deep_merge_dicts(exchange_config.get('ccxt_config', {}), ccxt_config) ccxt_config = deep_merge_dicts(exchange_config.get('ccxt_sync_config', {}), ccxt_config) self._api = self._init_ccxt(exchange_config, ccxt_kwargs=ccxt_config) ccxt_async_config = self._ccxt_config.copy() ccxt_async_config = deep_merge_dicts(exchange_config.get('ccxt_config', {}), ccxt_async_config) ccxt_async_config = deep_merge_dicts(exchange_config.get('ccxt_async_config', {}), ccxt_async_config) self._api_async = self._init_ccxt( exchange_config, ccxt_async, ccxt_kwargs=ccxt_async_config) logger.info('Using Exchange "%s"', self.name) if validate: # Check if timeframe is available self.validate_timeframes(config.get('timeframe')) # Initial markets load self._load_markets() # Check if all pairs are available self.validate_stakecurrency(config['stake_currency']) if not exchange_config.get('skip_pair_validation'): self.validate_pairs(config['exchange']['pair_whitelist']) self.validate_ordertypes(config.get('order_types', {})) self.validate_order_time_in_force(config.get('order_time_in_force', {})) self.validate_required_startup_candles(config.get('startup_candle_count', 0)) # Converts the interval provided in minutes in config to seconds self.markets_refresh_interval: int = exchange_config.get( "markets_refresh_interval", 60) * 60 def __del__(self): """ Destructor - clean up async stuff """ logger.debug("Exchange object destroyed, closing async loop") if self._api_async and inspect.iscoroutinefunction(self._api_async.close): asyncio.get_event_loop().run_until_complete(self._api_async.close()) def _init_ccxt(self, exchange_config: Dict[str, Any], ccxt_module: CcxtModuleType = ccxt, ccxt_kwargs: dict = None) -> ccxt.Exchange: """ Initialize ccxt with given config and return valid ccxt instance. """ # Find matching class for the given exchange name name = exchange_config['name'] if not is_exchange_known_ccxt(name, ccxt_module): raise OperationalException(f'Exchange {name} is not supported by ccxt') ex_config = { 'apiKey': exchange_config.get('key'), 'secret': exchange_config.get('secret'), 'password': exchange_config.get('password'), 'uid': exchange_config.get('uid', ''), } if ccxt_kwargs: logger.info('Applying additional ccxt config: %s', ccxt_kwargs) ex_config.update(ccxt_kwargs) try: api = getattr(ccxt_module, name.lower())(ex_config) except (KeyError, AttributeError) as e: raise OperationalException(f'Exchange {name} is not supported') from e except ccxt.BaseError as e: raise OperationalException(f"Initialization of ccxt failed. Reason: {e}") from e self.set_sandbox(api, exchange_config, name) return api @property def name(self) -> str: """exchange Name (from ccxt)""" return self._api.name @property def id(self) -> str: """exchange ccxt id""" return self._api.id @property def timeframes(self) -> List[str]: return list((self._api.timeframes or {}).keys()) @property def ohlcv_candle_limit(self) -> int: """exchange ohlcv candle limit""" return int(self._ohlcv_candle_limit) @property def markets(self) -> Dict: """exchange ccxt markets""" if not self._api.markets: logger.info("Markets were not loaded. Loading them now..") self._load_markets() return self._api.markets @property def precisionMode(self) -> str: """exchange ccxt precisionMode""" return self._api.precisionMode def get_markets(self, base_currencies: List[str] = None, quote_currencies: List[str] = None, pairs_only: bool = False, active_only: bool = False) -> Dict: """ Return exchange ccxt markets, filtered out by base currency and quote currency if this was requested in parameters. TODO: consider moving it to the Dataprovider """ markets = self.markets if not markets: raise OperationalException("Markets were not loaded.") if base_currencies: markets = {k: v for k, v in markets.items() if v['base'] in base_currencies} if quote_currencies: markets = {k: v for k, v in markets.items() if v['quote'] in quote_currencies} if pairs_only: markets = {k: v for k, v in markets.items() if self.market_is_tradable(v)} if active_only: markets = {k: v for k, v in markets.items() if market_is_active(v)} return markets def get_quote_currencies(self) -> List[str]: """ Return a list of supported quote currencies """ markets = self.markets return sorted(set([x['quote'] for _, x in markets.items()])) def get_pair_quote_currency(self, pair: str) -> str: """ Return a pair's quote currency """ return self.markets.get(pair, {}).get('quote', '') def get_pair_base_currency(self, pair: str) -> str: """ Return a pair's quote currency """ return self.markets.get(pair, {}).get('base', '') def market_is_tradable(self, market: Dict[str, Any]) -> bool: """ Check if the market symbol is tradable by Freqtrade. By default, checks if it's splittable by `/` and both sides correspond to base / quote """ symbol_parts = market['symbol'].split('/') return (len(symbol_parts) == 2 and len(symbol_parts[0]) > 0 and len(symbol_parts[1]) > 0 and symbol_parts[0] == market.get('base') and symbol_parts[1] == market.get('quote') ) def klines(self, pair_interval: Tuple[str, str], copy: bool = True) -> DataFrame: if pair_interval in self._klines: return self._klines[pair_interval].copy() if copy else self._klines[pair_interval] else: return DataFrame() def set_sandbox(self, api: ccxt.Exchange, exchange_config: dict, name: str) -> None: if exchange_config.get('sandbox'): if api.urls.get('test'): api.urls['api'] = api.urls['test'] logger.info("Enabled Sandbox API on %s", name) else: logger.warning( f"No Sandbox URL in CCXT for {name}, exiting. Please check your config.json") raise OperationalException(f'Exchange {name} does not provide a sandbox api') def _load_async_markets(self, reload: bool = False) -> None: try: if self._api_async: asyncio.get_event_loop().run_until_complete( self._api_async.load_markets(reload=reload)) except (asyncio.TimeoutError, ccxt.BaseError) as e: logger.warning('Could not load async markets. Reason: %s', e) return def _load_markets(self) -> None: """ Initialize markets both sync and async """ try: self._api.load_markets() self._load_async_markets() self._last_markets_refresh = arrow.utcnow().int_timestamp except ccxt.BaseError as e: logger.warning('Unable to initialize markets. Reason: %s', e) def reload_markets(self) -> None: """Reload markets both sync and async if refresh interval has passed """ # Check whether markets have to be reloaded if (self._last_markets_refresh > 0) and ( self._last_markets_refresh + self.markets_refresh_interval > arrow.utcnow().int_timestamp): return None logger.debug("Performing scheduled market reload..") try: self._api.load_markets(reload=True) # Also reload async markets to avoid issues with newly listed pairs self._load_async_markets(reload=True) self._last_markets_refresh = arrow.utcnow().int_timestamp except ccxt.BaseError: logger.exception("Could not reload markets.") def validate_stakecurrency(self, stake_currency: str) -> None: """ Checks stake-currency against available currencies on the exchange. :param stake_currency: Stake-currency to validate :raise: OperationalException if stake-currency is not available. """ quote_currencies = self.get_quote_currencies() if stake_currency not in quote_currencies: raise OperationalException( f"{stake_currency} is not available as stake on {self.name}. " f"Available currencies are: {', '.join(quote_currencies)}") def validate_pairs(self, pairs: List[str]) -> None: """ Checks if all given pairs are tradable on the current exchange. :param pairs: list of pairs :raise: OperationalException if one pair is not available :return: None """ if not self.markets: logger.warning('Unable to validate pairs (assuming they are correct).') return invalid_pairs = [] for pair in pairs: # Note: ccxt has BaseCurrency/QuoteCurrency format for pairs # TODO: add a support for having coins in BTC/USDT format if self.markets and pair not in self.markets: raise OperationalException( f'Pair {pair} is not available on {self.name}. ' f'Please remove {pair} from your whitelist.') # From ccxt Documentation: # markets.info: An associative array of non-common market properties, # including fees, rates, limits and other general market information. # The internal info array is different for each particular market, # its contents depend on the exchange. # It can also be a string or similar ... so we need to verify that first. elif (isinstance(self.markets[pair].get('info', None), dict) and self.markets[pair].get('info', {}).get('IsRestricted', False)): # Warn users about restricted pairs in whitelist. # We cannot determine reliably if Users are affected. logger.warning(f"Pair {pair} is restricted for some users on this exchange." f"Please check if you are impacted by this restriction " f"on the exchange and eventually remove {pair} from your whitelist.") if (self._config['stake_currency'] and self.get_pair_quote_currency(pair) != self._config['stake_currency']): invalid_pairs.append(pair) if invalid_pairs: raise OperationalException( f"Stake-currency '{self._config['stake_currency']}' not compatible with " f"pair-whitelist. Please remove the following pairs: {invalid_pairs}") def get_valid_pair_combination(self, curr_1: str, curr_2: str) -> str: """ Get valid pair combination of curr_1 and curr_2 by trying both combinations. """ for pair in [f"{curr_1}/{curr_2}", f"{curr_2}/{curr_1}"]: if pair in self.markets and self.markets[pair].get('active'): return pair raise ExchangeError(f"Could not combine {curr_1} and {curr_2} to get a valid pair.") def validate_timeframes(self, timeframe: Optional[str]) -> None: """ Check if timeframe from config is a supported timeframe on the exchange """ if not hasattr(self._api, "timeframes") or self._api.timeframes is None: # If timeframes attribute is missing (or is None), the exchange probably # has no fetchOHLCV method. # Therefore we also show that. raise OperationalException( f"The ccxt library does not provide the list of timeframes " f"for the exchange \"{self.name}\" and this exchange " f"is therefore not supported. ccxt fetchOHLCV: {self.exchange_has('fetchOHLCV')}") if timeframe and (timeframe not in self.timeframes): raise OperationalException( f"Invalid timeframe '{timeframe}'. This exchange supports: {self.timeframes}") if timeframe and timeframe_to_minutes(timeframe) < 1: raise OperationalException("Timeframes < 1m are currently not supported by Freqtrade.") def validate_ordertypes(self, order_types: Dict) -> None: """ Checks if order-types configured in strategy/config are supported """ if any(v == 'market' for k, v in order_types.items()): if not self.exchange_has('createMarketOrder'): raise OperationalException( f'Exchange {self.name} does not support market orders.') if (order_types.get("stoploss_on_exchange") and not self._ft_has.get("stoploss_on_exchange", False)): raise OperationalException( f'On exchange stoploss is not supported for {self.name}.' ) def validate_order_time_in_force(self, order_time_in_force: Dict) -> None: """ Checks if order time in force configured in strategy/config are supported """ if any(v not in self._ft_has["order_time_in_force"] for k, v in order_time_in_force.items()): raise OperationalException( f'Time in force policies are not supported for {self.name} yet.') def validate_required_startup_candles(self, startup_candles: int) -> None: """ Checks if required startup_candles is more than ohlcv_candle_limit. Requires a grace-period of 5 candles - so a startup-period up to 494 is allowed by default. """ if startup_candles + 5 > self._ft_has['ohlcv_candle_limit']: raise OperationalException( f"This strategy requires {startup_candles} candles to start. " f"{self.name} only provides {self._ft_has['ohlcv_candle_limit']}.") def exchange_has(self, endpoint: str) -> bool: """ Checks if exchange implements a specific API endpoint. Wrapper around ccxt 'has' attribute :param endpoint: Name of endpoint (e.g. 'fetchOHLCV', 'fetchTickers') :return: bool """ return endpoint in self._api.has and self._api.has[endpoint] def amount_to_precision(self, pair: str, amount: float) -> float: ''' Returns the amount to buy or sell to a precision the Exchange accepts Reimplementation of ccxt internal methods - ensuring we can test the result is correct based on our definitions. ''' if self.markets[pair]['precision']['amount']: amount = float(decimal_to_precision(amount, rounding_mode=TRUNCATE, precision=self.markets[pair]['precision']['amount'], counting_mode=self.precisionMode, )) return amount def price_to_precision(self, pair: str, price: float) -> float: ''' Returns the price rounded up to the precision the Exchange accepts. Partial Reimplementation of ccxt internal method decimal_to_precision(), which does not support rounding up TODO: If ccxt supports ROUND_UP for decimal_to_precision(), we could remove this and align with amount_to_precision(). Rounds up ''' if self.markets[pair]['precision']['price']: # price = float(decimal_to_precision(price, rounding_mode=ROUND, # precision=self.markets[pair]['precision']['price'], # counting_mode=self.precisionMode, # )) if self.precisionMode == TICK_SIZE: precision = self.markets[pair]['precision']['price'] missing = price % precision if missing != 0: price = price - missing + precision else: symbol_prec = self.markets[pair]['precision']['price'] big_price = price * pow(10, symbol_prec) price = ceil(big_price) / pow(10, symbol_prec) return price def price_get_one_pip(self, pair: str, price: float) -> float: """ Get's the "1 pip" value for this pair. Used in PriceFilter to calculate the 1pip movements. """ precision = self.markets[pair]['precision']['price'] if self.precisionMode == TICK_SIZE: return precision else: return 1 / pow(10, precision) def dry_run_order(self, pair: str, ordertype: str, side: str, amount: float, rate: float, params: Dict = {}) -> Dict[str, Any]: order_id = f'dry_run_{side}_{datetime.now().timestamp()}' _amount = self.amount_to_precision(pair, amount) dry_order = { 'id': order_id, 'symbol': pair, 'price': rate, 'average': rate, 'amount': _amount, 'cost': _amount * rate, 'type': ordertype, 'side': side, 'remaining': _amount, 'datetime': arrow.utcnow().isoformat(), 'timestamp': int(arrow.utcnow().int_timestamp * 1000), 'status': "closed" if ordertype == "market" else "open", 'fee': None, 'info': {} } self._store_dry_order(dry_order, pair) # Copy order and close it - so the returned order is open unless it's a market order return dry_order def _store_dry_order(self, dry_order: Dict, pair: str) -> None: closed_order = dry_order.copy() if closed_order['type'] in ["market", "limit"]: closed_order.update({ 'status': 'closed', 'filled': closed_order['amount'], 'remaining': 0, 'fee': { 'currency': self.get_pair_quote_currency(pair), 'cost': dry_order['cost'] * self.get_fee(pair), 'rate': self.get_fee(pair) } }) if closed_order["type"] in ["stop_loss_limit", "stop-loss-limit"]: closed_order["info"].update({"stopPrice": closed_order["price"]}) self._dry_run_open_orders[closed_order["id"]] = closed_order def create_order(self, pair: str, ordertype: str, side: str, amount: float, rate: float, params: Dict = {}) -> Dict: try: # Set the precision for amount and price(rate) as accepted by the exchange amount = self.amount_to_precision(pair, amount) needs_price = (ordertype != 'market' or self._api.options.get("createMarketBuyOrderRequiresPrice", False)) rate_for_order = self.price_to_precision(pair, rate) if needs_price else None return self._api.create_order(pair, ordertype, side, amount, rate_for_order, params) except ccxt.InsufficientFunds as e: raise InsufficientFundsError( f'Insufficient funds to create {ordertype} {side} order on market {pair}. ' f'Tried to {side} amount {amount} at rate {rate}.' f'Message: {e}') from e except ccxt.InvalidOrder as e: raise ExchangeError( f'Could not create {ordertype} {side} order on market {pair}. ' f'Tried to {side} amount {amount} at rate {rate}. ' f'Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not place {side} order due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e def buy(self, pair: str, ordertype: str, amount: float, rate: float, time_in_force: str) -> Dict: if self._config['dry_run']: dry_order = self.dry_run_order(pair, ordertype, "buy", amount, rate) return dry_order params = self._params.copy() if time_in_force != 'gtc' and ordertype != 'market': params.update({'timeInForce': time_in_force}) return self.create_order(pair, ordertype, 'buy', amount, rate, params) def sell(self, pair: str, ordertype: str, amount: float, rate: float, time_in_force: str = 'gtc') -> Dict: if self._config['dry_run']: dry_order = self.dry_run_order(pair, ordertype, "sell", amount, rate) return dry_order params = self._params.copy() if time_in_force != 'gtc' and ordertype != 'market': params.update({'timeInForce': time_in_force}) return self.create_order(pair, ordertype, 'sell', amount, rate, params) def stoploss_adjust(self, stop_loss: float, order: Dict) -> bool: """ Verify stop_loss against stoploss-order value (limit or price) Returns True if adjustment is necessary. """ raise OperationalException(f"stoploss is not implemented for {self.name}.") def stoploss(self, pair: str, amount: float, stop_price: float, order_types: Dict) -> Dict: """ creates a stoploss order. The precise ordertype is determined by the order_types dict or exchange default. Since ccxt does not unify stoploss-limit orders yet, this needs to be implemented in each exchange's subclass. The exception below should never raise, since we disallow starting the bot in validate_ordertypes() Note: Changes to this interface need to be applied to all sub-classes too. """ raise OperationalException(f"stoploss is not implemented for {self.name}.") @retrier def get_balance(self, currency: str) -> float: if self._config['dry_run']: return self._config['dry_run_wallet'] # ccxt exception is already handled by get_balances balances = self.get_balances() balance = balances.get(currency) if balance is None: raise TemporaryError( f'Could not get {currency} balance due to malformed exchange response: {balances}') return balance['free'] @retrier def get_balances(self) -> dict: if self._config['dry_run']: return {} try: balances = self._api.fetch_balance() # Remove additional info from ccxt results balances.pop("info", None) balances.pop("free", None) balances.pop("total", None) balances.pop("used", None) return balances except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not get balance due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e @retrier def get_tickers(self) -> Dict: try: return self._api.fetch_tickers() except ccxt.NotSupported as e: raise OperationalException( f'Exchange {self._api.name} does not support fetching tickers in batch. ' f'Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not load tickers due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e @retrier def fetch_ticker(self, pair: str) -> dict: try: if (pair not in self._api.markets or self._api.markets[pair].get('active', False) is False): raise ExchangeError(f"Pair {pair} not available") data = self._api.fetch_ticker(pair) return data except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not load ticker due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e def get_historic_ohlcv(self, pair: str, timeframe: str, since_ms: int) -> List: """ Get candle history using asyncio and returns the list of candles. Handles all async work for this. Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. :param pair: Pair to download :param timeframe: Timeframe to get data for :param since_ms: Timestamp in milliseconds to get history from :return: List with candle (OHLCV) data """ return asyncio.get_event_loop().run_until_complete( self._async_get_historic_ohlcv(pair=pair, timeframe=timeframe, since_ms=since_ms)) def get_historic_ohlcv_as_df(self, pair: str, timeframe: str, since_ms: int) -> DataFrame: """ Minimal wrapper around get_historic_ohlcv - converting the result into a dataframe :param pair: Pair to download :param timeframe: Timeframe to get data for :param since_ms: Timestamp in milliseconds to get history from :return: OHLCV DataFrame """ ticks = self.get_historic_ohlcv(pair, timeframe, since_ms=since_ms) return ohlcv_to_dataframe(ticks, timeframe, pair=pair, fill_missing=True, drop_incomplete=self._ohlcv_partial_candle) async def _async_get_historic_ohlcv(self, pair: str, timeframe: str, since_ms: int) -> List: """ Download historic ohlcv """ one_call = timeframe_to_msecs(timeframe) * self._ohlcv_candle_limit logger.debug( "one_call: %s msecs (%s)", one_call, arrow.utcnow().shift(seconds=one_call // 1000).humanize(only_distance=True) ) input_coroutines = [self._async_get_candle_history( pair, timeframe, since) for since in range(since_ms, arrow.utcnow().int_timestamp * 1000, one_call)] results = await asyncio.gather(*input_coroutines, return_exceptions=True) # Combine gathered results data: List = [] for res in results: if isinstance(res, Exception): logger.warning("Async code raised an exception: %s", res.__class__.__name__) continue # Deconstruct tuple if it's not an exception p, _, new_data = res if p == pair: data.extend(new_data) # Sort data again after extending the result - above calls return in "async order" data = sorted(data, key=lambda x: x[0]) logger.info("Downloaded data for %s with length %s.", pair, len(data)) return data def refresh_latest_ohlcv(self, pair_list: ListPairsWithTimeframes, *, since_ms: Optional[int] = None, cache: bool = True ) -> Dict[Tuple[str, str], DataFrame]: """ Refresh in-memory OHLCV asynchronously and set `_klines` with the result Loops asynchronously over pair_list and downloads all pairs async (semi-parallel). Only used in the dataprovider.refresh() method. :param pair_list: List of 2 element tuples containing pair, interval to refresh :param since_ms: time since when to download, in milliseconds :param cache: Assign result to _klines. Usefull for one-off downloads like for pairlists :return: Dict of [{(pair, timeframe): Dataframe}] """ logger.debug("Refreshing candle (OHLCV) data for %d pairs", len(pair_list)) input_coroutines = [] # Gather coroutines to run for pair, timeframe in set(pair_list): if (not ((pair, timeframe) in self._klines) or self._now_is_time_to_refresh(pair, timeframe)): input_coroutines.append(self._async_get_candle_history(pair, timeframe, since_ms=since_ms)) else: logger.debug( "Using cached candle (OHLCV) data for pair %s, timeframe %s ...", pair, timeframe ) results = asyncio.get_event_loop().run_until_complete( asyncio.gather(*input_coroutines, return_exceptions=True)) results_df = {} # handle caching for res in results: if isinstance(res, Exception): logger.warning("Async code raised an exception: %s", res.__class__.__name__) continue # Deconstruct tuple (has 3 elements) pair, timeframe, ticks = res # keeping last candle time as last refreshed time of the pair if ticks: self._pairs_last_refresh_time[(pair, timeframe)] = ticks[-1][0] // 1000 # keeping parsed dataframe in cache ohlcv_df = ohlcv_to_dataframe( ticks, timeframe, pair=pair, fill_missing=True, drop_incomplete=self._ohlcv_partial_candle) results_df[(pair, timeframe)] = ohlcv_df if cache: self._klines[(pair, timeframe)] = ohlcv_df return results_df def _now_is_time_to_refresh(self, pair: str, timeframe: str) -> bool: # Timeframe in seconds interval_in_sec = timeframe_to_seconds(timeframe) return not ((self._pairs_last_refresh_time.get((pair, timeframe), 0) + interval_in_sec) >= arrow.utcnow().int_timestamp) @retrier_async async def _async_get_candle_history(self, pair: str, timeframe: str, since_ms: Optional[int] = None) -> Tuple[str, str, List]: """ Asynchronously get candle history data using fetch_ohlcv returns tuple: (pair, timeframe, ohlcv_list) """ try: # Fetch OHLCV asynchronously s = '(' + arrow.get(since_ms // 1000).isoformat() + ') ' if since_ms is not None else '' logger.debug( "Fetching pair %s, interval %s, since %s %s...", pair, timeframe, since_ms, s ) data = await self._api_async.fetch_ohlcv(pair, timeframe=timeframe, since=since_ms, limit=self._ohlcv_candle_limit) # Some exchanges sort OHLCV in ASC order and others in DESC. # Ex: Bittrex returns the list of OHLCV in ASC order (oldest first, newest last) # while GDAX returns the list of OHLCV in DESC order (newest first, oldest last) # Only sort if necessary to save computing time try: if data and data[0][0] > data[-1][0]: data = sorted(data, key=lambda x: x[0]) except IndexError: logger.exception("Error loading %s. Result was %s.", pair, data) return pair, timeframe, [] logger.debug("Done fetching pair %s, interval %s ...", pair, timeframe) return pair, timeframe, data except ccxt.NotSupported as e: raise OperationalException( f'Exchange {self._api.name} does not support fetching historical ' f'candle (OHLCV) data. Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError(f'Could not fetch historical candle (OHLCV) data ' f'for pair {pair} due to {e.__class__.__name__}. ' f'Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(f'Could not fetch historical candle (OHLCV) data ' f'for pair {pair}. Message: {e}') from e @retrier_async async def _async_fetch_trades(self, pair: str, since: Optional[int] = None, params: Optional[dict] = None) -> List[List]: """ Asyncronously gets trade history using fetch_trades. Handles exchange errors, does one call to the exchange. :param pair: Pair to fetch trade data for :param since: Since as integer timestamp in milliseconds returns: List of dicts containing trades """ try: # fetch trades asynchronously if params: logger.debug("Fetching trades for pair %s, params: %s ", pair, params) trades = await self._api_async.fetch_trades(pair, params=params, limit=1000) else: logger.debug( "Fetching trades for pair %s, since %s %s...", pair, since, '(' + arrow.get(since // 1000).isoformat() + ') ' if since is not None else '' ) trades = await self._api_async.fetch_trades(pair, since=since, limit=1000) return trades_dict_to_list(trades) except ccxt.NotSupported as e: raise OperationalException( f'Exchange {self._api.name} does not support fetching historical trade data.' f'Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError(f'Could not load trade history due to {e.__class__.__name__}. ' f'Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(f'Could not fetch trade data. Msg: {e}') from e async def _async_get_trade_history_id(self, pair: str, until: int, since: Optional[int] = None, from_id: Optional[str] = None) -> Tuple[str, List[List]]: """ Asyncronously gets trade history using fetch_trades use this when exchange uses id-based iteration (check `self._trades_pagination`) :param pair: Pair to fetch trade data for :param since: Since as integer timestamp in milliseconds :param until: Until as integer timestamp in milliseconds :param from_id: Download data starting with ID (if id is known). Ignores "since" if set. returns tuple: (pair, trades-list) """ trades: List[List] = [] if not from_id: # Fetch first elements using timebased method to get an ID to paginate on # Depending on the Exchange, this can introduce a drift at the start of the interval # of up to an hour. # e.g. Binance returns the "last 1000" candles within a 1h time interval # - so we will miss the first trades. t = await self._async_fetch_trades(pair, since=since) # DEFAULT_TRADES_COLUMNS: 0 -> timestamp # DEFAULT_TRADES_COLUMNS: 1 -> id from_id = t[-1][1] trades.extend(t[:-1]) while True: t = await self._async_fetch_trades(pair, params={self._trades_pagination_arg: from_id}) if len(t): # Skip last id since its the key for the next call trades.extend(t[:-1]) if from_id == t[-1][1] or t[-1][0] > until: logger.debug(f"Stopping because from_id did not change. " f"Reached {t[-1][0]} > {until}") # Reached the end of the defined-download period - add last trade as well. trades.extend(t[-1:]) break from_id = t[-1][1] else: break return (pair, trades) async def _async_get_trade_history_time(self, pair: str, until: int, since: Optional[int] = None) -> Tuple[str, List[List]]: """ Asyncronously gets trade history using fetch_trades, when the exchange uses time-based iteration (check `self._trades_pagination`) :param pair: Pair to fetch trade data for :param since: Since as integer timestamp in milliseconds :param until: Until as integer timestamp in milliseconds returns tuple: (pair, trades-list) """ trades: List[List] = [] # DEFAULT_TRADES_COLUMNS: 0 -> timestamp # DEFAULT_TRADES_COLUMNS: 1 -> id while True: t = await self._async_fetch_trades(pair, since=since) if len(t): since = t[-1][1] trades.extend(t) # Reached the end of the defined-download period if until and t[-1][0] > until: logger.debug( f"Stopping because until was reached. {t[-1][0]} > {until}") break else: break return (pair, trades) async def _async_get_trade_history(self, pair: str, since: Optional[int] = None, until: Optional[int] = None, from_id: Optional[str] = None) -> Tuple[str, List[List]]: """ Async wrapper handling downloading trades using either time or id based methods. """ logger.debug(f"_async_get_trade_history(), pair: {pair}, " f"since: {since}, until: {until}, from_id: {from_id}") if until is None: until = ccxt.Exchange.milliseconds() logger.debug(f"Exchange milliseconds: {until}") if self._trades_pagination == 'time': return await self._async_get_trade_history_time( pair=pair, since=since, until=until) elif self._trades_pagination == 'id': return await self._async_get_trade_history_id( pair=pair, since=since, until=until, from_id=from_id ) else: raise OperationalException(f"Exchange {self.name} does use neither time, " f"nor id based pagination") def get_historic_trades(self, pair: str, since: Optional[int] = None, until: Optional[int] = None, from_id: Optional[str] = None) -> Tuple[str, List]: """ Get trade history data using asyncio. Handles all async work and returns the list of candles. Async over one pair, assuming we get `self._ohlcv_candle_limit` candles per call. :param pair: Pair to download :param since: Timestamp in milliseconds to get history from :param until: Timestamp in milliseconds. Defaults to current timestamp if not defined. :param from_id: Download data starting with ID (if id is known) :returns List of trade data """ if not self.exchange_has("fetchTrades"): raise OperationalException("This exchange does not suport downloading Trades.") return asyncio.get_event_loop().run_until_complete( self._async_get_trade_history(pair=pair, since=since, until=until, from_id=from_id)) def check_order_canceled_empty(self, order: Dict) -> bool: """ Verify if an order has been cancelled without being partially filled :param order: Order dict as returned from fetch_order() :return: True if order has been cancelled without being filled, False otherwise. """ return order.get('status') in ('closed', 'canceled') and order.get('filled') == 0.0 @retrier def cancel_order(self, order_id: str, pair: str) -> Dict: if self._config['dry_run']: order = self._dry_run_open_orders.get(order_id) if order: order.update({'status': 'canceled', 'filled': 0.0, 'remaining': order['amount']}) return order else: return {} try: return self._api.cancel_order(order_id, pair) except ccxt.InvalidOrder as e: raise InvalidOrderException( f'Could not cancel order. Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not cancel order due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e # Assign method to cancel_stoploss_order to allow easy overriding in other classes cancel_stoploss_order = cancel_order def is_cancel_order_result_suitable(self, corder) -> bool: if not isinstance(corder, dict): return False required = ('fee', 'status', 'amount') return all(k in corder for k in required) def cancel_order_with_result(self, order_id: str, pair: str, amount: float) -> Dict: """ Cancel order returning a result. Creates a fake result if cancel order returns a non-usable result and fetch_order does not work (certain exchanges don't return cancelled orders) :param order_id: Orderid to cancel :param pair: Pair corresponding to order_id :param amount: Amount to use for fake response :return: Result from either cancel_order if usable, or fetch_order """ try: corder = self.cancel_order(order_id, pair) if self.is_cancel_order_result_suitable(corder): return corder except InvalidOrderException: logger.warning(f"Could not cancel order {order_id} for {pair}.") try: order = self.fetch_order(order_id, pair) except InvalidOrderException: logger.warning(f"Could not fetch cancelled order {order_id}.") order = {'fee': {}, 'status': 'canceled', 'amount': amount, 'info': {}} return order @retrier(retries=API_FETCH_ORDER_RETRY_COUNT) def fetch_order(self, order_id: str, pair: str) -> Dict: if self._config['dry_run']: try: order = self._dry_run_open_orders[order_id] return order except KeyError as e: # Gracefully handle errors with dry-run orders. raise InvalidOrderException( f'Tried to get an invalid dry-run-order (id: {order_id}). Message: {e}') from e try: return self._api.fetch_order(order_id, pair) except ccxt.OrderNotFound as e: raise RetryableOrderError( f'Order not found (pair: {pair} id: {order_id}). Message: {e}') from e except ccxt.InvalidOrder as e: raise InvalidOrderException( f'Tried to get an invalid order (pair: {pair} id: {order_id}). Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not get order due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e # Assign method to fetch_stoploss_order to allow easy overriding in other classes fetch_stoploss_order = fetch_order def fetch_order_or_stoploss_order(self, order_id: str, pair: str, stoploss_order: bool = False) -> Dict: """ Simple wrapper calling either fetch_order or fetch_stoploss_order depending on the stoploss_order parameter :param stoploss_order: If true, uses fetch_stoploss_order, otherwise fetch_order. """ if stoploss_order: return self.fetch_stoploss_order(order_id, pair) return self.fetch_order(order_id, pair) @staticmethod def get_next_limit_in_list(limit: int, limit_range: Optional[List[int]]): """ Get next greater value in the list. Used by fetch_l2_order_book if the api only supports a limited range """ if not limit_range: return limit return min([x for x in limit_range if limit <= x] + [max(limit_range)]) @retrier def fetch_l2_order_book(self, pair: str, limit: int = 100) -> dict: """ Get L2 order book from exchange. Can be limited to a certain amount (if supported). Returns a dict in the format {'asks': [price, volume], 'bids': [price, volume]} """ limit1 = self.get_next_limit_in_list(limit, self._ft_has['l2_limit_range']) try: return self._api.fetch_l2_order_book(pair, limit1) except ccxt.NotSupported as e: raise OperationalException( f'Exchange {self._api.name} does not support fetching order book.' f'Message: {e}') from e except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not get order book due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e @retrier def get_trades_for_order(self, order_id: str, pair: str, since: datetime) -> List: """ Fetch Orders using the "fetch_my_trades" endpoint and filter them by order-id. The "since" argument passed in is coming from the database and is in UTC, as timezone-native datetime object. From the python documentation: > Naive datetime instances are assumed to represent local time Therefore, calling "since.timestamp()" will get the UTC timestamp, after applying the transformation from local timezone to UTC. This works for timezones UTC+ since then the result will contain trades from a few hours instead of from the last 5 seconds, however fails for UTC- timezones, since we're then asking for trades with a "since" argument in the future. :param order_id order_id: Order-id as given when creating the order :param pair: Pair the order is for :param since: datetime object of the order creation time. Assumes object is in UTC. """ if self._config['dry_run']: return [] if not self.exchange_has('fetchMyTrades'): return [] try: # Allow 5s offset to catch slight time offsets (discovered in #1185) # since needs to be int in milliseconds my_trades = self._api.fetch_my_trades( pair, int((since.replace(tzinfo=timezone.utc).timestamp() - 5) * 1000)) matched_trades = [trade for trade in my_trades if trade['order'] == order_id] return matched_trades except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not get trades due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e @retrier def get_fee(self, symbol: str, type: str = '', side: str = '', amount: float = 1, price: float = 1, taker_or_maker: str = 'maker') -> float: try: # validate that markets are loaded before trying to get fee if self._api.markets is None or len(self._api.markets) == 0: self._api.load_markets() return self._api.calculate_fee(symbol=symbol, type=type, side=side, amount=amount, price=price, takerOrMaker=taker_or_maker)['rate'] except ccxt.DDoSProtection as e: raise DDosProtection(e) from e except (ccxt.NetworkError, ccxt.ExchangeError) as e: raise TemporaryError( f'Could not get fee info due to {e.__class__.__name__}. Message: {e}') from e except ccxt.BaseError as e: raise OperationalException(e) from e @staticmethod def order_has_fee(order: Dict) -> bool: """ Verifies if the passed in order dict has the needed keys to extract fees, and that these keys (currency, cost) are not empty. :param order: Order or trade (one trade) dict :return: True if the fee substructure contains currency and cost, false otherwise """ if not isinstance(order, dict): return False return ('fee' in order and order['fee'] is not None and (order['fee'].keys() >= {'currency', 'cost'}) and order['fee']['currency'] is not None and order['fee']['cost'] is not None ) def calculate_fee_rate(self, order: Dict) -> Optional[float]: """ Calculate fee rate if it's not given by the exchange. :param order: Order or trade (one trade) dict """ if order['fee'].get('rate') is not None: return order['fee'].get('rate') fee_curr = order['fee']['currency'] # Calculate fee based on order details if fee_curr in self.get_pair_base_currency(order['symbol']): # Base currency - divide by amount return round( order['fee']['cost'] / safe_value_fallback2(order, order, 'filled', 'amount'), 8) elif fee_curr in self.get_pair_quote_currency(order['symbol']): # Quote currency - divide by cost return round(order['fee']['cost'] / order['cost'], 8) if order['cost'] else None else: # If Fee currency is a different currency if not order['cost']: # If cost is None or 0.0 -> falsy, return None return None try: comb = self.get_valid_pair_combination(fee_curr, self._config['stake_currency']) tick = self.fetch_ticker(comb) fee_to_quote_rate = safe_value_fallback2(tick, tick, 'last', 'ask') return round((order['fee']['cost'] * fee_to_quote_rate) / order['cost'], 8) except ExchangeError: return None def extract_cost_curr_rate(self, order: Dict) -> Tuple[float, str, Optional[float]]: """ Extract tuple of cost, currency, rate. Requires order_has_fee to run first! :param order: Order or trade (one trade) dict :return: Tuple with cost, currency, rate of the given fee dict """ return (order['fee']['cost'], order['fee']['currency'], self.calculate_fee_rate(order)) def is_exchange_bad(exchange_name: str) -> bool: return exchange_name in BAD_EXCHANGES def get_exchange_bad_reason(exchange_name: str) -> str: return BAD_EXCHANGES.get(exchange_name, "") def is_exchange_known_ccxt(exchange_name: str, ccxt_module: CcxtModuleType = None) -> bool: return exchange_name in ccxt_exchanges(ccxt_module) def is_exchange_officially_supported(exchange_name: str) -> bool: return exchange_name in ['bittrex', 'binance', 'kraken'] def ccxt_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]: """ Return the list of all exchanges known to ccxt """ return ccxt_module.exchanges if ccxt_module is not None else ccxt.exchanges def available_exchanges(ccxt_module: CcxtModuleType = None) -> List[str]: """ Return exchanges available to the bot, i.e. non-bad exchanges in the ccxt list """ exchanges = ccxt_exchanges(ccxt_module) return [x for x in exchanges if not is_exchange_bad(x)] def timeframe_to_seconds(timeframe: str) -> int: """ Translates the timeframe interval value written in the human readable form ('1m', '5m', '1h', '1d', '1w', etc.) to the number of seconds for one timeframe interval. """ return ccxt.Exchange.parse_timeframe(timeframe) def timeframe_to_minutes(timeframe: str) -> int: """ Same as timeframe_to_seconds, but returns minutes. """ return ccxt.Exchange.parse_timeframe(timeframe) // 60 def timeframe_to_msecs(timeframe: str) -> int: """ Same as timeframe_to_seconds, but returns milliseconds. """ return ccxt.Exchange.parse_timeframe(timeframe) * 1000 def timeframe_to_prev_date(timeframe: str, date: datetime = None) -> datetime: """ Use Timeframe and determine last possible candle. :param timeframe: timeframe in string format (e.g. "5m") :param date: date to use. Defaults to utcnow() :returns: date of previous candle (with utc timezone) """ if not date: date = datetime.now(timezone.utc) new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000, ROUND_DOWN) // 1000 return datetime.fromtimestamp(new_timestamp, tz=timezone.utc) def timeframe_to_next_date(timeframe: str, date: datetime = None) -> datetime: """ Use Timeframe and determine next candle. :param timeframe: timeframe in string format (e.g. "5m") :param date: date to use. Defaults to utcnow() :returns: date of next candle (with utc timezone) """ if not date: date = datetime.now(timezone.utc) new_timestamp = ccxt.Exchange.round_timeframe(timeframe, date.timestamp() * 1000, ROUND_UP) // 1000 return datetime.fromtimestamp(new_timestamp, tz=timezone.utc) def market_is_active(market: Dict) -> bool: """ Return True if the market is active. """ # "It's active, if the active flag isn't explicitly set to false. If it's missing or # true then it's true. If it's undefined, then it's most likely true, but not 100% )" # See https://github.com/ccxt/ccxt/issues/4874, # https://github.com/ccxt/ccxt/issues/4075#issuecomment-434760520 return market.get('active', True) is not False
gpl-3.0
ray306/expy
stim/video.py
2544
from expy import shared from expy.response import * from .draw import getPos def loadVideo(path): ''' Load a video array Parameters ---------- path: str The file path of target video Returns ------- player: pyglet.media.Player playVideo() could use it ''' source = shared.pyglet.media.load(path) format = source.video_format if not format: raise ValueError('Unsupported file type') player = shared.pyglet.media.Player() player.queue(source) return player def playVideo(video, pauseKey=key_.SPACE, x=0.0, y=0.0, anchor_x='center', anchor_y='center'): ''' Play a loaded video Parameters ---------- video: pyglet.media.Player The player of target video pauseKey: (default: key_.SPACE) The name for pausekey x: int, or float (default:0.0) The x coordinate of text. If x is int, the coordinate would be pixel number to the left margin of screen; If x is float (-1~1), the coordinate would be percentage of half screen to the screen center. y: int, or float (default:0.0) The y coordinate of text. If y is int, the coordinate would be pixel number to the upper margin of screen; If y is float (-1~1), the coordinate would be percentage of half screen to the screen center. anchor_x: str (default:'center') The position benchmark on this object to the given x. Options: 'center', 'left', or 'right'. anchor_y: str (default:'center') The position benchmark on this object to the given y. Options: 'center', 'top', or 'bottom'. Returns ------- None ''' source = video.source duration = source.duration pos = getPos(x, y, source.video_format.width, source.video_format.height, anchor_x=anchor_x,anchor_y=anchor_x) @shared.win.event def on_draw(): shared.win.clear() if source and source.video_format: video.get_texture().blit(pos[0],pos[1]) video.play() startT = shared.time.time() while shared.time.time() - startT < duration: shared.pyglet.clock.tick() shared.win.dispatch_events() if len(shared.events)>0 and shared.events[0]['type']=='key_press' and shared.events[0]['key'] == pauseKey: shared.events = [] video.pause() key,rt = waitForResponse([pauseKey]) video.play() startT += rt shared.win.dispatch_event('on_draw') shared.win.flip() shared.win.clear()
gpl-3.0
Donkyhotay/MoonPy
zope/app/session/ftests.py
3899
############################################################################## # # Copyright (c) 2004 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## """Session functional tests. $Id: tests.py 26427 2004-07-12 16:05:02Z Zen $ """ import unittest from zope.component import provideHandler, getGlobalSiteManager from zope.app.folder import Folder from zope.app.publication.interfaces import IBeforeTraverseEvent from zope.app.testing.functional import BrowserTestCase from zope.app.zptpage.zptpage import ZPTPage from interfaces import ISession class ZPTSessionTest(BrowserTestCase): content = u''' <div tal:define=" session request/session:products.foo; dummy python:session.__setitem__( 'count', session.get('count', 0) + 1) " tal:omit-tag=""> <span tal:replace="session/count" /> </div> ''' def setUp(self): BrowserTestCase.setUp(self) page = ZPTPage() page.source = self.content page.evaluateInlineCode = True root = self.getRootFolder() root['page'] = page self.commit() def tearDown(self): root = self.getRootFolder() del root['page'] BrowserTestCase.tearDown(self) def fetch(self, page='/page'): response = self.publish(page) self.failUnlessEqual(response.getStatus(), 200) return response.getBody().strip() def test(self): response1 = self.fetch() self.failUnlessEqual(response1, u'1') response2 = self.fetch() self.failUnlessEqual(response2, u'2') response3 = self.fetch() self.failUnlessEqual(response3, u'3') class VirtualHostSessionTest(BrowserTestCase): def setUp(self): super(VirtualHostSessionTest, self).setUp() page = ZPTPage() page.source = (u'<div ' u'tal:define="session request/session:products.foo"/>') page.evaluateInlineCode = True root = self.getRootFolder() root['folder'] = Folder() root['folder']['page'] = page self.commit() provideHandler(self.accessSessionOnTraverse, (IBeforeTraverseEvent,)) def tearDown(self): getGlobalSiteManager().unregisterHandler(self.accessSessionOnTraverse, (IBeforeTraverseEvent,)) def accessSessionOnTraverse(self, event): session = ISession(event.request) def assertCookiePath(self, path): cookie = self.cookies.values()[0] self.assertEqual(cookie['path'], path) def testShortendPath(self): self.publish( '/++skin++Rotterdam/folder/++vh++http:localhost:80/++/page') self.assertCookiePath('/') def testLongerPath(self): self.publish( '/folder/++vh++http:localhost:80/foo/bar/++/page') self.assertCookiePath('/foo/bar') def testDifferentHostname(self): self.publish( '/folder/++vh++http:foo.bar:80/++/page') self.assertCookiePath('/') def test_suite(): return unittest.TestSuite(( unittest.makeSuite(ZPTSessionTest), unittest.makeSuite(VirtualHostSessionTest), )) if __name__ == '__main__': unittest.main() # vim: set filetype=python ts=4 sw=4 et si
gpl-3.0
3dct/open_iA
libs/guibase/io/iAAmiraMeshIO.cpp
13349
/************************************* open_iA ************************************ * * ********** A tool for visual analysis and processing of 3D CT images ********** * * *********************************************************************************** * * Copyright (C) 2016-2021 C. Heinzl, M. Reiter, A. Reh, W. Li, M. Arikan, Ar. & Al. * * Amirkhanov, J. Weissenböck, B. Fröhler, M. Schiwarth, P. Weinberger * * *********************************************************************************** * * 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 3 of the License, or (at your option) any later version. * * * * This program 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License along with this * * program. If not, see http://www.gnu.org/licenses/ * * *********************************************************************************** * * Contact: FH OÖ Forschungs & Entwicklungs GmbH, Campus Wels, CT-Gruppe, * * Stelzhamerstraße 23, 4600 Wels / Austria, Email: [email protected] * * ************************************************************************************/ #include "iAAmiraMeshIO.h" // base #include <iALog.h> #include <iAFileUtils.h> #include <vtkImageData.h> #include <QFile> #include <QString> #include <QStringList> #include <QTextStream> #include <cstdio> #include <cstring> #include <cassert> #include <stdexcept> // for runtime_error // based on code found here: // https://people.mpi-inf.mpg.de/~weinkauf/notes/amiramesh.html const int VTKLabelType = VTK_UNSIGNED_CHAR; typedef unsigned char LabelType; //! Find a string in the given buffer and return a pointer to the contents //! directly behind the SearchString. //! If not found, return the buffer. A subsequent sscanf() //! will fail then, but at least we return a decent pointer. const char* FindAndJump(const char* buffer, const char* SearchString) { const char* FoundLoc = strstr(buffer, SearchString); if (FoundLoc) return FoundLoc + strlen(SearchString); return buffer; } typedef char RawDataType; int decodeRLE(RawDataType* in, size_t inLength, RawDataType* out, size_t maxOutLength) { size_t curOutStart = 0; for (size_t curInIdx = 0; curInIdx < inLength; ++curInIdx) { int len = in[curInIdx]; // block length char c = in[curInIdx + 1]; // character if (c < 0) { c &= 0x7F; } if (len == EOF) return 1; // end of file if (c == EOF) return 0; // bad format if ((curOutStart + len) >= maxOutLength) { LOG(lvlWarn, "decodeRLE: More data in encoded array than fits into output!"); break; } for (int curSubOutIdx = 0; curSubOutIdx < len; curSubOutIdx++) { out[curOutStart + curSubOutIdx] = c; } curOutStart += len; } assert(curOutStart <= std::numeric_limits<int>::max()); return static_cast<int>(curOutStart); } namespace { QString const AmiraMeshFileTag("# AmiraMesh BINARY-LITTLE-ENDIAN 2.1"); QString const AvizoFileTag("# Avizo BINARY-LITTLE-ENDIAN 2.1"); const char * DefineLatticeToken = "define Lattice"; const char * BoundingBoxToken = "BoundingBox"; QString const ByteType("byte"); QString const FloatType("float"); } vtkSmartPointer<vtkImageData> iAAmiraMeshIO::Load(QString const & fileName) { FILE* fp = fopen( getLocalEncodingFileName(fileName).c_str(), "rb"); if (!fp) { throw std::runtime_error(QString("Could not open file '%1'.").arg(fileName).toStdString()); } //We read the first 2k bytes into memory to parse the header. //The fixed buffer size looks a bit like a hack, and it is one, but it gets the job done. const size_t MaxHeaderSize = 2047; char buffer[MaxHeaderSize +1]; size_t readBytes = fread(buffer, sizeof(char), MaxHeaderSize, fp); if (readBytes == 0 || ferror(fp) != 0) { fclose(fp); throw std::runtime_error(QString("Could not read header of Avizo/AmiraMesh file %1.").arg(MaxHeaderSize).arg(fileName).toStdString()); } buffer[readBytes-1] = '\0'; //The following string routines prefer null-terminated strings QString header(buffer); if (!header.startsWith(AmiraMeshFileTag) && !header.startsWith(AvizoFileTag)) { fclose(fp); throw std::runtime_error(QString("File %1 is not a proper Avizo/AmiraMesh file, it is missing the initial file tag.").arg(fileName).toStdString()); } //Find the Lattice definition, i.e., the dimensions of the uniform grid int xDim(0), yDim(0), zDim(0); sscanf(FindAndJump(buffer, DefineLatticeToken), "%d %d %d", &xDim, &yDim, &zDim); //LOG(lvlInfo, QString("Grid Dimensions: %1 %2 %3").arg(xDim).arg(yDim).arg(zDim)); //Find the BoundingBox float xmin(1.0f), ymin(1.0f), zmin(1.0f); float xmax(-1.0f), ymax(-1.0f), zmax(-1.0f); sscanf(FindAndJump(buffer, BoundingBoxToken), "%g %g %g %g %g %g", &xmin, &xmax, &ymin, &ymax, &zmin, &zmax); //LOG(lvlInfo, QString("BoundingBox: x=[%1...%2], y=[%3...%4], z=[%5...%6]") // .arg(xmin).arg(xmax).arg(ymin).arg(ymax).arg(zmin).arg(zmax)); //Is it a uniform grid? We need this only for the sanity check below. const bool bIsUniform = (strstr(buffer, "CoordType \"uniform\"") != nullptr); //LOG(lvlInfo, QString("GridType: %1").arg(bIsUniform ? "uniform" : "UNKNOWN")); //Type of the field: scalar, vector int NumComponents(0); int latticePos = header.indexOf("Lattice {"); int nextLineBreakPos = header.indexOf("\n", latticePos); int lineSize = nextLineBreakPos - latticePos; QString latticeLine = header.mid(latticePos, lineSize ); #if QT_VERSION < QT_VERSION_CHECK(5, 15, 0) QStringList latticeTokens = latticeLine.split(" ", QString::SkipEmptyParts); #else QStringList latticeTokens = latticeLine.split(" ", Qt::SkipEmptyParts); #endif // TODO more types? int dataType; QString dataTypeStr = latticeTokens[2]; if (dataTypeStr == ByteType) { NumComponents = 1; dataType = VTKLabelType; } else if (dataTypeStr == FloatType) { NumComponents = 1; dataType = VTK_FLOAT; } else if (dataTypeStr.startsWith(FloatType)) { //A field with more than one component, i.e., a vector field dataType = VTK_FLOAT; sscanf(FindAndJump(buffer, "Lattice { float["), "%d", &NumComponents); } else { fclose(fp); throw std::runtime_error(QString("Unknown pixel type '%1' (not yet implemented). Supported pixel types: byte (unsigned char), float.").arg(dataTypeStr).toStdString()); } const QString RLEMarker("HxByteRLE"); bool rleEncoded = latticeLine.contains(RLEMarker); size_t rawDataSize = 0; if (rleEncoded) { if (latticeTokens.size() < 6) { LOG(lvlWarn, QString("Expected at least 6 tokens in lattice line, only found %1.").arg(latticeTokens.size())); } int pos = latticeTokens[5].indexOf(RLEMarker); //int latticeLength = latticeTokens[5].length(); int sizePos = pos + RLEMarker.length() + 1; int sizeLen = latticeTokens[5].length() - pos - RLEMarker.length() - 2; QString dataLenStr = latticeTokens[5].mid(sizePos, sizeLen); rawDataSize = dataLenStr.toInt(); LOG(lvlInfo, QString("RLE encoded (%1 compressed bytes)").arg(rawDataSize)); } //LOG(lvlInfo, QString("Number of Components: %1").arg(NumComponents)); vtkImageData* imageData = vtkImageData::New(); imageData->SetDimensions(xDim, yDim, zDim); imageData->AllocateScalars(dataType, NumComponents); //Sanity check if (xDim <= 0 || yDim <= 0 || zDim <= 0 || xmin > xmax || ymin > ymax || zmin > zmax || !bIsUniform || NumComponents <= 0) { fclose(fp); throw std::runtime_error("Something went wrong (dimensions smaller or equal 0, [xyz]min > [xyz]max, not uniform or numComponents <= 0)."); } //Find the beginning of the data section const long idxStartData = strstr(buffer, "# Data section follows") - buffer; if (idxStartData <= 0) { fclose(fp); throw std::runtime_error("Data section not found!"); } //Set the file pointer to the beginning of "# Data section follows" bool err = fseek(fp, idxStartData, SEEK_SET) != 0; //Consume this line, which is "# Data section follows" err |= fgets(buffer, MaxHeaderSize, fp) == nullptr; //Consume the next line, which is "@1" err |= fgets(buffer, MaxHeaderSize, fp) == nullptr; if (err) { fclose(fp); throw std::runtime_error("A read error occured while seeking data section!"); } //Read the data // - how much to read size_t numOfValues = xDim * yDim * zDim * NumComponents; int dataTypeSize = 0; switch (dataType) { case VTK_FLOAT: { dataTypeSize = sizeof(float); break; } case VTKLabelType: { dataTypeSize = sizeof(LabelType); break; } } size_t dataMemorySize = dataTypeSize * numOfValues; if (!rawDataSize) rawDataSize = dataMemorySize; RawDataType* rawData = new RawDataType[rawDataSize]; size_t rawDataTypeSize = sizeof(RawDataType); if (!rawData) { fclose(fp); throw std::runtime_error(QString("Could not allocate memory (%1 bytes)!").arg(rawDataSize).toStdString()); } size_t actRead = fread( (void*)rawData, rawDataTypeSize, rawDataSize, fp); if (rawDataSize != actRead) { delete [] rawData; fclose(fp); throw std::runtime_error(QString("Wanted to read %1 but got %2 bytes while reading the binary data section." " Premature end of file?").arg(rawDataSize).arg(actRead).toStdString()); } if (rleEncoded) { char* output = new RawDataType[dataMemorySize]; actRead = decodeRLE(rawData, actRead, output, dataMemorySize); delete[] rawData; if (actRead != dataMemorySize) { delete[] output; fclose(fp); throw std::runtime_error(QString("RLE decode: Wanted to get %1 but got %2 bytes while decoding. Wrong data type?").arg(dataMemorySize).arg(actRead).toStdString()); } rawDataSize = dataMemorySize; rawData = output; } //Note: Data runs x-fastest, i.e., the loop over the x-axis is the innermost size_t Idx(0); for (int z = 0; z<zDim; z++) { for (int y = 0; y<yDim; y++) { for (int x = 0; x<xDim; x++) { //Note: Random access to the value (of the first component) of the grid point (x,y,z): // pData[((z * yDim + y) * xDim + x) * NumComponents] assert(((static_cast<size_t>(z) * yDim + y) * xDim + x) * NumComponents == Idx * NumComponents); for (int c = 0; c<NumComponents; c++) { float pixelValue = 0; switch (dataType) { case VTK_FLOAT: pixelValue = (reinterpret_cast<float*>(rawData))[Idx * NumComponents + c]; break; case VTKLabelType: pixelValue = (reinterpret_cast<LabelType*>(rawData))[Idx * NumComponents + c]; break; } //printf("%g ", pData[Idx * NumComponents + c]); imageData->SetScalarComponentFromFloat(x, y, z, c, pixelValue); } Idx++; } } } delete[] rawData; fclose(fp); return imageData; } void iAAmiraMeshIO::Write(QString const & filename, vtkImageData* img) { int extent[6]; img->GetExtent(extent); int w = extent[1] - extent[0] + 1; int h = extent[3] - extent[2] + 1; int d = extent[5] - extent[4] + 1; int NumComponents = img->GetNumberOfScalarComponents(); int vtkType = img->GetScalarType(); QString amiraType; QString amiraTypeDesc; switch (vtkType) { case VTK_UNSIGNED_CHAR: amiraType = "byte"; amiraTypeDesc = "Label"; break; case VTK_FLOAT: amiraType = "float"; amiraTypeDesc = "Data"; break; default: throw std::runtime_error("Avizo/AmiraMesh: (Currently) unsupported data type! Supported data types: label image (unsigned char), float."); } QFile file(filename); file.open(QIODevice::WriteOnly); QByteArray headerData; QTextStream stream(&headerData); stream << AmiraMeshFileTag << "\n\n\n"; stream << QString(QString(DefineLatticeToken) + " %1 %2 %3").arg(w).arg(h).arg(d).toLocal8Bit() << "\n\n"; stream << QString("Parameters {\n" //" Colormap \"labels.am\",\n" " Content \"%1x%2x%3 %4, uniform coordinates\",\n") .arg(w).arg(h).arg(d).arg(amiraType).toLocal8Bit(); stream << QString( " BoundingBox %1 %2 %3 %4 %5 %6,\n" " CoordType \"uniform\"\n" "}\n\n") .arg(extent[0]).arg(extent[1]).arg(extent[2]).arg(extent[3]).arg(extent[4]).arg(extent[5]).toLocal8Bit(); stream << QString("Lattice { %1 %2 } @1\n\n").arg(amiraType).arg(amiraTypeDesc); stream << "# Data section follows\n"; stream << "@1\n"; stream.flush(); file.write(headerData); for (int z = 0; z < d; z++) { for (int y = 0; y < h; y++) { for (int x = 0; x < w; x++) { for (int c = 0; c < NumComponents; c++) { float pixelValue = img->GetScalarComponentAsFloat(x, y, z, c); switch (vtkType) { case VTK_FLOAT: { file.write(reinterpret_cast<char*>(&pixelValue), sizeof(float)); break; } case VTK_UNSIGNED_CHAR: { unsigned char pixVal = static_cast<unsigned char>(pixelValue); file.write(reinterpret_cast<char*>(&pixVal), 1); break; } } } } } } file.close(); }
gpl-3.0
Scille/parsec-gui
src/reducers/viewSwitcherReducer.test.js
678
import viewSwitcherReducer from './viewSwitcherReducer' import * as types from '../actions/ActionTypes'; describe('ViewSwitcher Reducer', () => { const initialState = {list: true, loading_animation: true} it('should return the initial state', () => { expect(viewSwitcherReducer(undefined, {})).toEqual(initialState) }) it('should handle SWITCH_VIEW', () => { const state = {list: true, loading_animation: true} const action = { type: types.SWITCH_VIEW } expect(viewSwitcherReducer(undefined, action)).toEqual({list: false, loading_animation: true}) expect(viewSwitcherReducer(state, action)).toEqual({list: false, loading_animation: true}) }) })
gpl-3.0
Limnor/Limnor-Studio-Source-Code
Source/WebBuilder/JsString.cs
14073
/* * Author: Bob Limnor ([email protected]) * Project: Limnor Studio * Item: Web Project Support * License: GNU General Public License v3.0 */ using System; using System.Collections.Generic; using System.Text; using System.Drawing; using VPL; using System.ComponentModel; using System.Collections.Specialized; using System.Globalization; using System.Xml; using System.Text.RegularExpressions; namespace Limnor.WebBuilder { [TypeMapping(typeof(string))] [TypeConverter(typeof(TypeConverterJsString))] [JsTypeAttribute] [ToolboxBitmapAttribute(typeof(JsString), "Resources.abc.bmp")] public class JsString : IJavascriptType { #region fields and constructors private string _value; public JsString() { } public JsString(string value) { _value = value; } #endregion #region Properties [WebClientMember] public int Length { get { if (string.IsNullOrEmpty(_value)) { return 0; } return _value.Length; } } [WebClientMember] public bool IsEmailAddress { get { if (string.IsNullOrEmpty(_value)) { return false; } RegexUtilities r = new RegexUtilities(); return r.IsValidEmail(_value); } } [WebClientMember] public bool IsEmailAddressList { get { if (string.IsNullOrEmpty(_value)) { return false; } string[] ss = _value.Split(';'); if (ss.Length > 0) { for (int i = 0; i < ss.Length; i++) { if (ss[i].Length > 0) { RegexUtilities r = new RegexUtilities(); if (!r.IsValidEmail(ss[i])) { return false; } } } return true; } return false; } } [NotForProgramming] [Browsable(false)] public string Value { get { return _value; } } #endregion #region Methods [WebClientMember] [Description("Return a string by removing all non-alphanumeric characters from this string, allowing spaces, +, - and _")] public JsString GetAlphaNumericPlus() { return new JsString(); } [WebClientMember] [Description("Return a string by removing all non-alphanumeric characters from this string")] public JsString GetAlphaNumeric() { return new JsString(); } [WebClientMember] [Description("Return a string by removing all non-alphanumeric characters from this string, allowing - and _")] public JsString GetAlphaNumericEx() { return new JsString(); } [WebClientMember] [Description("Returns a string by removing , each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.")] public JsString Trim() { return new JsString(); } [WebClientMember] [Description("Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.")] public JsArray Split(string delimeter) { return new JsArray(); } [WebClientMember] [Description("Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter. Parameter 'limit' specifies the number of splits.")] public JsArray Split(string delimeter, int limit) { return new JsArray(); } [WebClientMember] [Description("Append value to the end of this string")] public void Append(string value) { } [WebClientMember] [Description("Replace string occurenses specified by parameter 'search' by a string specified by parameter 'value'.")] public JsString Replace(string search, string value) { return new JsString(); } [WebClientMember] [Description("Replace string occurenses specified by parameter 'search' by a string specified by parameter 'value'. The search of string occurenses is case-insensitive.")] public JsString Replace_IgnoreCase(string search, string value) { return new JsString(); } [WebClientMember] [Description("Assuming this string is a file path, this function returns the last part from the path")] public JsString GetFilename() { return new JsString(); } [WebClientMember] [Description("Assuming this string is a file path, this function returns the last part from the path and removes file extension from the return value.")] public JsString GetFilenameWithoutExt() { return new JsString(); } [WebClientMember] [Description("Get a portion of the string by specifying the starting character and length. 0 indicates the first character, 1 indicates the second character, etc.")] public JsString SubString(int start, int length) { return new JsString(); } [WebClientMember] [Description("Get a portion of the string by specifying the starting character. 0 indicates the first character, 1 indicates the second character, etc.")] public JsString SubString(int start) { return new JsString(); } [NotForProgramming] [Browsable(false)] public override string ToString() { return _value; } #endregion #region IJavascriptType Members [Browsable(false)] [NotForProgramming] public string CreateDefaultObject() { return "''"; } [Browsable(false)] [NotForProgramming] public bool IsDefaultValue() { return string.IsNullOrEmpty(_value); } [Browsable(false)] [NotForProgramming] public void SetValueString(string value) { _value = value; } [Browsable(false)] [NotForProgramming] public string GetValueString() { return _value; } [Browsable(false)] [NotForProgramming] public string GetValueJsCode() { if (string.IsNullOrEmpty(_value)) return "''"; return string.Format(CultureInfo.InvariantCulture, "'{0}'", _value.Replace("'", "\\'")); } [Browsable(false)] [NotForProgramming] public void SetValue(object value) { if (value != null) { if (value is string) { _value = (string)value; } else { _value = value.ToString(); } } else { _value = string.Empty; } } [Browsable(false)] [NotForProgramming] public object GetValue() { if (_value == null) { _value = string.Empty; } return _value; } [Browsable(false)] [NotForProgramming] public Type GetValueType() { return typeof(string); } [Browsable(false)] [NotForProgramming] public string GetJavascriptMethodRef(string objectName, string methodname, StringCollection methodCode, StringCollection parameters) { if (string.CompareOrdinal(methodname, "GetAlphaNumeric") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.getAlphaNumeric({0})", objectName); } else if (string.CompareOrdinal(methodname, "GetAlphaNumericEx") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.getAlphaNumericEx({0})", objectName); } else if (string.CompareOrdinal(methodname, "GetAlphaNumericPlus") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.getAlphaNumericPlus({0})", objectName); } else if (string.CompareOrdinal(methodname, "GetFilename") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.getFilename({0})", objectName); } else if (string.CompareOrdinal(methodname, "GetFilenameWithoutExt") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.getFilenameNoExt({0})", objectName); } else if (string.CompareOrdinal(methodname, "Trim") == 0) { return string.Format(CultureInfo.InvariantCulture, "{0}.trim()", objectName); } else if (string.CompareOrdinal(methodname, "Split") == 0 || string.CompareOrdinal(methodname, "SplitWithLimit") == 0) { if (parameters != null) { if (parameters.Count == 1) { return string.Format(CultureInfo.InvariantCulture, "{0}.split({1})", objectName, parameters[0]); } else if (parameters.Count == 2) { return string.Format(CultureInfo.InvariantCulture, "{0}.split({1},{2})", objectName, parameters[0], parameters[1]); } } } else if (string.CompareOrdinal(methodname, ".ctor") == 0) { if (parameters == null || parameters.Count == 0) { return "''"; } else { return parameters[0]; } } else if (string.CompareOrdinal(methodname, "Append") == 0) { return string.Format(CultureInfo.InvariantCulture, "{0} = {0} + {1}", objectName, parameters[0]); } else if (string.CompareOrdinal(methodname, "Replace") == 0) { return string.Format(CultureInfo.InvariantCulture, "{0}.replace(new RegExp({1},'g'), {2})", objectName, parameters[0], parameters[1]); } else if (string.CompareOrdinal(methodname, "Replace_IgnoreCase") == 0) { return string.Format(CultureInfo.InvariantCulture, "{0}.replace(new RegExp({1},'gi'), {2})", objectName, parameters[0], parameters[1]); } else if (string.CompareOrdinal(methodname, "SubString") == 0) { if (parameters.Count == 1) return string.Format(CultureInfo.InvariantCulture, "{0}.substr({1})", objectName, parameters[0]); if (parameters.Count == 2) return string.Format(CultureInfo.InvariantCulture, "{0}.substr({1}, {2})", objectName, parameters[0], parameters[1]); } return "null"; } [Browsable(false)] [NotForProgramming] public string GetJavascriptPropertyRef(string objectName, string propertyName) { if (string.CompareOrdinal(propertyName, "Length") == 0) { return string.Format(CultureInfo.InvariantCulture, "{0}.length", objectName); } else if (string.CompareOrdinal(propertyName, "IsEmailAddress") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.isEmailAddress({0})", objectName); } else if (string.CompareOrdinal(propertyName, "IsEmailAddressList") == 0) { return string.Format(CultureInfo.InvariantCulture, "JsonDataBinding.isEmailAddressList({0})", objectName); } return "null"; } #endregion #region ICloneable Members [NotForProgramming] [Browsable(false)] public object Clone() { JsString obj = new JsString(_value); return obj; } #endregion #region IXmlNodeSerializable Members [Browsable(false)] [NotForProgramming] public void OnReadFromXmlNode(IXmlCodeReader serializer, XmlNode node) { foreach (XmlNode n in node.ChildNodes) { XmlCDataSection cd = n as XmlCDataSection; if (cd != null) { _value = cd.Value; break; } } } [Browsable(false)] [NotForProgramming] public void OnWriteToXmlNode(IXmlCodeWriter serializer, XmlNode node) { XmlCDataSection cd = node.OwnerDocument.CreateCDataSection(_value); node.AppendChild(cd); } #endregion } public class TypeConverterJsString : TypeConverter { public TypeConverterJsString() { } public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (typeof(string).Equals(sourceType)) { return true; } return base.CanConvertFrom(context, sourceType); } public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (typeof(string).Equals(destinationType)) { return true; } return base.CanConvertTo(context, destinationType); } public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { if (value == null) { return new JsString(); } else { return new JsString(value.ToString()); } } public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { if (typeof(JsString).IsAssignableFrom(destinationType)) { if (value == null) { return new JsString(); } else { return new JsString(value.ToString()); } } if (typeof(string).Equals(destinationType)) { if (value == null) { return string.Empty; } return value.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } public override object CreateInstance(ITypeDescriptorContext context, System.Collections.IDictionary propertyValues) { if (propertyValues != null) { object v = null; if (propertyValues.Contains("value")) { v = propertyValues["value"]; } if (v == null) { return new JsString(); } else { return new JsString(v.ToString()); } } return base.CreateInstance(context, propertyValues); } } public class RegexUtilities { bool invalid = false; public bool IsValidEmail(string strIn) { invalid = false; if (String.IsNullOrEmpty(strIn)) return false; // Use IdnMapping class to convert Unicode domain names. try { strIn = Regex.Replace(strIn, @"(@)(.+)$", this.DomainMapper, RegexOptions.None); } catch { return false; } if (invalid) return false; // Return true if strIn is in valid e-mail format. try { return Regex.IsMatch(strIn, @"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" + @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$", RegexOptions.IgnoreCase); } catch { return false; } } private string DomainMapper(Match match) { // IdnMapping class with default property values. IdnMapping idn = new IdnMapping(); string domainName = match.Groups[2].Value; try { domainName = idn.GetAscii(domainName); } catch (ArgumentException) { invalid = true; } return match.Groups[1].Value + domainName; } } }
gpl-3.0
emiliano84/FormValidationUwp
Yugen.Toolkit.Uwp/Services/LocalizationService.cs
451
using Windows.ApplicationModel.Resources; namespace Yugen.Toolkit.Uwp.Services { public static class LocalizationService { private static readonly ResourceLoader Loader = new ResourceLoader(); public static string Load(string stringName) { var localizedString = Loader.GetString(stringName); return string.IsNullOrEmpty(localizedString) ? $"__{stringName}" : localizedString; } } }
gpl-3.0
DaGeRe/KoPeMe
kopeme-core/src/test/java/de/dagere/kopeme/kieker/TestKiekerTraceEntry.java
448
package de.dagere.kopeme.kieker; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.util.Arrays; import org.junit.Test; public class TestKiekerTraceEntry { @Test public void testFieldOrder() throws Exception { String[] testable = KiekerTraceEntry.getFieldDescription(); assertFalse(Arrays.asList(testable).contains("FIELDS")); assertEquals(10, testable.length); } }
gpl-3.0
willjoseph/cpparch
cpparch/cppparse/msvc-8.0/include/delayhlp.cpp
15385
// // DelayHlp.cpp // // Copyright (c) Microsoft Corporation. All rights reserved. // // Implement the delay load helper routines. // // Build instructions // cl -c -O1 -Z7 -Zl -W3 delayhlp.cpp // // For ISOLATION_AWARE_ENABLED calls to LoadLibrary(), you will need to add // a definition for ISOLATION_AWARE_ENABLED to the command line above, eg: // cl -c -O1 -Z7 -Zl -W3 -DISOLATION_AWARE_ENABLED=1 delayhlp.cpp // // // Then, you can either link directly with this new object file, or replace the one in // delayimp.lib with your new one, eg: // lib /out:delayimp.lib delayhlp.obj // #define WIN32_LEAN_AND_MEAN #define STRICT #include <windows.h> #include "DelayImp.h" // // Local copies of strlen, memcmp, and memcpy to make sure we do not need the CRT // static inline size_t __strlen(const char * sz) { const char *szEnd = sz; while( *szEnd++ ) { ; } return szEnd - sz - 1; } static inline int __memcmp(const void * pv1, const void * pv2, size_t cb) { if (!cb) { return 0; } while ( --cb && *(char *)pv1 == *(char *)pv2 ) { pv1 = (char *)pv1 + 1; pv2 = (char *)pv2 + 1; } return *((unsigned char *)pv1) - *((unsigned char *)pv2); } static inline void * __memcpy(void * pvDst, const void * pvSrc, size_t cb) { void * pvRet = pvDst; // // copy from lower addresses to higher addresses // while (cb--) { *(char *)pvDst = *(char *)pvSrc; pvDst = (char *)pvDst + 1; pvSrc = (char *)pvSrc + 1; } return pvRet; } // utility function for calculating the index of the current import // for all the tables (INT, BIAT, UIAT, and IAT). inline unsigned IndexFromPImgThunkData(PCImgThunkData pitdCur, PCImgThunkData pitdBase) { return (unsigned) (pitdCur - pitdBase); } // C++ template utility function for converting RVAs to pointers // #if defined(_M_IA64) #pragma section(".base", long, read) extern "C" __declspec(allocate(".base")) const IMAGE_DOS_HEADER __ImageBase; #else extern "C" const IMAGE_DOS_HEADER __ImageBase; #endif template <class X> X PFromRva(RVA rva) { return X(PBYTE(&__ImageBase) + rva); } // structure definitions for the list of unload records typedef struct UnloadInfo * PUnloadInfo; typedef struct UnloadInfo { PUnloadInfo puiNext; PCImgDelayDescr pidd; } UnloadInfo; // utility function for calculating the count of imports given the base // of the IAT. NB: this only works on a valid IAT! inline unsigned CountOfImports(PCImgThunkData pitdBase) { unsigned cRet = 0; PCImgThunkData pitd = pitdBase; while (pitd->u1.Function) { pitd++; cRet++; } return cRet; } extern "C" PUnloadInfo __puiHead = 0; struct ULI : public UnloadInfo { ULI(PCImgDelayDescr pidd_) { pidd = pidd_; Link(); } ~ULI() { Unlink(); } void * operator new(size_t cb) { return ::LocalAlloc(LPTR, cb); } void operator delete(void * pv) { ::LocalFree(pv); } void Unlink() { PUnloadInfo * ppui = &__puiHead; while (*ppui && *ppui != this) { ppui = &((*ppui)->puiNext); } if (*ppui == this) { *ppui = puiNext; } } void Link() { puiNext = __puiHead; __puiHead = this; } }; // For our own internal use, we convert to the old // format for convenience. // struct InternalImgDelayDescr { DWORD grAttrs; // attributes LPCSTR szName; // pointer to dll name HMODULE * phmod; // address of module handle PImgThunkData pIAT; // address of the IAT PCImgThunkData pINT; // address of the INT PCImgThunkData pBoundIAT; // address of the optional bound IAT PCImgThunkData pUnloadIAT; // address of optional copy of original IAT DWORD dwTimeStamp; // 0 if not bound, // O.W. date/time stamp of DLL bound to (Old BIND) }; typedef InternalImgDelayDescr * PIIDD; typedef const InternalImgDelayDescr * PCIIDD; static inline PIMAGE_NT_HEADERS WINAPI PinhFromImageBase(HMODULE hmod) { return PIMAGE_NT_HEADERS(PBYTE(hmod) + PIMAGE_DOS_HEADER(hmod)->e_lfanew); } static inline void WINAPI OverlayIAT(PImgThunkData pitdDst, PCImgThunkData pitdSrc) { __memcpy(pitdDst, pitdSrc, CountOfImports(pitdDst) * sizeof IMAGE_THUNK_DATA); } static inline DWORD WINAPI TimeStampOfImage(PIMAGE_NT_HEADERS pinh) { return pinh->FileHeader.TimeDateStamp; } static inline bool WINAPI FLoadedAtPreferredAddress(PIMAGE_NT_HEADERS pinh, HMODULE hmod) { return UINT_PTR(hmod) == pinh->OptionalHeader.ImageBase; } // Do the InterlockedExchange magic // #ifdef _M_IX86 #undef InterlockedExchangePointer #define InterlockedExchangePointer(Target, Value) \ (PVOID)(LONG_PTR)InterlockedExchange((PLONG)(Target), (LONG)(LONG_PTR)(Value)) #if (_MSC_VER >= 1300) typedef __w64 unsigned long *PULONG_PTR; #else typedef unsigned long *PULONG_PTR; #endif #endif extern "C" FARPROC WINAPI __delayLoadHelper2( PCImgDelayDescr pidd, FARPROC * ppfnIATEntry ) { // Set up some data we use for the hook procs but also useful for // our own use // InternalImgDelayDescr idd = { pidd->grAttrs, PFromRva<LPCSTR>(pidd->rvaDLLName), PFromRva<HMODULE*>(pidd->rvaHmod), PFromRva<PImgThunkData>(pidd->rvaIAT), PFromRva<PCImgThunkData>(pidd->rvaINT), PFromRva<PCImgThunkData>(pidd->rvaBoundIAT), PFromRva<PCImgThunkData>(pidd->rvaUnloadIAT), pidd->dwTimeStamp }; DelayLoadInfo dli = { sizeof DelayLoadInfo, pidd, ppfnIATEntry, idd.szName, { 0 }, 0, 0, 0 }; if (0 == (idd.grAttrs & dlattrRva)) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_INVALID_PARAMETER), 0, 1, PULONG_PTR(rgpdli) ); return 0; } HMODULE hmod = *idd.phmod; // Calculate the index for the IAT entry in the import address table // N.B. The INT entries are ordered the same as the IAT entries so // the calculation can be done on the IAT side. // const unsigned iIAT = IndexFromPImgThunkData(PCImgThunkData(ppfnIATEntry), idd.pIAT); const unsigned iINT = iIAT; PCImgThunkData pitd = &(idd.pINT[iINT]); dli.dlp.fImportByName = !IMAGE_SNAP_BY_ORDINAL(pitd->u1.Ordinal); if (dli.dlp.fImportByName) { dli.dlp.szProcName = LPCSTR(PFromRva<PIMAGE_IMPORT_BY_NAME>(RVA(UINT_PTR(pitd->u1.AddressOfData)))->Name); } else { dli.dlp.dwOrdinal = DWORD(IMAGE_ORDINAL(pitd->u1.Ordinal)); } // Call the initial hook. If it exists and returns a function pointer, // abort the rest of the processing and just return it for the call. // FARPROC pfnRet = NULL; if (__pfnDliNotifyHook2) { pfnRet = ((*__pfnDliNotifyHook2)(dliStartProcessing, &dli)); if (pfnRet != NULL) { goto HookBypass; } } // Check to see if we need to try to load the library. // if (hmod == 0) { if (__pfnDliNotifyHook2) { hmod = HMODULE(((*__pfnDliNotifyHook2)(dliNotePreLoadLibrary, &dli))); } if (hmod == 0) { hmod = ::LoadLibrary(dli.szDll); } if (hmod == 0) { dli.dwLastError = ::GetLastError(); if (__pfnDliFailureHook2) { // when the hook is called on LoadLibrary failure, it will // return 0 for failure and an hmod for the lib if it fixed // the problem. // hmod = HMODULE((*__pfnDliFailureHook2)(dliFailLoadLib, &dli)); } if (hmod == 0) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_MOD_NOT_FOUND), 0, 1, PULONG_PTR(rgpdli) ); // If we get to here, we blindly assume that the handler of the exception // has magically fixed everything up and left the function pointer in // dli.pfnCur. // return dli.pfnCur; } } // Store the library handle. If it is already there, we infer // that another thread got there first, and we need to do a // FreeLibrary() to reduce the refcount // HMODULE hmodT = HMODULE(InterlockedExchangePointer((PVOID *) idd.phmod, PVOID(hmod))); if (hmodT != hmod) { // add lib to unload list if we have unload data if (pidd->rvaUnloadIAT) { // suppress prefast warning 6014, the object is saved in a link list in the constructor of ULI #pragma warning(suppress:6014) new ULI(pidd); } } else { ::FreeLibrary(hmod); } } // Go for the procedure now. // dli.hmodCur = hmod; if (__pfnDliNotifyHook2) { pfnRet = (*__pfnDliNotifyHook2)(dliNotePreGetProcAddress, &dli); } if (pfnRet == 0) { if (pidd->rvaBoundIAT && pidd->dwTimeStamp) { // bound imports exist...check the timestamp from the target image // PIMAGE_NT_HEADERS pinh(PinhFromImageBase(hmod)); if (pinh->Signature == IMAGE_NT_SIGNATURE && TimeStampOfImage(pinh) == idd.dwTimeStamp && FLoadedAtPreferredAddress(pinh, hmod)) { // Everything is good to go, if we have a decent address // in the bound IAT! // pfnRet = FARPROC(UINT_PTR(idd.pBoundIAT[iIAT].u1.Function)); if (pfnRet != 0) { goto SetEntryHookBypass; } } } pfnRet = ::GetProcAddress(hmod, dli.dlp.szProcName); } if (pfnRet == 0) { dli.dwLastError = ::GetLastError(); if (__pfnDliFailureHook2) { // when the hook is called on GetProcAddress failure, it will // return 0 on failure and a valid proc address on success // pfnRet = (*__pfnDliFailureHook2)(dliFailGetProc, &dli); } if (pfnRet == 0) { PDelayLoadInfo rgpdli[1] = { &dli }; RaiseException( VcppException(ERROR_SEVERITY_ERROR, ERROR_PROC_NOT_FOUND), 0, 1, PULONG_PTR(rgpdli) ); // If we get to here, we blindly assume that the handler of the exception // has magically fixed everything up and left the function pointer in // dli.pfnCur. // pfnRet = dli.pfnCur; } } SetEntryHookBypass: *ppfnIATEntry = pfnRet; HookBypass: if (__pfnDliNotifyHook2) { dli.dwLastError = 0; dli.hmodCur = hmod; dli.pfnCur = pfnRet; (*__pfnDliNotifyHook2)(dliNoteEndProcessing, &dli); } return pfnRet; } extern "C" BOOL WINAPI __FUnloadDelayLoadedDLL2(LPCSTR szDll) { BOOL fRet = FALSE; PUnloadInfo pui = __puiHead; for (pui = __puiHead; pui; pui = pui->puiNext) { LPCSTR szName = PFromRva<LPCSTR>(pui->pidd->rvaDLLName); size_t cbName = __strlen(szName); // Intentionally case sensitive to avoid complication of using the CRT // for those that don't use the CRT...the user can replace this with // a variant of a case insenstive comparison routine // if (cbName == __strlen(szDll) && __memcmp(szDll, szName, cbName) == 0) { break; } } if (pui && pui->pidd->rvaUnloadIAT) { PCImgDelayDescr pidd = pui->pidd; HMODULE * phmod = PFromRva<HMODULE*>(pidd->rvaHmod); HMODULE hmod = *phmod; OverlayIAT( PFromRva<PImgThunkData>(pidd->rvaIAT), PFromRva<PCImgThunkData>(pidd->rvaUnloadIAT) ); ::FreeLibrary(hmod); *phmod = NULL; delete reinterpret_cast<ULI*> (pui); fRet = TRUE; } return fRet; } extern "C" HRESULT WINAPI __HrLoadAllImportsForDll(LPCSTR szDll) { HRESULT hrRet = HRESULT_FROM_WIN32(ERROR_MOD_NOT_FOUND); PIMAGE_NT_HEADERS pinh = PinhFromImageBase(HMODULE(&__ImageBase)); // Scan the Delay load IAT/INT for the dll in question // if (pinh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].Size) { PCImgDelayDescr pidd; pidd = PFromRva<PCImgDelayDescr>( pinh->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT].VirtualAddress ); // Check all of the dlls listed up to the NULL one. // while (pidd->rvaDLLName) { // Check to see if it is the DLL we want to load. // Intentionally case sensitive to avoid complication of using the CRT // for those that don't use the CRT...the user can replace this with // a variant of a case insenstive comparison routine. // LPCSTR szDllCur = PFromRva<LPCSTR>(pidd->rvaDLLName); size_t cchDllCur = __strlen(szDllCur); if (cchDllCur == __strlen(szDll) && __memcmp(szDll, szDllCur, cchDllCur) == 0) { // We found it, so break out with pidd and szDllCur set appropriately // break; } // Advance to the next delay import descriptor // pidd++; } if (pidd->rvaDLLName) { // Found a matching DLL name, now process it. // // Set up the internal structure // FARPROC * ppfnIATEntry = PFromRva<FARPROC*>(pidd->rvaIAT); size_t cpfnIATEntries = CountOfImports(PCImgThunkData(ppfnIATEntry)); FARPROC * ppfnIATEntryMax = ppfnIATEntry + cpfnIATEntries; for (;ppfnIATEntry < ppfnIATEntryMax; ppfnIATEntry++) { __delayLoadHelper2(pidd, ppfnIATEntry); } // Done, indicate some semblance of success // hrRet = S_OK; } } return hrRet; }
gpl-3.0
EasyFarm/EasyFarm
EasyFarm/Classes/PlayerMonitor.cs
1945
// /////////////////////////////////////////////////////////////////// // This file is a part of EasyFarm for Final Fantasy XI // Copyright (C) 2013 Mykezero // // EasyFarm 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 3 of the License, or // (at your option) any later version. // // EasyFarm 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 General Public License for more details. // // You should have received a copy of the GNU General Public License // If not, see <http://www.gnu.org/licenses/>. // /////////////////////////////////////////////////////////////////// using System.Threading; using System.Threading.Tasks; using EasyFarm.States; using MemoryAPI; namespace EasyFarm.Classes { public class PlayerMonitor { private CancellationTokenSource _tokenSource; private readonly PlayerMovementTracker _movementTracker; public PlayerMonitor(IMemoryAPI memory) { _movementTracker = new PlayerMovementTracker(memory); } public void Start() { _tokenSource = new CancellationTokenSource(); Task.Factory.StartNew(Monitor, _tokenSource.Token, TaskCreationOptions.LongRunning, TaskScheduler.Default); } public void Stop() { _tokenSource.Cancel(); } private void Monitor() { while (true) { if (_tokenSource.IsCancellationRequested) { _tokenSource.Token.ThrowIfCancellationRequested(); } _movementTracker.RunComponent(); TimeWaiter.Pause(100); } } } }
gpl-3.0
FabriceSalvaire/PyValentina
Patro/TextileTechnology/Seam.py
1853
#################################################################################################### # # Patro - A Python library to make patterns for fashion design # Copyright (C) 2019 Fabrice Salvaire # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program 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 Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <https://www.gnu.org/licenses/>. # #################################################################################################### __all__ = ['AstmSeam'] #################################################################################################### class AstmSeamClass: ############################################## def __init__(self, name): self._name = str(name) ############################################## @property def name(self): return self._name #################################################################################################### class AstmSeam: ############################################## def __init__(self, seam_class, seam_type, number_of_rows): self._class = seam_class self._type = seam_type self._number_of_rows = number_of_rows ############################################## @property def name(self): return '{self._class}{self._type}-{self._number_of_rows}'.format(self)
gpl-3.0
google-code/algoexplorer
src/ppciarravano/algoexplorer/util/PropFileLoader.java
1231
package ppciarravano.algoexplorer.util; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Classe per caricare un file di properties dal classpath. * * <br><br>License: GNU General Public License Version 3<br> * * @author Pier Paolo Ciarravano * @version Vers. 0.9 (11/01/2010) */ public abstract class PropFileLoader { /** * Loads the property file. * * @param propFileName - the name of the property file * @return The properties loaded from the file. * @throws java.io.IOException - when the file is not found, etc. */ public static Properties loadProperties(String propFileName) throws IOException { // find the jdo.properties in the class path InputStream ioStream = PropFileLoader.class.getResourceAsStream(propFileName); if(ioStream == null) { throw new IOException("File not found: " + propFileName); } // load the properties Properties retv = new Properties(); retv.load(ioStream); // close the stream ioStream.close(); // return the properties return retv; } }
gpl-3.0
cgeltly/treechecker
app/views/gedcom/lifespan/chart.blade.php
84
<div class="page-header"> <h3> Lifespan </h3> </div> {{ $svg }}
gpl-3.0
FBSLikan/Cetico-TCC
setup.py
745
from distutils.core import setup setup( name='cetico-dev', version='2.8.9', packages=['data.libs.exifread', 'data.libs.exifread.tags', 'data.libs.exifread.tags.makernote', 'data.libs.reportlab', 'data.libs.reportlab.lib', 'data.libs.reportlab.pdfgen', 'data.libs.reportlab.pdfbase', 'data.libs.reportlab.graphics', 'data.libs.reportlab.graphics.charts', 'data.libs.reportlab.graphics.barcode', 'data.libs.reportlab.graphics.samples', 'data.libs.reportlab.graphics.widgets', 'data.libs.reportlab.platypus'], url='https://github.com/FBSLikan/Cetico-TCC', license='', author='Fausto Biazzi de Sousa', author_email='[email protected]', description='' )
gpl-3.0
tcotys/frameworkweb2000
administration/includes/handle_zip.req.php
1999
<?php function copyDirectoryToZip($in_dir, $zip_file, $sub_dir, $debug = false) { if($debug) {$out_txt = "<p>Start reading directory: $sub_dir ...</p>";} if ($handle = opendir($in_dir.$sub_dir)) { $zip_file->addEmptyDir($sub_dir); if($debug){$out_txt .= "<ul>";} while (false !== ($entry = readdir($handle))) { if($debug){$out_txt .= "<li>$entry : ";} if ($entry != "." && $entry != "..") { if(is_file($in_dir.$sub_dir.$entry)) { if($debug){$out_txt .= "file</li>";} $zip_file->addFile($in_dir.$sub_dir.$entry, $sub_dir.$entry); } else if(is_dir($in_dir.$sub_dir.$entry)) { if($debug){$out_txt .= "dir</li>";} $out_txt .= copyDirectoryToZip($in_dir, $zip_file, $sub_dir.$entry.'/'); } else if(is_link($in_dir.$sub_dir.$entry)) { if (is_file(readlink($in_dir.$sub_dir.$entry))) { $zip_file->addFile(readlink($in_dir.$sub_dir.$entry), $sub_dir.$entry); } else if (is_dir(readlink($in_dir.$sub_dir.$entry))) { $out_txt .= copyDirectoryToZip($in_dir, $zip_file, $sub_dir.$entry.'/'); } } else { if($debug){$out_txt .= "unknown</li>";} } } } if($debug){$out_txt .= "</ul>";} closedir($handle); } else { $out_txt .= "<p>Error: Cannot read directory.</p>"; } return $out_txt; } function copyZipToDirectory($zip_file, $out_dir, $sub_dir, $debug = false) { if($debug){$out_txt = "<p>Start reading directory: $sub_dir ...</p>";} if($debug){$out_txt .= "<ul>";} for($i = 0; $i < $zip_file->numFiles; $i++) { $zip_filename = $zip_file->getNameIndex($i); if (preg_match('#^'.$sub_dir.'#', $zip_filename)) { if($debug){$out_txt .= "<li>".$zip_filename."</li>";} $zip_file->extractTo($out_dir, array($zip_filename)); // chmod($out_dir.$zip_filename, 0777); } } if($debug){$out_txt .= "</ul>";} return $out_txt; } ?>
gpl-3.0
Nielko/MBSE-Vacation-Manager
de.tu_bs.vacation_manager.test/src/de/tu_bs/vacation_manager/Calender/impl/custom/CalenderFactoryImplCustorm.java
448
package de.tu_bs.vacation_manager.Calender.impl.custom; import de.tu_bs.vacation_manager.Calender.Calender; import de.tu_bs.vacation_manager.Calender.impl.CalenderFactoryImpl; import de.tu_bs.vacation_manager.Calender.impl.CalenderImpl; public class CalenderFactoryImplCustorm extends CalenderFactoryImpl{ @Override public Calender createCalender() { CalenderImpl calender = (CalenderImpl) new CalenderImplCustom(); return calender; } }
gpl-3.0
hyperbox/vbox-5.1
modules/server/core/src/main/java/io/kamax/vbox5_1/setting/memory/LargePagesSettingAction.java
1857
/* * Hyperbox - Virtual Infrastructure Manager * Copyright (C) 2015 Maxime Dor * * http://kamax.io/hbox/ * * 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 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.kamax.vbox5_1.setting.memory; import io.kamax.hbox.constant.MachineAttribute; import io.kamax.tools.setting.BooleanSetting; import io.kamax.tools.setting._Setting; import io.kamax.vbox.settings.memory.LargePagesSetting; import io.kamax.vbox5_1.setting._MachineSettingAction; import org.virtualbox_5_1.HWVirtExPropertyType; import org.virtualbox_5_1.IMachine; import org.virtualbox_5_1.LockType; public class LargePagesSettingAction implements _MachineSettingAction { @Override public LockType getLockType() { return LockType.Write; } @Override public String getSettingName() { return MachineAttribute.LargePages.toString(); } @Override public void set(IMachine machine, _Setting setting) { // TODO check if nested paging & 64 bits is on machine.setHWVirtExProperty(HWVirtExPropertyType.LargePages, ((BooleanSetting) setting).getValue()); } @Override public _Setting get(IMachine machine) { return new LargePagesSetting(machine.getHWVirtExProperty(HWVirtExPropertyType.LargePages)); } }
gpl-3.0
AlexandruValeanu/Concurrent-Programming-in-Scala
src/concurrent_programming/data_parallel/system_equations/ConcurrentJacobiIteration.scala
1744
package concurrent_programming.data_parallel.system_equations import io.threadcso.{Barrier, CombiningBarrier, PROC, proc, ||} class ConcurrentJacobiIteration(A: MatrixUtils.Matrix, b: MatrixUtils.Vector){ val N: Int = MatrixUtils.getRows(A) private val x = MatrixUtils.getNullVector(N) private val newX = MatrixUtils.getNullVector(N) val EPSILON: Double = 0.00000001 private val W = 2 private val height = N / W private val conjBarrier = new CombiningBarrier[Boolean](W, true, _ && _) private val barrier = new Barrier(W) private def worker(start: Int, end: Int): PROC = proc{ var finished = false while (!finished){ // calculate our slice of newX from x for (i <- start until end){ var sum: MatrixUtils.Type = 0 for (j <- 0.until(N)) if (i != j) sum += A(i)(j) * x(j) newX(i) = (b(i) - sum) / A(i)(i) } barrier.sync() // all workers have written their own slice of newX // calculate our slice of x from newX var finishedLocally = true for (i <- start until end){ var sum: MatrixUtils.Type = 0 for (j <- 0.until(N)) if (i != j) sum += A(i)(j) * newX(j) x(i) = (b(i) - sum) / A(i)(i) finishedLocally = finishedLocally && (Math.abs(x(i) - newX(i)) < EPSILON) } // cast our vote for termination, retrieve the aggregated votes finished = conjBarrier.sync(finishedLocally) // all workers have written their own slice of x for this iteration } } def solve(): MatrixUtils.Vector = { for (i <- 0.until(N)) x(i) = 0 val system = || (for (i <- 0 until W) yield worker(height*i, height*(i+1))) system() x } }
gpl-3.0
ghsy158/fgh-framework
fgh-common/src/main/java/fgh/common/dao/Page.java
2234
package fgh.common.dao; import java.io.Serializable; import java.util.List; import com.alibaba.fastjson.JSONObject; /** * 分页对象 * * @author fgh * @since 2016年7月12日下午6:21:25 */ public class Page implements Serializable { private static final long serialVersionUID = -2285216628802671550L; /** * 总记录数 */ private int total; /** * 总页数 */ private int totalPages; /** * 第几页 从0开始 */ private int page = 0; /** * 开始的记录位置 */ private int start; /** * 每页多少条 */ private int pagesize = 20;; /** * 查询到的结果集 */ private List<JSONObject> rows; /** * 排序字段 */ private String sort; /** * 排序方式 asc或desc 默认desc */ private String order = "desc"; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public void setTotalPages() { if (total % pagesize == 0) { this.totalPages = total / pagesize; } else { this.totalPages = (total / pagesize) + 1; } } public int getPage() { return page; } public void setPage(int page) { this.page = page; } public int getPagesize() { return pagesize; } public void setPagesize(int pagesize) { this.pagesize = pagesize; } public int getStart() { return start; } public void setStart() { this.start = page * pagesize; } public List<JSONObject> getRows() { return rows; } public void setRows(List<JSONObject> rows) { this.rows = rows; } public String getSort() { return sort; } public void setSort(String sort) { this.sort = sort; } public String getOrder() { return order; } public void setOrder(String order) { this.order = order; } @Override public String toString() { return "Page [total=" + total + ", totalPages=" + totalPages + ", page=" + page + ", start=" + start + ", pagesize=" + pagesize + ", sort=" + sort + ", order=" + order + "]"; } }
gpl-3.0
malinink/easy-tests
src/test/java/easytests/core/entities/IssueStandardQuestionTypeOptionEntityTest.java
1206
package easytests.core.entities; import easytests.core.models.IssueStandardQuestionTypeOptionModelInterface; import easytests.support.IssueStandardQuestionTypeOptionsSupport; import org.junit.Test; /** * @author VeronikaRevjakina */ public class IssueStandardQuestionTypeOptionEntityTest extends AbstractEntityTest { private IssueStandardQuestionTypeOptionsSupport issueStandardQuestionTypeOptionsSupport = new IssueStandardQuestionTypeOptionsSupport(); @Test public void testCommon() throws Exception { this.testCommon(IssueStandardQuestionTypeOptionEntity.class); } @Test public void testMap() throws Exception { final IssueStandardQuestionTypeOptionModelInterface issueStandardQuestionTypeOptionsModel = this.issueStandardQuestionTypeOptionsSupport.getModelFixtureMock(0); final IssueStandardQuestionTypeOptionEntity issueStandardQuestionTypeOptionEntity = new IssueStandardQuestionTypeOptionEntity(); issueStandardQuestionTypeOptionEntity.map(issueStandardQuestionTypeOptionsModel); this.issueStandardQuestionTypeOptionsSupport.assertEquals(issueStandardQuestionTypeOptionsModel, issueStandardQuestionTypeOptionEntity); } }
gpl-3.0
estaban/pyload
module/plugins/hooks/Captcha9kw.py
6580
# -*- coding: utf-8 -*- """ 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 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, see <http://www.gnu.org/licenses/>. """ from __future__ import with_statement from thread import start_new_thread from base64 import b64encode import time from module.network.RequestFactory import getURL from module.network.HTTPRequest import BadHeader from module.plugins.Hook import Hook class Captcha9kw(Hook): __name__ = "Captcha9kw" __version__ = "0.09" __type__ = "hook" __config__ = [("activated", "bool", "Activated", False), ("force", "bool", "Force CT even if client is connected", True), ("https", "bool", "Enable HTTPS", False), ("confirm", "bool", "Confirm Captcha (Cost +6)", False), ("captchaperhour", "int", "Captcha per hour (max. 9999)", 9999), ("prio", "int", "Prio 1-10 (Cost +1-10)", 0), ("selfsolve", "bool", "If enabled and you have a 9kw client active only you will get your captcha to solve it (Selfsolve)", False), ("timeout", "int", "Timeout (max. 300)", 300), ("passkey", "password", "API key", "")] __description__ = """Send captchas to 9kw.eu""" __author_name__ = "RaNaN" __author_mail__ = "[email protected]" API_URL = "://www.9kw.eu/index.cgi" def setup(self): self.API_URL = "https" + self.API_URL if self.getConfig("https") else "http" + self.API_URL self.info = {} def getCredits(self): response = getURL(self.API_URL, get={"apikey": self.getConfig("passkey"), "pyload": "1", "source": "pyload", "action": "usercaptchaguthaben"}) if response.isdigit(): self.logInfo(_("%s credits left") % response) self.info['credits'] = credits = int(response) return credits else: self.logError(response) return 0 def processCaptcha(self, task): result = None with open(task.captchaFile, 'rb') as f: data = f.read() data = b64encode(data) self.logDebug("%s : %s" % (task.captchaFile, data)) if task.isPositional(): mouse = 1 else: mouse = 0 response = getURL(self.API_URL, post={ "apikey": self.getConfig("passkey"), "prio": self.getConfig("prio"), "confirm": self.getConfig("confirm"), "captchaperhour": self.getConfig("captchaperhour"), "maxtimeout": self.getConfig("timeout"), "selfsolve": self.getConfig("selfsolve"), "pyload": "1", "source": "pyload", "base64": "1", "mouse": mouse, "file-upload-01": data, "action": "usercaptchaupload"}) if response.isdigit(): self.logInfo(_("New CaptchaID from upload: %s : %s") % (response, task.captchaFile)) for _ in xrange(1, 100, 1): response2 = getURL(self.API_URL, get={"apikey": self.getConfig("passkey"), "id": response, "pyload": "1", "source": "pyload", "action": "usercaptchacorrectdata"}) if response2 != "": break time.sleep(3) result = response2 task.data['ticket'] = response self.logInfo("result %s : %s" % (response, result)) task.setResult(result) else: self.logError("Bad upload: %s" % response) return False def newCaptchaTask(self, task): if not task.isTextual() and not task.isPositional(): return False if not self.getConfig("passkey"): return False if self.core.isClientConnected() and not self.getConfig("force"): return False if self.getCredits() > 0: task.handler.append(self) task.setWaiting(self.getConfig("timeout")) start_new_thread(self.processCaptcha, (task,)) else: self.logError(_("Your Captcha 9kw.eu Account has not enough credits")) def captchaCorrect(self, task): if "ticket" in task.data: try: response = getURL(self.API_URL, post={"action": "usercaptchacorrectback", "apikey": self.getConfig("passkey"), "api_key": self.getConfig("passkey"), "correct": "1", "pyload": "1", "source": "pyload", "id": task.data['ticket']}) self.logInfo("Request correct: %s" % response) except BadHeader, e: self.logError("Could not send correct request.", str(e)) else: self.logError("No CaptchaID for correct request (task %s) found." % task) def captchaInvalid(self, task): if "ticket" in task.data: try: response = getURL(self.API_URL, post={"action": "usercaptchacorrectback", "apikey": self.getConfig("passkey"), "api_key": self.getConfig("passkey"), "correct": "2", "pyload": "1", "source": "pyload", "id": task.data['ticket']}) self.logInfo("Request refund: %s" % response) except BadHeader, e: self.logError("Could not send refund request.", str(e)) else: self.logError("No CaptchaID for not correct request (task %s) found." % task)
gpl-3.0
robwarm/gpaw-symm
doc/exercises/submit.agts.py
1628
def agts(queue): queue.add('neb/neb1.py', ncpus=1) queue.add('neb/neb2.py', ncpus=1) queue.add('neb/neb3.py', ncpus=1) queue.add('aluminium/Al_fcc.py', ncpus=2) queue.add('aluminium/Al_bcc.py', ncpus=2) queue.add('aluminium/Al_fcc_vs_bcc.py', ncpus=2) queue.add('aluminium/Al_fcc_modified.py', ncpus=2) queue.add('diffusion/initial.py', ncpus=2) sol = queue.add('diffusion/solution.py', ncpus=2) queue.add('diffusion/densitydiff.py', deps=[sol]) h2o = queue.add('vibrations/h2o.py', ncpus=8) h2ovib = queue.add('vibrations/H2O_vib.py', ncpus=8, deps=[h2o]) queue.add('vibrations/H2O_vib_2.py', ncpus=4, deps=[h2ovib]) si = queue.add('wannier/si.py', ncpus=8) queue.add('wannier/wannier-si.py', deps=[si]) benzene = queue.add('wannier/benzene.py', ncpus=8) queue.add('wannier/wannier-benzene.py', deps=[benzene]) queue.add('lrtddft/ground_state.py', ncpus=8) queue.add('transport/pt_h2_tb_transport.py') t1 = queue.add('transport/pt_h2_lcao_manual.py') queue.add('transport/pt_h2_lcao_transport.py', deps=t1) queue.add('wavefunctions/CO.py', ncpus=8) ferro = queue.add('iron/ferro.py', ncpus=4) anti = queue.add('iron/anti.py', ncpus=4) non = queue.add('iron/non.py', ncpus=2) queue.add('iron/PBE.py', deps=[ferro, anti, non]) queue.add('gw/test.py') band = queue.add('band_structure/ag.py', ncpus=1, creates='Ag.png') queue.add('eels/test.py', deps=band, ncpus=4) lif = queue.add('bse/LiF_gs.py') queue.add('bse/LiF_RPA.py', deps=lif) queue.add('bse/LiF_BSE.py', deps=lif, ncpus=24, walltime=3 * 60)
gpl-3.0
sigma-random/bettercap
network/net_wifi.go
479
package network import ( "sync" ) const NO_CHANNEL = -1 var ( currChannels = make(map[string]int) currChannelLock = sync.Mutex{} ) func GetInterfaceChannel(iface string) int { currChannelLock.Lock() defer currChannelLock.Unlock() if curr, found := currChannels[iface]; found { return curr } return NO_CHANNEL } func SetInterfaceCurrentChannel(iface string, channel int) { currChannelLock.Lock() defer currChannelLock.Unlock() currChannels[iface] = channel }
gpl-3.0
AuScope/MDU-Portal
src/main/java/org/auscope/portal/csw/CSWRecord.java
11629
package org.auscope.portal.csw; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpression; import javax.xml.xpath.XPathExpressionException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** * User: Mathew Wyatt * Date: 11/02/2009 * Time: 11:58:21 AM */ //TODO: refactor into data and service records public class CSWRecord { private static final Log logger = LogFactory.getLog(CSWRecord.class); private String serviceName; private CSWOnlineResource[] onlineResources; private String contactOrganisation; private String resourceProvider; private String fileIdentifier; private String recordInfoUrl; private CSWGeographicElement[] cswGeographicElements; private String[] descriptiveKeywords; private String dataIdentificationAbstract; private String[] constraints; private static final XPathExpression serviceTitleExpression; private static final XPathExpression dataIdentificationAbstractExpression; private static final XPathExpression contactOrganisationExpression; private static final XPathExpression resourceProviderExpression; private static final XPathExpression fileIdentifierExpression; private static final XPathExpression onlineTransfersExpression; private static final XPathExpression bboxExpression; private static final XPathExpression keywordListExpression; private static final XPathExpression otherConstraintsExpression; /** * Initialise all of our XPathExpressions */ static { serviceTitleExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:citation/gmd:CI_Citation/gmd:title/gco:CharacterString"); dataIdentificationAbstractExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:abstract/gco:CharacterString"); contactOrganisationExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:contact/gmd:CI_ResponsibleParty/gmd:organisationName/gco:CharacterString"); resourceProviderExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:pointOfContact/gmd:CI_ResponsibleParty[./gmd:role[./gmd:CI_RoleCode[@codeListValue = 'resourceProvider']]]/gmd:organisationName/gco:CharacterString"); fileIdentifierExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:fileIdentifier/gco:CharacterString"); onlineTransfersExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:distributionInfo/gmd:MD_Distribution/gmd:transferOptions/gmd:MD_DigitalTransferOptions/gmd:onLine"); bboxExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:extent/gmd:EX_Extent/gmd:geographicElement/gmd:EX_GeographicBoundingBox"); keywordListExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:descriptiveKeywords/gmd:MD_Keywords/gmd:keyword/gco:CharacterString"); otherConstraintsExpression = CSWXPathUtil.attemptCompileXpathExpr("gmd:identificationInfo/gmd:MD_DataIdentification/gmd:resourceConstraints/gmd:MD_LegalConstraints/gmd:otherConstraints/gco:CharacterString"); } public CSWRecord(String serviceName, String contactOrganisation, String fileIdentifier, String recordInfoUrl, String dataIdentificationAbstract, CSWOnlineResource[] onlineResources, CSWGeographicElement[] cswGeographicsElements) { this.serviceName = serviceName; this.contactOrganisation = contactOrganisation; this.fileIdentifier = fileIdentifier; this.recordInfoUrl = recordInfoUrl; this.dataIdentificationAbstract = dataIdentificationAbstract; this.onlineResources = onlineResources; this.cswGeographicElements = cswGeographicsElements; this.descriptiveKeywords = new String[0]; this.constraints = new String[0]; } public CSWRecord(Node node) throws XPathExpressionException { NodeList tempNodeList1 = null; serviceName = (String)serviceTitleExpression.evaluate(node, XPathConstants.STRING); dataIdentificationAbstract = (String) dataIdentificationAbstractExpression.evaluate(node, XPathConstants.STRING); contactOrganisation = (String) contactOrganisationExpression.evaluate(node, XPathConstants.STRING); fileIdentifier = (String) fileIdentifierExpression.evaluate(node, XPathConstants.STRING); resourceProvider = (String) resourceProviderExpression.evaluate(node, XPathConstants.STRING); if (resourceProvider.equals("")) { resourceProvider = "Unknown"; } //There can be multiple gmd:onLine elements (which contain a number of fields we want) tempNodeList1 = (NodeList)onlineTransfersExpression.evaluate(node, XPathConstants.NODESET); List<CSWOnlineResource> resources = new ArrayList<CSWOnlineResource>(); for (int i = 0; i < tempNodeList1.getLength(); i++) { try { Node onlineNode = tempNodeList1.item(i); resources.add(CSWOnlineResourceFactory.parseFromNode(onlineNode)); } catch (IllegalArgumentException ex) { logger.debug(String.format("Unable to parse online resource for serviceName='%1$s' %2$s",serviceName, ex)); } } onlineResources = resources.toArray(new CSWOnlineResource[resources.size()]); //Parse our bounding boxes (if they exist). If any are unparsable, don't worry and just continue tempNodeList1 = (NodeList)bboxExpression.evaluate(node, XPathConstants.NODESET); if (tempNodeList1 != null && tempNodeList1.getLength() > 0) { List<CSWGeographicElement> elList = new ArrayList<CSWGeographicElement>(); for (int i = 0; i < tempNodeList1.getLength(); i++) { try { Node geographyNode = tempNodeList1.item(i); elList.add(CSWGeographicBoundingBox.fromGeographicBoundingBoxNode(geographyNode)); } catch (Exception ex) { logger.debug(String.format("Unable to parse CSWGeographicBoundingBox resource for serviceName='%1$s' %2$s",serviceName, ex)); } } cswGeographicElements = elList.toArray(new CSWGeographicElement[elList.size()]); } //Parse the descriptive keywords tempNodeList1 = (NodeList) keywordListExpression.evaluate(node, XPathConstants.NODESET); if (tempNodeList1 != null && tempNodeList1.getLength() > 0 ) { List<String> keywords = new ArrayList<String>(); Node keyword; for (int j=0; j<tempNodeList1.getLength(); j++) { keyword = tempNodeList1.item(j); keywords.add(keyword.getTextContent()); } descriptiveKeywords = keywords.toArray(new String[keywords.size()]); } else { // Its already at size zero in the constructor } //Parse constraints tempNodeList1 = (NodeList) otherConstraintsExpression.evaluate(node, XPathConstants.NODESET); if(tempNodeList1 != null && tempNodeList1.getLength() > 0) { List<String> constraintsList = new ArrayList<String>(); Node constraint; for (int j=0; j<tempNodeList1.getLength(); j++) { constraint = tempNodeList1.item(j); constraintsList.add(constraint.getTextContent()); } constraints = constraintsList.toArray(new String[constraintsList.size()]); } } public void setRecordInfoUrl(String recordInfoUrl) { this.recordInfoUrl = recordInfoUrl; } public String getRecordInfoUrl() { return recordInfoUrl; } public String getFileIdentifier() { return fileIdentifier; } public String getServiceName() { return serviceName; } public CSWOnlineResource[] getOnlineResources() { return onlineResources; } public String getContactOrganisation() { return contactOrganisation; } public String getResourceProvider() { return resourceProvider; } public String getDataIdentificationAbstract() { return dataIdentificationAbstract; } /** * Set the CSWGeographicElement that bounds this record * @param cswGeographicElement (can be null) */ public void setCSWGeographicElements(CSWGeographicElement[] cswGeographicElements) { this.cswGeographicElements = cswGeographicElements; } /** * gets the CSWGeographicElement that bounds this record (or null if it DNE) * @return */ public CSWGeographicElement[] getCSWGeographicElements() { return cswGeographicElements; } /** * Returns the descriptive keywords for this record * @return descriptive keywords */ public String[] getDescriptiveKeywords() { return descriptiveKeywords; } public String[] getConstraints() { return constraints; } @Override public String toString() { return "CSWRecord [contactOrganisation=" + contactOrganisation + ", resourceProvider=" + resourceProvider + ", cswGeographicElements=" + Arrays.toString(cswGeographicElements) + ", dataIdentificationAbstract=" + dataIdentificationAbstract + ", fileIdentifier=" + fileIdentifier + ", onlineResources=" + Arrays.toString(onlineResources) + ", recordInfoUrl=" + recordInfoUrl + ", serviceName=" + serviceName + ", constraints=" + Arrays.toString(constraints) + "]"; } /** * Returns a filtered list of online resource protocols that match at least one of the specified types * * @param types The list of types you want to filter by * @return */ public CSWOnlineResource[] getOnlineResourcesByType(CSWOnlineResource.OnlineResourceType... types) { List <CSWOnlineResource> result = new ArrayList<CSWOnlineResource>(); for (CSWOnlineResource r : onlineResources) { boolean matching = false; CSWOnlineResource.OnlineResourceType typeToMatch = r.getType(); for (CSWOnlineResource.OnlineResourceType type : types) { if (typeToMatch == type) { matching = true; break; } } if (matching) { result.add(r); } } return result.toArray(new CSWOnlineResource[result.size()]); } /** * Returns true if this CSW Record contains at least 1 onlineResource with ANY of the specified types * @param types * @return */ public boolean containsAnyOnlineResource(CSWOnlineResource.OnlineResourceType... types) { for (CSWOnlineResource r : onlineResources) { CSWOnlineResource.OnlineResourceType typeToMatch = r.getType(); for (CSWOnlineResource.OnlineResourceType type : types) { if (typeToMatch == type) { return true; } } } return false; } /** * Returns true if this record contains the given descriptive keyword, false otherwise. * * @param str * @return true if this record contains the given descriptive keyword, false otherwise. */ public boolean containsKeyword(String str) { for(String keyword : descriptiveKeywords) { if(keyword.equals(str)) { return true; } } return false; } }
gpl-3.0
jolupeza/mailing-ad
application/views/templates/admin/default/html/newsletters/add.php
4853
<div class="row"> <div class="col-sm-12"> <div class="panel"> <div class="panel-heading"> <h2><?php echo $this->lang->line('cms_general_label_add_newsletter'); ?></h2> <?php if (validation_errors()) : ?> <div class="alert alert-danger"> <?php echo validation_errors('<p><small>', '</small></p>'); ?> </div> <?php endif; ?> </div><!-- end panel-heading --> </div><!-- end panel --> </div><!-- end col-sm-12 --> </div><!-- end row --> <div class="row"> <div class="col-sm-12"> <div class="panel"> <div class="panel-body"> <?php echo form_open('', array('id' => 'form_add_newsletter', 'class' => 'form-horizontal', 'role' => 'form'), array('token' => $_token)); ?> <div class="row"> <div class="col-sm-8"> <!-- Name --> <div class="form-group"> <?php echo form_label($this->lang->line('cms_general_label_name'), 'name', array('class' => 'col-sm-3 control-label')); ?> <div class="col-sm-9"> <?php echo form_input(array('id' => 'name', 'name' => 'name', 'class' => 'form-control'), set_value('name'), 'required'); ?> </div><!-- end col-sm-9 --> </div><!-- end form-group --> <!-- Status --> <div class="form-group"> <div class="col-sm-offset-3 col-sm-9"> <div class="checkbox"> <label> <?php $attr = array( 'name' => 'status', 'id' => 'status', 'value' => '1', 'data-off-text' => "<i class='fa fa-times'></i>", 'data-on-text' => "<i class='fa fa-check'></i>", ); ?> <?php echo form_checkbox($attr); ?> <?php echo $this->lang->line('cms_general_label_active'); ?>? </label><!-- end label --> </div><!-- end checkbox --> </div><!-- end col-sm-9 --> </div><!-- end form-group --> <!-- Date submit --> <div class="form-group"> <?php echo form_label($this->lang->line('cms_general_label_date_submit'), 'submit_at', array('class' => 'col-sm-3 control-label')); ?> <div class="col-sm-9"> <div class='input-group date' id='datetimepicker-add' data-date-format="YYYY/MM/DD hh:mm:ss a"> <input type='text' class="form-control" name="submit_at" id="submit_at" /> <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span> </div> </div><!-- end col-sm-9 --> </div> <!-- Content --> <div class="form-group"> <div class="col-sm-12"> <?php echo form_label($this->lang->line('cms_general_label_content'), 'content'); ?> <?php echo form_textarea(array('id' => 'content', 'name' => 'content', 'class' => 'form-control edit-wysiwg'), set_value('content')); ?> </div><!-- end col-sm-9 --> </div> <?php echo form_button(array('class' => 'btn btn-cms pull-right', 'type' => 'submit', 'value' => $this->lang->line('cms_general_label_add'), 'content' => $this->lang->line('cms_general_label_add'))); ?> </div><!-- end col-sm-8 --> <div class="col-sm-4"> <div class="sidebar-right"> <div class="wrapper-widget"> <div class="title-widget"> <h4><?php echo $this->lang->line('cms_general_title_templates'); ?> <span class="oc-panel glyphicon glyphicon-chevron-up"></span></h4> </div> <div class="content-widget"> <?php if ($_templates && (count($_templates) > 0)) { ?> <ul> <?php foreach ($_templates as $temp) : ?> <li> <div class="checkbox"> <label> <?php echo form_radio(array('name' => 'temp_id', 'id' => 'temp-' . $temp->id, 'value' => $temp->id, 'data-news' => '0')); ?> <?php echo $temp->name; ?> </label> </div><!-- end checkbox --> <?php if ($temp->image != '') : ?> <figure class="text-center"> <img src="<?php echo $temp->image; ?>" class="img-responsive img-thumbnail" /> </figure> <?php endif; ?> </li> <?php endforeach; ?> </ul> <?php } else { ?> <p><?php echo $this->lang->line('cms_general_label_no_found'); ?></p> <?php } ?> </div><!-- end content-widget --> </div><!-- end wrapper-widget --> </div><!-- end sidebar-right --> </div><!-- end col-sm-4 --> </div><!-- end row --> <?php echo form_close(); ?> </div><!-- end panel-body --> </div><!-- end panel --> </div><!-- end col-sm-12 --> </div><!-- end row -->
gpl-3.0
vitoyan/Algorithms
DynamicProgramming/cutSteel.cpp
783
#include <iostream> #include <vector> #include <string> #include <iterator> #include <sstream> #include <stack> #include <limits> #include "./util/util.h" std::vector<int> cutSteel(std::vector<int> &p) { std::vector<int> m(p.size() + 1, 0); std::vector<int> s(p.size() + 1, 0); for(int j = 1; j <= (int)p.size(); j++) { for(int i = 1; i <= j; i++) { if(m[j] < (p[i - 1] + m[j - i])) { s[j] = i; m[j] = p[i - 1] + m[j - i]; } } } return s; } void printCutSolution(std::vector<int> s, int n) { if(s.empty() || n == 0) return; while(n > 0) { std::cout<<s[n]<<" "; n = n - s[n]; } std::cout<<std::endl; } int main() { std::vector<int> input; while(!getIntArrayFromConsole(input)); printCutSolution(cutSteel(input), input.size()); }
gpl-3.0
SzommerLaszlo/recommendation-engine
import-dataset/src/main/java/com/utcluj/recommender/dataset/batch/writers/PostItemWriter.java
3192
package com.utcluj.recommender.dataset.batch.writers; import com.utcluj.recommender.dataset.domain.Post; import com.utcluj.recommender.dataset.services.TagService; import org.springframework.batch.item.ItemWriter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BatchPreparedStatementSetter; import org.springframework.jdbc.core.JdbcOperations; import org.springframework.util.Assert; import org.springframework.util.StringUtils; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * Writer to handle the post related operations and validations. */ public class PostItemWriter implements ItemWriter<Post> { /** Writer to delegate to. */ private ItemWriter<Post> postItemWriter; /** Database template to handle the database operations. */ private JdbcOperations jdbcTemplate; /** Service for making the relations between tags and the post. */ private TagService tagService; @Override public void write(List<? extends Post> items) throws Exception { final List<Tuple<Long, Long>> postTagPairings = new ArrayList<>(); for (Post post : items) { if (StringUtils.hasText(post.getTags())) { post.setTagIds(new ArrayList<>()); String[] tags = post.getTags().split(">"); for (String tag : tags) { String curTag = tag; if (tag.startsWith("<")) { curTag = tag.substring(1); } long tagId = tagService.getTagId(curTag); post.getTagIds().add(tagId); postTagPairings.add(new Tuple<>(post.getId(), tagId)); } } } postItemWriter.write(items); jdbcTemplate.batchUpdate("insert into POST_TAG (POST_ID, TAG_ID) VALUES (?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setLong(1, postTagPairings.get(i).getKey()); ps.setLong(2, postTagPairings.get(i).getValue()); } @Override public int getBatchSize() { return postTagPairings.size(); } }); } public void setDelegateWriter(ItemWriter<Post> postItemWriter) { Assert.notNull(postItemWriter); this.postItemWriter = postItemWriter; } @Autowired public void setJdbcTemplate(JdbcOperations jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Autowired public void setTagService(TagService tagService) { this.tagService = tagService; } private class Tuple<T, D> { private final T key; private final D value; public Tuple(T key, D value) { this.key = key; this.value = value; } public T getKey() { return key; } public D getValue() { return value; } @Override public String toString() { return "key: " + key + " value: " + value; } } }
gpl-3.0
FinalsClub/djKarma
notes/management/commands/clean_courses.py
2129
from django.core.management.base import BaseCommand from notes.models import School, Course class Command(BaseCommand): args = 'none' help = ('Populates Courses with default School, semester, academic_year info if None. ' 'Also enforces uniqueness of (school, slug). ') def handle(self, *args, **options): length = len(Course.objects.all()) count = 0 # Count of models affected by this command duplicate_courses = [] # List of pk tuples corresponding to Courses with (school, slug) collision for course in Course.objects.all(): do_save = False if course.academic_year == None: course.academic_year = 2012 do_save = True self.stdout.write('Populated academic year for %s \n' % course.title) if course.school == None: # if null, set the school to Harvard course.school = School.objects.filter(pk=1)[0] do_save = True self.stdout.write('Populated school for %s \n' % course.title) if course.semester == None: course.semester = 1 do_save = True self.stdout.write('Populated semester for %s \n' % course.title) if do_save: count += 1 course.save() self.stdout.write('Populated default values for %d / %d courses\n' % (count, length)) for course in Course.objects.all(): for other_course in Course.objects.all(): if course.slug == other_course.slug and course.school == other_course.school and course.pk != other_course.pk: if (course.pk, other_course.pk) not in duplicate_courses and (other_course.pk, course.pk) not in duplicate_courses: duplicate_courses.append((course.pk, other_course.pk)) self.stdout.write('Duplicate courses: %s and %s titled: %s \n' % (course.pk, other_course.pk, course.slug)) self.stdout.write('Found %d duplicate courses \n' % len(duplicate_courses))
gpl-3.0
jabber-at/gajim
src/adhoc_commands.py
22981
# -*- coding: utf-8 -*- ## src/adhoc_commands.py ## ## Copyright (C) 2006 Nikos Kouremenos <kourem AT gmail.com> ## Copyright (C) 2006-2007 Tomasz Melcer <liori AT exroot.org> ## Copyright (C) 2006-2017 Yann Leboulanger <asterix AT lagaule.org> ## Copyright (C) 2008 Jonathan Schleifer <js-gajim AT webkeks.org> ## Stephan Erb <steve-e AT h3c.de> ## ## This file is part of Gajim. ## ## Gajim 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; version 3 only. ## ## Gajim 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 General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Gajim. If not, see <http://www.gnu.org/licenses/>. ## # FIXME: think if we need caching command list. it may be wrong if there will # be entities that often change the list, it may be slow to fetch it every time import gobject import gtk import nbxmpp from common import gajim from common import dataforms import gtkgui_helpers import dialogs import dataforms_widget class CommandWindow: """ Class for a window for single ad-hoc commands session Note, that there might be more than one for one account/jid pair in one moment. TODO: Maybe put this window into MessageWindow? consider this when it will be possible to manage more than one window of one. TODO: Account/jid pair in MessageWindowMgr. TODO: GTK 2.10 has a special wizard-widget, consider using it... """ def __init__(self, account, jid, commandnode=None): """ Create new window """ # an account object self.account = gajim.connections[account] self.jid = jid self.commandnode = commandnode self.data_form_widget = None # retrieving widgets from xml self.xml = gtkgui_helpers.get_gtk_builder('adhoc_commands_window.ui') self.window = self.xml.get_object('adhoc_commands_window') self.window.connect('delete-event', self.on_adhoc_commands_window_delete_event) for name in ('restart_button', 'back_button', 'forward_button', 'execute_button', 'finish_button', 'close_button', 'stages_notebook', 'retrieving_commands_stage_vbox', 'command_list_stage_vbox', 'command_list_vbox', 'sending_form_stage_vbox', 'sending_form_progressbar', 'notes_label', 'no_commands_stage_vbox', 'error_stage_vbox', 'error_description_label'): setattr(self, name, self.xml.get_object(name)) self.initiate() def initiate(self): self.pulse_id = None # to satisfy self.setup_pulsing() self.commandlist = None # a list of (commandname, commanddescription) # command's data self.sessionid = None self.dataform = None self.allow_stage3_close = False # creating data forms widget if self.data_form_widget: self.sending_form_stage_vbox.remove(self.data_form_widget) self.data_form_widget.destroy() self.data_form_widget = dataforms_widget.DataFormWidget() self.data_form_widget.show() self.sending_form_stage_vbox.pack_start(self.data_form_widget) if self.commandnode: # Execute command self.stage3() else: # setting initial stage self.stage1() # displaying the window self.window.set_title(_('Ad-hoc Commands - Gajim')) self.xml.connect_signals(self) self.window.show_all() self.restart_button.set_sensitive(False) # These functions are set up by appropriate stageX methods. def stage_finish(self, *anything): pass def stage_back_button_clicked(self, *anything): assert False def stage_forward_button_clicked(self, *anything): assert False def stage_execute_button_clicked(self, *anything): assert False def stage_close_button_clicked(self, *anything): assert False def stage_restart_button_clicked(self, *anything): assert False def stage_adhoc_commands_window_delete_event(self, *anything): assert False def do_nothing(self, *anything): return False # Widget callbacks... def on_back_button_clicked(self, *anything): return self.stage_back_button_clicked(*anything) def on_forward_button_clicked(self, *anything): return self.stage_forward_button_clicked(*anything) def on_execute_button_clicked(self, *anything): return self.stage_execute_button_clicked(*anything) def on_finish_button_clicked(self, *anything): return self.stage_finish_button_clicked(*anything) def on_close_button_clicked(self, *anything): return self.stage_close_button_clicked(*anything) def on_restart_button_clicked(self, *anything): return self.stage_restart_button_clicked(*anything) def on_adhoc_commands_window_destroy(self, *anything): # TODO: do all actions that are needed to remove this object from memory self.remove_pulsing() def on_adhoc_commands_window_delete_event(self, *anything): return self.stage_adhoc_commands_window_delete_event(self.window) def __del__(self): print 'Object has been deleted.' # stage 1: waiting for command list def stage1(self): """ Prepare the first stage. Request command list, set appropriate state of widgets """ # close old stage... self.stage_finish() # show the stage self.stages_notebook.set_current_page( self.stages_notebook.page_num( self.retrieving_commands_stage_vbox)) # set widgets' state self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(False) self.execute_button.set_sensitive(False) self.finish_button.set_sensitive(False) # request command list self.request_command_list() self.setup_pulsing( self.xml.get_object('retrieving_commands_progressbar')) # setup the callbacks self.stage_finish = self.stage1_finish self.stage_close_button_clicked = self.stage1_close_button_clicked self.stage_restart_button_clicked = self.stage1_restart_button_clicked self.stage_adhoc_commands_window_delete_event = \ self.stage1_adhoc_commands_window_delete_event def stage1_finish(self): self.remove_pulsing() def stage1_close_button_clicked(self, widget): # cancelling in this stage is not critical, so we don't # show any popups to user self.stage_finish() self.window.destroy() def stage1_restart_button_clicked(self, widget): self.stage_finish() self.restart() def stage1_adhoc_commands_window_delete_event(self, widget): self.stage1_finish() return True # stage 2: choosing the command to execute def stage2(self): """ Populate the command list vbox with radiobuttons FIXME: If there is more commands, maybe some kind of list, set widgets state """ # close old stage self.stage_finish() assert len(self.commandlist)>0 self.stages_notebook.set_current_page( self.stages_notebook.page_num(self.command_list_stage_vbox)) self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(True) self.execute_button.set_sensitive(False) self.finish_button.set_sensitive(False) # build the commands list radiobuttons first_radio = None for (commandnode, commandname) in self.commandlist: radio = gtk.RadioButton(first_radio, label=commandname) radio.connect("toggled", self.on_command_radiobutton_toggled, commandnode) if not first_radio: first_radio = radio self.commandnode = commandnode self.command_list_vbox.pack_start(radio, expand=False) self.command_list_vbox.show_all() self.stage_finish = self.stage2_finish self.stage_close_button_clicked = self.stage2_close_button_clicked self.stage_restart_button_clicked = self.stage2_restart_button_clicked self.stage_forward_button_clicked = self.stage2_forward_button_clicked self.stage_adhoc_commands_window_delete_event = self.do_nothing def stage2_finish(self): """ Remove widgets we created. Not needed when the window is destroyed """ def remove_widget(widget): self.command_list_vbox.remove(widget) self.command_list_vbox.foreach(remove_widget) def stage2_close_button_clicked(self, widget): self.stage_finish() self.window.destroy() def stage2_restart_button_clicked(self, widget): self.stage_finish() self.restart() def stage2_forward_button_clicked(self, widget): self.stage3() def on_command_radiobutton_toggled(self, widget, commandnode): self.commandnode = commandnode def on_check_commands_1_button_clicked(self, widget): self.stage1() # stage 3: command invocation def stage3(self): # close old stage self.stage_finish() assert isinstance(self.commandnode, unicode) self.form_status = None self.stages_notebook.set_current_page( self.stages_notebook.page_num( self.sending_form_stage_vbox)) self.restart_button.set_sensitive(True) self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(False) self.execute_button.set_sensitive(False) self.finish_button.set_sensitive(False) self.stage3_submit_form() self.stage_finish = self.stage3_finish self.stage_back_button_clicked = self.stage3_back_button_clicked self.stage_forward_button_clicked = self.stage3_forward_button_clicked self.stage_execute_button_clicked = self.stage3_execute_button_clicked self.stage_finish_button_clicked = self.stage3_finish_button_clicked self.stage_close_button_clicked = self.stage3_close_button_clicked self.stage_restart_button_clicked = self.stage3_restart_button_clicked self.stage_adhoc_commands_window_delete_event = \ self.stage3_close_button_clicked def stage3_finish(self): pass def stage3_can_close(self, cb): if self.form_status == 'completed': cb() return def on_yes(button): self.send_cancel() dialog.destroy() cb() dialog = dialogs.HigDialog(self.window, gtk.MESSAGE_WARNING, gtk.BUTTONS_YES_NO, _('Cancel confirmation'), _('You are in process of executing command. Do you really want to ' 'cancel it?'), on_response_yes=on_yes) dialog.popup() def stage3_close_button_clicked(self, widget): """ We are in the middle of executing command. Ask user if he really want to cancel the process, then cancel it """ # this works also as a handler for window_delete_event, so we have to # return appropriate values if self.allow_stage3_close: return False def on_ok(): self.allow_stage3_close = True self.window.destroy() self.stage3_can_close(on_ok) return True # Block event, don't close window def stage3_restart_button_clicked(self, widget): def on_ok(): self.restart() self.stage3_can_close(on_ok) def stage3_back_button_clicked(self, widget): self.stage3_submit_form('prev') def stage3_forward_button_clicked(self, widget): self.stage3_submit_form('next') def stage3_execute_button_clicked(self, widget): self.stage3_submit_form('execute') def stage3_finish_button_clicked(self, widget): self.stage3_submit_form('complete') def stage3_submit_form(self, action='execute'): self.data_form_widget.set_sensitive(False) if self.data_form_widget.get_data_form(): df = self.data_form_widget.get_data_form() if not df.is_valid(): dialogs.ErrorDialog(_('Invalid Form'), _('The form is not filled correctly.')) self.data_form_widget.set_sensitive(True) return self.data_form_widget.data_form.type_ = 'submit' else: self.data_form_widget.hide() self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(False) self.execute_button.set_sensitive(False) self.finish_button.set_sensitive(False) self.sending_form_progressbar.show() self.setup_pulsing(self.sending_form_progressbar) self.send_command(action) def stage3_next_form(self, command): if not isinstance(command, nbxmpp.Node): self.stage5(error=_('Service sent malformed data'), senderror=True) return self.remove_pulsing() self.sending_form_progressbar.hide() if not self.sessionid: self.sessionid = command.getAttr('sessionid') elif self.sessionid != command.getAttr('sessionid'): self.stage5(error=_('Service changed the session identifier.'), senderror=True) return self.form_status = command.getAttr('status') self.commandnode = command.getAttr('node') if command.getTag('x'): self.dataform = dataforms.ExtendForm(node=command.getTag('x')) self.data_form_widget.set_sensitive(True) try: self.data_form_widget.selectable = True self.data_form_widget.data_form = self.dataform except dataforms.Error: self.stage5(error=_('Service sent malformed data'), senderror=True) return self.data_form_widget.show() if self.data_form_widget.title: self.window.set_title(_('%s - Ad-hoc Commands - Gajim') % \ self.data_form_widget.title) else: self.data_form_widget.hide() actions = command.getTag('actions') if actions: # actions, actions, actions... self.close_button.set_sensitive(True) self.back_button.set_sensitive(actions.getTag('prev') is not None) self.forward_button.set_sensitive( actions.getTag('next') is not None) self.execute_button.set_sensitive(True) self.finish_button.set_sensitive(actions.getTag('complete') is not \ None) else: self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(False) self.execute_button.set_sensitive(True) self.finish_button.set_sensitive(False) if self.form_status == 'completed': self.close_button.set_sensitive(True) self.back_button.hide() self.forward_button.hide() self.execute_button.hide() self.finish_button.hide() self.close_button.show() self.stage_adhoc_commands_window_delete_event = \ self.stage3_close_button_clicked note = command.getTag('note') if note: self.notes_label.set_text(note.getData().decode('utf-8')) self.notes_label.set_no_show_all(False) self.notes_label.show() else: self.notes_label.set_no_show_all(True) self.notes_label.hide() def restart(self): self.commandnode = None self.initiate() # stage 4: no commands are exposed def stage4(self): """ Display the message. Wait for user to close the window """ # close old stage self.stage_finish() self.stages_notebook.set_current_page( self.stages_notebook.page_num(self.no_commands_stage_vbox)) self.close_button.set_sensitive(True) self.back_button.set_sensitive(False) self.forward_button.set_sensitive(False) self.execute_button.set_sensitive(False) self.finish_button.set_sensitive(False) self.stage_finish = self.do_nothing self.stage_close_button_clicked = self.stage4_close_button_clicked self.stage_restart_button_clicked = self.stage4_restart_button_clicked self.stage_adhoc_commands_window_delete_event = self.do_nothing def stage4_close_button_clicked(self, widget): self.window.destroy() def stage4_restart_button_clicked(self, widget): self.restart() def on_check_commands_2_button_clicked(self, widget): self.stage1() # stage 5: an error has occured def stage5(self, error=None, errorid=None, senderror=False): """ Display the error message. Wait for user to close the window """ # FIXME: sending error to responder # close old stage self.stage_finish() assert errorid or error if errorid: # we've got error code, display appropriate message try: errorname = nbxmpp.NS_STANZAS + ' ' + str(errorid) errordesc = nbxmpp.ERRORS[errorname][2] error = errordesc.decode('utf-8') del errorname, errordesc except KeyError: # when stanza doesn't have error description error = _('Service returned an error.') elif error: # we've got error message pass else: # we don't know what's that, bailing out assert False self.stages_notebook.set_current_page( self.stages_notebook.page_num(self.error_stage_vbox)) self.close_button.set_sensitive(True) self.back_button.hide() self.forward_button.hide() self.execute_button.hide() self.finish_button.hide() self.error_description_label.set_text(error) self.stage_finish = self.do_nothing self.stage_close_button_clicked = self.stage5_close_button_clicked self.stage_restart_button_clicked = self.stage5_restart_button_clicked self.stage_adhoc_commands_window_delete_event = self.do_nothing def stage5_close_button_clicked(self, widget): self.window.destroy() def stage5_restart_button_clicked(self, widget): self.restart() # helpers to handle pulsing in progressbar def setup_pulsing(self, progressbar): """ Set the progressbar to pulse. Makes a custom function to repeatedly call progressbar.pulse() method """ assert not self.pulse_id assert isinstance(progressbar, gtk.ProgressBar) def callback(): progressbar.pulse() return True # important to keep callback be called back! # 12 times per second (80 miliseconds) self.pulse_id = gobject.timeout_add(80, callback) def remove_pulsing(self): """ Stop pulsing, useful when especially when removing widget """ if self.pulse_id: gobject.source_remove(self.pulse_id) self.pulse_id = None # handling xml stanzas def request_command_list(self): """ Request the command list. Change stage on delivery """ query = nbxmpp.Iq(typ='get', to=nbxmpp.JID(self.jid), queryNS=nbxmpp.NS_DISCO_ITEMS) query.setQuerynode(nbxmpp.NS_COMMANDS) def callback(response): '''Called on response to query.''' # FIXME: move to connection_handlers.py # is error => error stage error = response.getError() if error: # extracting error description self.stage5(errorid=error) return # no commands => no commands stage # commands => command selection stage query = response.getTag('query') if query and query.getAttr('node') == nbxmpp.NS_COMMANDS: items = query.getTags('item') else: items = [] if len(items)==0: self.commandlist = [] self.stage4() else: self.commandlist = [(t.getAttr('node'), t.getAttr('name')) \ for t in items] self.stage2() self.account.connection.SendAndCallForResponse(query, callback) def send_command(self, action='execute'): """ Send the command with data form. Wait for reply """ # create the stanza assert isinstance(self.commandnode, unicode) assert action in ('execute', 'prev', 'next', 'complete') stanza = nbxmpp.Iq(typ='set', to=self.jid) cmdnode = stanza.addChild('command', namespace=nbxmpp.NS_COMMANDS, attrs={'node':self.commandnode, 'action':action}) if self.sessionid: cmdnode.setAttr('sessionid', self.sessionid) if self.data_form_widget.data_form: cmdnode.addChild(node=self.data_form_widget.data_form.get_purged()) def callback(response): # FIXME: move to connection_handlers.py err = response.getError() if err: self.stage5(errorid = err) else: self.stage3_next_form(response.getTag('command')) self.account.connection.SendAndCallForResponse(stanza, callback) def send_cancel(self): """ Send the command with action='cancel' """ assert self.commandnode if self.sessionid and self.account.connection: # we already have sessionid, so the service sent at least one reply. stanza = nbxmpp.Iq(typ='set', to=self.jid) stanza.addChild('command', namespace=nbxmpp.NS_COMMANDS, attrs={ 'node':self.commandnode, 'sessionid':self.sessionid, 'action':'cancel' }) self.account.connection.send(stanza) else: # we did not received any reply from service; # FIXME: we should wait and then send cancel; for now we do nothing pass
gpl-3.0
kallimachos/CodeEval
prime_palindrome.py
489
import math def is_prime(n): if n % 2 == 0 and n > 2: return False return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2)) def is_palindrome(n): front = [] back = [] for digit in str(n): front.append(digit) for digit in reversed(front): back.append(digit) if front == back: return True else: return False for x in range(1000, 1, -1): if is_prime(x) and is_palindrome(x): print(x) break
gpl-3.0
triguero/Keel3.0
src/keel/Algorithms/UnsupervisedLearning/AssociationRules/IntervalRuleLearning/EARMGA/Gene.java
3876
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera ([email protected]) L. Sánchez ([email protected]) J. Alcalá-Fdez ([email protected]) S. García ([email protected]) A. Fernández ([email protected]) J. Luengo ([email protected]) 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 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.UnsupervisedLearning.AssociationRules.IntervalRuleLearning.EARMGA; import java.util.*; public class Gene { public static final int NOMINAL = 0; public static final int INTEGER = 1; public static final int REAL = 2; private int attr; private int type; private ArrayList<Integer> value; public Gene() { this.value = new ArrayList<Integer>(); } public Gene copy() { int i; Gene gen = new Gene(); gen.attr = this.attr; gen.type = this.type; for (i=0; i < this.value.size(); i++) gen.value.add(new Integer(this.value.get(i).intValue())); return gen; } public int getAttr() { return attr; } public void setAttr(int attr) { this.attr = attr; } public int getType() { return type; } public void setType(int type) { this.type = type; } public ArrayList<Integer> getValue() { return this.value; } public int getValue(int pos) { return this.value.get(pos).intValue(); } public void setValue(ArrayList<Integer> newIntervals) { int i=0; this.value.clear(); for (i=0; i < newIntervals.size(); i++) this.value.add(new Integer (newIntervals.get(i).intValue())); } public void clearValue() { this.value.clear(); } /* public void removeValue(int pos) { this.value.remove(pos); } */ public void setValue(int inter) { this.value.clear(); this.value.add(new Integer (inter)); } public void addValue(int inter) { this.value.add(new Integer (inter)); } public boolean isUsed(int inter) { int i; for (i=0; i < this.value.size(); i++) { if (this.value.get(i).intValue()==inter) return (true); } return (false); } public int numIntervals() { return (this.value.size()); } public boolean isEqualValue(Gene gen) { int i, j; boolean found; if (this.value.size() != gen.value.size()) return (false); for (i=0; i < this.value.size(); i++) { found = false; for (j=0; j < gen.value.size() && !found; j++) { if (this.value.get(i).intValue() == gen.value.get(j).intValue()) found = true; } if (!found) return (false); } return (true); } public boolean isSubValue(Gene gen) { int i, j; boolean found; if (this.numIntervals() > gen.numIntervals()) return (false); for (i=0; i < this.numIntervals(); i++) { found = false; for (j=0; j < gen.numIntervals() && !found; j++) { if (this.getValue(i) == gen.getValue(j)) found = true; } if (!found) return (false); } return (true); } public String toString() { return "A: " + attr + "; T: " + type + "; V: " + value; } }
gpl-3.0
fanruan/finereport-design
designer_chart/src/com/fr/design/mainframe/chart/gui/style/series/Bar2DSeriesPane.java
2816
package com.fr.design.mainframe.chart.gui.style.series; import java.awt.Component; import javax.swing.JPanel; import javax.swing.JSeparator; import com.fr.chart.chartattr.Bar2DPlot; import com.fr.chart.chartattr.Plot; import com.fr.design.gui.frpane.UINumberDragPane; import com.fr.design.gui.ilable.UILabel; import com.fr.design.layout.TableLayout; import com.fr.design.layout.TableLayoutHelper; import com.fr.design.mainframe.chart.gui.ChartStylePane; import com.fr.design.mainframe.chart.gui.style.ChartBeautyPane; import com.fr.general.Inter; public class Bar2DSeriesPane extends AbstractPlotSeriesPane{ protected ChartBeautyPane stylePane; private UINumberDragPane seriesGap; private UINumberDragPane categoryGap; private static final double HUNDRED = 100.0; private static final double FIVE = 5.0; public Bar2DSeriesPane(ChartStylePane parent, Plot plot) { super(parent, plot, false); } public Bar2DSeriesPane(ChartStylePane parent, Plot plot, boolean custom) { super(parent, plot, true); } @Override protected JPanel getContentInPlotType() { seriesGap = new UINumberDragPane(-HUNDRED, HUNDRED); categoryGap = new UINumberDragPane(0, FIVE * HUNDRED); stylePane = new ChartBeautyPane(); double p = TableLayout.PREFERRED; double f = TableLayout.FILL; double[] columnSize = {p, f}; double[] rowSize = { p,p,p,p}; Component[][] components = new Component[][]{ new Component[]{stylePane, null}, new Component[]{new JSeparator(), null}, new Component[]{new UILabel(Inter.getLocText("FR-Chart-Gap_Series")), seriesGap}, new Component[]{new UILabel(Inter.getLocText("FR-Chart-Gap_Category")), categoryGap} }; return TableLayoutHelper.createTableLayoutPane(components,rowSize,columnSize); } public void populateBean(Plot plot) { super.populateBean(plot); if(plot instanceof Bar2DPlot) { Bar2DPlot barPlot = (Bar2DPlot)plot; if(stylePane != null) { stylePane.populateBean(barPlot.getPlotStyle()); } if(seriesGap != null) { seriesGap.populateBean(barPlot.getSeriesOverlapPercent() * HUNDRED); } if(categoryGap != null) { categoryGap.populateBean(barPlot.getCategoryIntervalPercent() * HUNDRED); } } } public void updateBean(Plot plot) { super.updateBean(plot); if(plot instanceof Bar2DPlot) { Bar2DPlot barPlot = (Bar2DPlot)plot; if(stylePane != null) { barPlot.setPlotStyle(stylePane.updateBean()); } if(seriesGap != null && !barPlot.isStacked()) { barPlot.setSeriesOverlapPercent(seriesGap.updateBean()/HUNDRED); } if(categoryGap != null) { barPlot.setCategoryIntervalPercent(categoryGap.updateBean()/HUNDRED); } } } }
gpl-3.0
clevernet/CleverNIM
views/site/login.php
1109
<?php /* @var $this SiteController */ /* @var $model LoginForm */ /* @var $form CActiveForm */ $this->pageTitle=Yii::app()->name . ' - Login'; $this->breadcrumbs=array( 'Login', ); ?> <h1>Login</h1> <p>Merci de fournir votre login et votre mot de passe Novell:</p> <div class="form"> <?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'login-form', 'type'=>'horizontal', 'enableClientValidation'=>true, 'htmlOptions' => array('class' => 'well'), 'clientOptions'=>array( 'validateOnSubmit'=>true, ), )); ?> <p class="note">Les champs avec <span class="required">*</span> sont requis.</p> <?php echo $form->textFieldRow($model,'username'); ?> <?php echo $form->passwordFieldRow($model,'password'); ?> <?php echo $form->checkBoxRow($model,'rememberMe'); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array( 'buttonType'=>'submit', 'type'=>'primary', 'label'=>'Login', )); ?> </div> <?php $this->endWidget(); ?> </div><!-- form -->
gpl-3.0
netik/chibios-orchard
ext/ugfx/docs/html/navtreeindex6.js
18572
var NAVTREEINDEX6 = { "group___progressbar.html#ga3a465c3b2ad152aaef1e1216001acf7e":[2,0,239,9], "group___progressbar.html#ga5c3be9e67dbb05bc935fde49c08da0e7":[0,13,1,6,10], "group___progressbar.html#ga5c3be9e67dbb05bc935fde49c08da0e7":[2,0,239,11], "group___progressbar.html#ga70753ef64f3be18cbebe10e64b394a7e":[0,13,1,6,1], "group___progressbar.html#ga70753ef64f3be18cbebe10e64b394a7e":[2,0,239,0], "group___progressbar.html#ga70753ef64f3be18cbebe10e64b394a7e":[2,0,238,0], "group___progressbar.html#ga794a9d287babde83ed5f20bc90bc7e5a":[2,0,238,6], "group___progressbar.html#ga794a9d287babde83ed5f20bc90bc7e5a":[0,13,1,6,6], "group___progressbar.html#ga794a9d287babde83ed5f20bc90bc7e5a":[2,0,239,7], "group___progressbar.html#ga913fee2e5b11f7513a5165c6ab627625":[0,13,1,6,4], "group___progressbar.html#ga913fee2e5b11f7513a5165c6ab627625":[2,0,239,5], "group___progressbar.html#ga913fee2e5b11f7513a5165c6ab627625":[2,0,238,4], "group___progressbar.html#ga9a8cc18c4aec11f4f28777001f4ed646":[0,13,1,6,9], "group___progressbar.html#ga9a8cc18c4aec11f4f28777001f4ed646":[2,0,239,10], "group___progressbar.html#ga9cd8e38c20b91e9e07e645b5af8c93b3":[2,0,238,3], "group___progressbar.html#ga9cd8e38c20b91e9e07e645b5af8c93b3":[2,0,239,4], "group___progressbar.html#ga9cd8e38c20b91e9e07e645b5af8c93b3":[0,13,1,6,3], "group___progressbar.html#gaae59c9e6124536698cd7c6f7285739a9":[0,13,1,6,2], "group___progressbar.html#gaae59c9e6124536698cd7c6f7285739a9":[2,0,239,1], "group___progressbar.html#gaae59c9e6124536698cd7c6f7285739a9":[2,0,238,1], "group___radio_button.html":[0,13,1,7], "group___radio_button.html#ga2d8105853946a03f5bb5a79cc221e7d7":[0,13,1,7,5], "group___radio_button.html#ga2d8105853946a03f5bb5a79cc221e7d7":[2,0,241,5], "group___radio_button.html#ga4476e99fb84a494cf3cd7cede20e5f42":[0,13,1,7,7], "group___radio_button.html#ga4476e99fb84a494cf3cd7cede20e5f42":[2,0,241,7], "group___radio_button.html#ga5c9f392635c3900bfaaccd85bcd2e913":[0,13,1,7,6], "group___radio_button.html#ga5c9f392635c3900bfaaccd85bcd2e913":[2,0,241,6], "group___radio_button.html#ga8d2dabb1d6eee4bf5e9a2573f87ed8ca":[0,13,1,7,9], "group___radio_button.html#ga8d2dabb1d6eee4bf5e9a2573f87ed8ca":[2,0,241,9], "group___radio_button.html#gaad72f9cd372e5d5bed094b148a256311":[0,13,1,7,10], "group___radio_button.html#gaad72f9cd372e5d5bed094b148a256311":[2,0,241,10], "group___radio_button.html#gab06dc981a7b33e0d034ae9c585f8d50e":[0,13,1,7,3], "group___radio_button.html#gab06dc981a7b33e0d034ae9c585f8d50e":[2,0,241,0], "group___radio_button.html#gadf09c711fa24ee2353cdd5253a351499":[0,13,1,7,4], "group___radio_button.html#gadf09c711fa24ee2353cdd5253a351499":[2,0,241,4], "group___radio_button.html#gaf35c2291e3bce960e252d925ad22de8b":[0,13,1,7,8], "group___radio_button.html#gaf35c2291e3bce960e252d925ad22de8b":[2,0,241,8], "group___renderings___button.html":[0,13,1,0,1], "group___renderings___button.html#ga0d3879e2c45c5d36d004826721292d8c":[0,13,1,0,1,6], "group___renderings___button.html#ga0d3879e2c45c5d36d004826721292d8c":[2,0,212,6], "group___renderings___button.html#ga2d7f47eac7b0e154c2b1d2cf21c91c57":[0,13,1,0,1,2], "group___renderings___button.html#ga2d7f47eac7b0e154c2b1d2cf21c91c57":[2,0,212,2], "group___renderings___button.html#ga4a25b291b0c4a3d788ed075b62615f43":[0,13,1,0,1,0], "group___renderings___button.html#ga4a25b291b0c4a3d788ed075b62615f43":[2,0,212,0], "group___renderings___button.html#ga7715bac2598dfec62ee579a9d6f6e2f0":[0,13,1,0,1,4], "group___renderings___button.html#ga7715bac2598dfec62ee579a9d6f6e2f0":[2,0,212,4], "group___renderings___button.html#ga976582adf1d141d077d36debcecec496":[2,0,212,5], "group___renderings___button.html#ga976582adf1d141d077d36debcecec496":[0,13,1,0,1,5], "group___renderings___button.html#gac8ca11362721cbe0a060cc738ff30b1e":[0,13,1,0,1,1], "group___renderings___button.html#gac8ca11362721cbe0a060cc738ff30b1e":[2,0,212,1], "group___renderings___button.html#gad7133bb00a3cb53e32244d044c30911d":[2,0,212,3], "group___renderings___button.html#gad7133bb00a3cb53e32244d044c30911d":[0,13,1,0,1,3], "group___renderings___button.html#gaf40a4c45f005d514b50b4cd7ac339c11":[0,13,1,0,1,7], "group___renderings___button.html#gaf40a4c45f005d514b50b4cd7ac339c11":[2,0,212,7], "group___renderings___checkbox.html":[0,13,1,1,0], "group___renderings___checkbox.html#ga410b726bc7ab08753754cfb3494a5837":[0,13,1,1,0,2], "group___renderings___checkbox.html#ga410b726bc7ab08753754cfb3494a5837":[2,0,213,3], "group___renderings___checkbox.html#ga410b726bc7ab08753754cfb3494a5837":[2,0,214,3], "group___renderings___checkbox.html#ga9ca982d80bc98c200089e217eef60921":[0,13,1,1,0,0], "group___renderings___checkbox.html#ga9ca982d80bc98c200089e217eef60921":[2,0,213,1], "group___renderings___checkbox.html#ga9ca982d80bc98c200089e217eef60921":[2,0,214,1], "group___renderings___checkbox.html#gad39ff7a19ee47cc1c4871bc20e51bc01":[0,13,1,1,0,1], "group___renderings___checkbox.html#gad39ff7a19ee47cc1c4871bc20e51bc01":[2,0,213,2], "group___renderings___checkbox.html#gad39ff7a19ee47cc1c4871bc20e51bc01":[2,0,214,2], "group___renderings___container.html":[0,13,0,0,0], "group___renderings___container.html#ga18cb067d6530a6d4bf0b4875b4105a91":[0,13,0,0,0,2], "group___renderings___container.html#ga18cb067d6530a6d4bf0b4875b4105a91":[2,0,219,2], "group___renderings___container.html#ga20cdce27a4eb1e7dffb541adfa961280":[0,13,0,0,0,0], "group___renderings___container.html#ga20cdce27a4eb1e7dffb541adfa961280":[2,0,219,0], "group___renderings___container.html#gad752b07ac8a1f867d8111bdf3a060ede":[0,13,0,0,0,1], "group___renderings___container.html#gad752b07ac8a1f867d8111bdf3a060ede":[2,0,219,1], "group___renderings___frame.html":[0,13,0,1,0], "group___renderings___frame.html#ga20271eb132a7f7b4ee5de90f1a92289b":[2,0,221,1], "group___renderings___frame.html#ga20271eb132a7f7b4ee5de90f1a92289b":[0,13,0,1,0,1], "group___renderings___frame.html#ga49c017776d9926c225ec1b7a32f1d136":[2,0,221,2], "group___renderings___frame.html#ga49c017776d9926c225ec1b7a32f1d136":[0,13,0,1,0,2], "group___renderings___frame.html#ga7d961a0ebef7b9b24c8178423b93af2e":[0,13,0,1,0,0], "group___renderings___frame.html#ga7d961a0ebef7b9b24c8178423b93af2e":[2,0,221,0], "group___renderings___keyboard.html":[0,13,1,3,1], "group___renderings___keyboard.html#gaf0e86c964bcaf6b3dda2032fc55807ba":[0,13,1,3,1,0], "group___renderings___keyboard.html#gaf0e86c964bcaf6b3dda2032fc55807ba":[2,0,229,1], "group___renderings___label.html":[0,13,1,4,0], "group___renderings___label.html#ga1b46f6c891d720c016428580b10772b3":[0,13,1,4,0,1], "group___renderings___label.html#ga1b46f6c891d720c016428580b10772b3":[2,0,233,2], "group___renderings___label.html#ga76d54b354d49fae4ed779146e74fd85a":[0,13,1,4,0,0], "group___renderings___label.html#ga76d54b354d49fae4ed779146e74fd85a":[2,0,233,1], "group___renderings___label.html#ga8b02298a8aa08748096f3d008416851e":[0,13,1,4,0,2], "group___renderings___label.html#ga8b02298a8aa08748096f3d008416851e":[2,0,233,3], "group___renderings___list.html":[0,13,1,5,2], "group___renderings___list.html#gaae5c507937fa32180a180da79508b8ed":[2,0,235,2], "group___renderings___list.html#gaae5c507937fa32180a180da79508b8ed":[0,13,1,5,2,0], "group___renderings___progressbar.html":[0,13,1,6,0], "group___renderings___progressbar.html#gaeaafc1ef8644ed159c7591ff9f223c6f":[2,0,238,2], "group___renderings___progressbar.html#gaeaafc1ef8644ed159c7591ff9f223c6f":[0,13,1,6,0,1], "group___renderings___progressbar.html#gaeaafc1ef8644ed159c7591ff9f223c6f":[2,0,239,3], "group___renderings___progressbar.html#gaeef2caa508b34a588fb260e52fd43410":[2,0,239,2], "group___renderings___progressbar.html#gaeef2caa508b34a588fb260e52fd43410":[0,13,1,6,0,0], "group___renderings___radiobutton.html":[0,13,1,7,2], "group___renderings___radiobutton.html#ga20079de84051bcd3b13164398aaab705":[0,13,1,7,2,0], "group___renderings___radiobutton.html#ga20079de84051bcd3b13164398aaab705":[2,0,241,1], "group___renderings___radiobutton.html#ga75f3ac1b35a6c7f4a80d0cedf15470f8":[0,13,1,7,2,1], "group___renderings___radiobutton.html#ga75f3ac1b35a6c7f4a80d0cedf15470f8":[2,0,241,2], "group___renderings___radiobutton.html#gafa74576fde8c6cdddc3dbde720492657":[2,0,241,3], "group___renderings___radiobutton.html#gafa74576fde8c6cdddc3dbde720492657":[0,13,1,7,2,2], "group___renderings___slider.html":[0,13,1,8,0], "group___renderings___slider.html#gaa7688cd4e4d839d908af699ffd47563d":[0,13,1,8,0,1], "group___renderings___slider.html#gaa7688cd4e4d839d908af699ffd47563d":[2,0,244,2], "group___renderings___slider.html#gaa7688cd4e4d839d908af699ffd47563d":[2,0,243,1], "group___renderings___slider.html#gaf6ca0a9f9a61bbde759babb774cb265d":[0,13,1,8,0,0], "group___renderings___slider.html#gaf6ca0a9f9a61bbde759babb774cb265d":[2,0,244,1], "group___renderings___tabset.html":[0,13,0,2,1], "group___renderings___tabset.html#ga156f210b7b294839542eda8b45ed7803":[0,13,0,2,1,2], "group___renderings___tabset.html#ga156f210b7b294839542eda8b45ed7803":[2,0,246,5], "group___renderings___tabset.html#ga634287acf93e7ab71847ce443fe863c2":[0,13,0,2,1,1], "group___renderings___tabset.html#ga634287acf93e7ab71847ce443fe863c2":[2,0,246,4], "group___renderings___tabset.html#ga64961d6bbacf13fa8b37468eed59a319":[0,13,0,2,1,0], "group___renderings___tabset.html#ga64961d6bbacf13fa8b37468eed59a319":[2,0,246,3], "group___renderings___textedit.html":[0,13,1,9,0], "group___renderings___textedit.html#ga3d7a8405d5ee676ba2cf4158e892d037":[0,13,1,9,0,0], "group___renderings___textedit.html#ga3d7a8405d5ee676ba2cf4158e892d037":[2,0,248,1], "group___slider.html":[0,13,1,8], "group___slider.html#ga4146842a167e63945760b6cbdabfe976":[2,0,244,3], "group___slider.html#ga4146842a167e63945760b6cbdabfe976":[0,13,1,8,2], "group___slider.html#ga4146842a167e63945760b6cbdabfe976":[2,0,243,2], "group___slider.html#ga570ed1fb76ee4dddddb95a2d96b52a18":[0,13,1,8,4], "group___slider.html#ga570ed1fb76ee4dddddb95a2d96b52a18":[2,0,243,4], "group___slider.html#ga570ed1fb76ee4dddddb95a2d96b52a18":[2,0,244,5], "group___slider.html#ga9f2f24309404cf3fca608ebe9713760a":[2,0,243,0], "group___slider.html#ga9f2f24309404cf3fca608ebe9713760a":[2,0,244,0], "group___slider.html#ga9f2f24309404cf3fca608ebe9713760a":[0,13,1,8,1], "group___slider.html#gaaf8619e080df43c3cc63bdd191fbcdbf":[2,0,244,7], "group___slider.html#gaaf8619e080df43c3cc63bdd191fbcdbf":[0,13,1,8,6], "group___slider.html#gab0beee066a1d1db54e376955b2eed994":[0,13,1,8,3], "group___slider.html#gab0beee066a1d1db54e376955b2eed994":[2,0,243,3], "group___slider.html#gab0beee066a1d1db54e376955b2eed994":[2,0,244,4], "group___slider.html#gad20c738c333f426bea4b6b2b12e532bb":[2,0,244,6], "group___slider.html#gad20c738c333f426bea4b6b2b12e532bb":[0,13,1,8,5], "group___tabset.html":[0,13,0,2], "group___tabset.html#ga44dd0ea88c7c24fc51ebe1fb734a13fa":[0,13,0,2,13], "group___tabset.html#ga44dd0ea88c7c24fc51ebe1fb734a13fa":[2,0,246,14], "group___tabset.html#ga8163774217d95181551af2a5b65311b6":[2,0,246,0], "group___tabset.html#ga8163774217d95181551af2a5b65311b6":[0,13,0,2,2], "group___tabset.html#ga8f9a0e2f474bfc4ca9c29bb7eb0aec7e":[0,13,0,2,11], "group___tabset.html#ga8f9a0e2f474bfc4ca9c29bb7eb0aec7e":[2,0,246,12], "group___tabset.html#ga97578d438231e0c4e10d194a99fbdba7":[0,13,0,2,7], "group___tabset.html#ga97578d438231e0c4e10d194a99fbdba7":[2,0,246,8], "group___tabset.html#ga9f49b15daa33eb041412dd504e0ec352":[2,0,246,2], "group___tabset.html#ga9f49b15daa33eb041412dd504e0ec352":[0,13,0,2,4], "group___tabset.html#gaac0e4a0248871002e6f52305f688d415":[0,13,0,2,3], "group___tabset.html#gaac0e4a0248871002e6f52305f688d415":[2,0,246,1], "group___tabset.html#gaacbf8243a3564084d7b18c760e1a71a5":[0,13,0,2,8], "group___tabset.html#gaacbf8243a3564084d7b18c760e1a71a5":[2,0,246,9], "group___tabset.html#gab683369faa610819bc1e0dceb9eb2583":[0,13,0,2,6], "group___tabset.html#gab683369faa610819bc1e0dceb9eb2583":[2,0,246,7], "group___tabset.html#gadb70994aa9a24681508b78cf7a3b76fe":[0,13,0,2,10], "group___tabset.html#gadb70994aa9a24681508b78cf7a3b76fe":[2,0,246,11], "group___tabset.html#gaec059bb92d28ab9c315810a18fd6b255":[0,13,0,2,12], "group___tabset.html#gaec059bb92d28ab9c315810a18fd6b255":[2,0,246,13], "group___tabset.html#gaf3ca5cfe7368f37be3eb55cfdc5a124a":[2,0,246,10], "group___tabset.html#gaf3ca5cfe7368f37be3eb55cfdc5a124a":[0,13,0,2,9], "group___tabset.html#gaf8120a4991e2de2b9bb5f280d55fd662":[0,13,0,2,5], "group___tabset.html#gaf8120a4991e2de2b9bb5f280d55fd662":[2,0,246,6], "group___text_edit.html":[0,13,1,9], "group___text_edit.html#gaa7348daa8486c5362d8a1f1a3ff5dba1":[2,0,248,0], "group___text_edit.html#gaa7348daa8486c5362d8a1f1a3ff5dba1":[0,13,1,9,1], "group___toggle.html":[0,7,3], "group___toggle.html#ga27ac510620308fc67e349d23e792330f":[0,7,3,1], "group___toggle.html#ga27ac510620308fc67e349d23e792330f":[2,0,144,1], "group___toggle.html#ga27ac510620308fc67e349d23e792330f":[2,0,143,1], "group___toggle.html#ga90339321e47146c6d38a0663de1b3701":[2,0,144,0], "group___toggle.html#ga90339321e47146c6d38a0663de1b3701":[0,7,3,0], "group___toggle.html#ga90339321e47146c6d38a0663de1b3701":[2,0,143,0], "group___toggle.html#gaafa468832c84ed480856b73d2b70d876":[2,0,144,2], "group___toggle.html#gaafa468832c84ed480856b73d2b70d876":[0,7,3,2], "group___toggle.html#gaafa468832c84ed480856b73d2b70d876":[2,0,143,2], "group___virtual_keyboard.html":[0,13,1,3], "group___virtual_keyboard.html#ga1e8ccd27a28408f1caeda3b67ab96b86":[0,13,1,3,6], "group___virtual_keyboard.html#ga1e8ccd27a28408f1caeda3b67ab96b86":[2,0,229,5], "group___virtual_keyboard.html#ga330fd93a1d2037e6b4420c6e2bb53308":[2,0,229,0], "group___virtual_keyboard.html#ga330fd93a1d2037e6b4420c6e2bb53308":[0,13,1,3,2], "group___virtual_keyboard.html#ga3a945a8b2bf8826d87d6b92a8bc942fb":[2,0,229,6], "group___virtual_keyboard.html#ga3a945a8b2bf8826d87d6b92a8bc942fb":[0,13,1,3,7], "group___virtual_keyboard.html#ga5e19207689c2d01098afa7cc8d262321":[0,13,1,3,4], "group___virtual_keyboard.html#ga5e19207689c2d01098afa7cc8d262321":[2,0,229,3], "group___virtual_keyboard.html#ga6d14e7ae18f8d0889d3d01ae8268d227":[0,13,1,3,5], "group___virtual_keyboard.html#ga6d14e7ae18f8d0889d3d01ae8268d227":[2,0,229,4], "group___virtual_keyboard.html#ga720063c721656da0793e4511f4b30cd5":[0,13,1,3,8], "group___virtual_keyboard.html#ga720063c721656da0793e4511f4b30cd5":[2,0,229,7], "group___virtual_keyboard.html#gafc464c45dbe13c3fed378ef58679a176":[2,0,229,2], "group___virtual_keyboard.html#gafc464c45dbe13c3fed378ef58679a176":[0,13,1,3,3], "group___widget.html":[0,13,1,10], "group___widget.html#ga0d2b40a6ef33c7be87f77876a94b9561":[0,13,1,10,20], "group___widget.html#ga0d2b40a6ef33c7be87f77876a94b9561":[2,0,250,15], "group___widget.html#ga1d2f107cdb9645526eda55df85c1beba":[2,0,250,7], "group___widget.html#ga1d2f107cdb9645526eda55df85c1beba":[0,13,1,10,12], "group___widget.html#ga235af9ded71d52a608838c36b149e67e":[2,0,250,18], "group___widget.html#ga235af9ded71d52a608838c36b149e67e":[0,13,1,10,23], "group___widget.html#ga2efa69b21320a19ab42e6ad910064e59":[2,0,250,0], "group___widget.html#ga2efa69b21320a19ab42e6ad910064e59":[0,13,1,10,5], "group___widget.html#ga3a35bac0f7341f513c87a4d0ac736d87":[0,13,1,10,24], "group___widget.html#ga3a35bac0f7341f513c87a4d0ac736d87":[2,0,250,19], "group___widget.html#ga435021b87d03934e5cedd59cd547fd36":[0,13,1,10,25], "group___widget.html#ga435021b87d03934e5cedd59cd547fd36":[2,0,250,20], "group___widget.html#ga47e1603199646a5389dc130106775a8a":[2,0,250,5], "group___widget.html#ga47e1603199646a5389dc130106775a8a":[0,13,1,10,10], "group___widget.html#ga5159c156ffbb3c679ce2949d13825a63":[2,0,250,10], "group___widget.html#ga5159c156ffbb3c679ce2949d13825a63":[0,13,1,10,15], "group___widget.html#ga5506100a7c7fdbcdbc762b54790cfb23":[2,0,250,9], "group___widget.html#ga5506100a7c7fdbcdbc762b54790cfb23":[0,13,1,10,14], "group___widget.html#ga5cb42f46952411f31609626101571307":[0,13,1,10,18], "group___widget.html#ga5cb42f46952411f31609626101571307":[2,0,250,13], "group___widget.html#ga609bb0a5d7481824a95648d49b4b54f0":[2,0,250,2], "group___widget.html#ga609bb0a5d7481824a95648d49b4b54f0":[0,13,1,10,7], "group___widget.html#ga63eeec716d0c83321bf7d8a9a2726876":[2,0,250,23], "group___widget.html#ga63eeec716d0c83321bf7d8a9a2726876":[0,13,1,10,28], "group___widget.html#ga6592f3945dde6d3e76912ffe004adc8c":[2,0,250,3], "group___widget.html#ga6592f3945dde6d3e76912ffe004adc8c":[0,13,1,10,8], "group___widget.html#ga6dcbcddff48888f1cba670eb9c720a63":[2,0,250,8], "group___widget.html#ga6dcbcddff48888f1cba670eb9c720a63":[0,13,1,10,13], "group___widget.html#ga8af9346b34dcdc9ffde7ae5e37f39258":[2,0,250,4], "group___widget.html#ga8af9346b34dcdc9ffde7ae5e37f39258":[0,13,1,10,9], "group___widget.html#gac7613b7fa8314148923c0e5a48a28191":[0,13,1,10,26], "group___widget.html#gac7613b7fa8314148923c0e5a48a28191":[2,0,250,21], "group___widget.html#gad099ae675c60bce48e485851ed8a552d":[0,13,1,10,29], "group___widget.html#gad099ae675c60bce48e485851ed8a552d":[2,0,250,24], "group___widget.html#gadf60a281daf59eb997dd8e42d13b55a1":[0,13,1,10,30], "group___widget.html#gadf60a281daf59eb997dd8e42d13b55a1":[2,0,250,25], "group___widget.html#gae7a414480b2c34040746ca897a189b70":[2,0,250,11], "group___widget.html#gae7a414480b2c34040746ca897a189b70":[0,13,1,10,16], "group___widget.html#gaeb5cd65e198446bf1eff188bbc4e21c8":[2,0,250,16], "group___widget.html#gaeb5cd65e198446bf1eff188bbc4e21c8":[0,13,1,10,21], "group___widget.html#gaeef41c6c192f93fada7f972ec0c8c1e0":[2,0,250,1], "group___widget.html#gaeef41c6c192f93fada7f972ec0c8c1e0":[0,13,1,10,6], "group___widget.html#gaf03b6b6a3798b9a94e7936fcbac63339":[2,0,250,12], "group___widget.html#gaf03b6b6a3798b9a94e7936fcbac63339":[0,13,1,10,17], "group___widget.html#gaf4620831126da1814296825baf56f00a":[2,0,250,22], "group___widget.html#gaf4620831126da1814296825baf56f00a":[0,13,1,10,27], "group___widget.html#gaf7b32299d79023ccb5db8c2510ff5ecd":[0,13,1,10,22], "group___widget.html#gaf7b32299d79023ccb5db8c2510ff5ecd":[2,0,250,17], "group___widget.html#gafb84c7bf263dba65fd32250ed14aec69":[2,0,250,14], "group___widget.html#gafb84c7bf263dba65fd32250ed14aec69":[0,13,1,10,19], "group___widget.html#gaff1e3d306137b1958d3c7df8e30e5f9b":[2,0,250,6], "group___widget.html#gaff1e3d306137b1958d3c7df8e30e5f9b":[0,13,1,10,11], "group___widgets.html":[0,13,1], "group___window.html":[0,13,2,0], "group___window.html#ga03754773124ae12518ed635a0f300f43":[2,0,210,23], "group___window.html#ga03754773124ae12518ed635a0f300f43":[0,13,2,0,25], "group___window.html#ga048d48b213074cf27d23b947b633e03b":[0,13,2,0,53], "group___window.html#ga048d48b213074cf27d23b947b633e03b":[2,0,210,51], "group___window.html#ga05e99b742e3d56bc5f52e05298b7a3e5":[0,13,2,0,60] };
gpl-3.0
bzcheeseman/NeuralNetworks
main.cpp
3490
// // Created by Aman LaChapelle on 9/18/16. // // NeuralNetworks // Copyright (C) 2016 Aman LaChapelle // // Full license at NeuralNetworks/LICENSE.txt // /* 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 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <string> #include <math.h> #include <ctime> #include "include/FFNetwork.hpp" #include "include/dataReader.hpp" #include "include/Activations.hpp" #include "include/CostFunctions.hpp" using namespace std; int main(int argc, char *argv[]){ gflags::ParseCommandLineFlags(&argc, &argv, true); std::vector<unsigned> topo = {4, 4, 3, 3}; std::vector<unsigned> dropout = {0, 1, 1, 0}; double eta = 5e-2; double l = 5e4; //this appears in a denominator - regularization parameter double gamma = 0.9; double epsilon = 1e-6; std::string backprop = "ADADELTA"; // AdaDelta seems to like the quadratic cost best, and is not happy with ReLU probably because gradients // are ill-formed (ish) - it's weird dataReader *train = new dataReader("/Users/Aman/code/NeuralNetworks/data/iris_training.dat", 4, 3); dataReader *validate = new dataReader("/Users/Aman/code/NeuralNetworks/data/iris_validation.dat", 4, 3); dataReader *test = new dataReader("/Users/Aman/code/NeuralNetworks/data/iris_test.dat", 4, 3); FFNetwork *net = new FFNetwork(topo, dropout, eta, l, gamma, epsilon); net->setFunctions(Sigmoid, SigmoidPrime, Identity, Bernoulli, truncate, QuadCost, QuadCostPrime); net->setBackpropAlgorithm(backprop.c_str()); int corr = 0; for (int i = 0; i < test->data->count; i++){ Eigen::VectorXi out = (*net)(test->data->inputs[i]); if (out == test->data->outputs[i].cast<int>()){ corr++; } } std::cout << "Before Training: " << corr << "/" << validate->data->count << " correct" << std::endl; int len = train->data->count; double goal = 1e-4; long max_epochs = 1e9; double min_gradient = 1e-5; net->Train(train->data, validate->data, goal, max_epochs, min_gradient); corr = 0; for (int i = 0; i < test->data->count; i++){ Eigen::VectorXi out = (*net)(test->data->inputs[i]); if (out == test->data->outputs[i].cast<int>()){ corr++; } } std::cout << "After Training: " << corr << "/" << test->data->count << " correct" << std::endl << std::endl; std::cout << "Raw network output on test dataset:" << std::endl; std::cout << net->feedForward(test->data->inputs[0]) << std::endl << std::endl; std::cout << "Truncated network output:" << std::endl; std::cout << (*net)(test->data->inputs[0]) << std::endl << std::endl; std::cout << "Corresponding correct output:" << std::endl; std::cout << test->data->outputs[0] << std::endl << std::endl; // std::cout << *net << std::endl; std::ofstream net_out("/users/aman/code/NeuralNetworks/logging/netTest.log"); net_out << *net; net_out.close(); return 0; }
gpl-3.0
tectronics/openjill
jn-file/src/main/java/org/jill/jn/SaveDataImpl.java
2435
package org.jill.jn; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.jill.file.FileAbstractByte; /** * Save data object (70 bytes lenght). * * @author Emeric MARTINEAU * @version 1.0 */ public class SaveDataImpl implements SaveData { /** * Display level. */ private final int level; /** * X-coordinate of object. */ private final int health; /** * Y-coordinate of object. */ private final int score; /** * List of inventory item (knife, gem...). */ private final List<Integer> inventory; /** * Offset in file of this record. */ private final int offset; /** * Constructor. * * @param jnFile file * * @throws IOException if error */ public SaveDataImpl(final FileAbstractByte jnFile) throws IOException { this.offset = (int) jnFile.getFilePointer(); level = jnFile.read16bitLE(); health = jnFile.read16bitLE(); final int nbInventory = jnFile.read16bitLE(); inventory = new ArrayList<>(nbInventory); int index; for (index = 0; index < nbInventory; index++) { inventory.add(jnFile.read16bitLE()); } final int skipEntry = MAX_INVENTORY_ENTRY - nbInventory; for (index = 0; index < skipEntry; index++) { jnFile.read16bitLE(); } score = jnFile.read32bitLE(); // Skip to go 70 bytes jnFile.skipBytes(SAVE_HOLE); } /** * Leve. * * @return level level */ @Override public final int getLevel() { return level; } /** * Health. * * @return health health */ @Override public final int getHealth() { return health; } /** * Score. * * @return score score */ @Override public final int getScore() { return score; } /** * Inventory. * * @return inventory inventory */ @Override public final List<Integer> getInventory() { return inventory; } /** * Return offset in file for this object. * * @return offset */ @Override public final int getOffset() { return offset; } }
mpl-2.0
seanmonstar/servo
src/components/script/dom/htmlanchorelement.rs
3330
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use dom::bindings::codegen::Bindings::HTMLAnchorElementBinding; use dom::bindings::codegen::InheritTypes::HTMLAnchorElementDerived; use dom::bindings::codegen::InheritTypes::{ElementCast, HTMLElementCast, NodeCast}; use dom::bindings::js::{JSRef, Temporary, OptionalRootable}; use dom::bindings::utils::{Reflectable, Reflector}; use dom::document::{Document, DocumentHelpers}; use dom::attr::AttrMethods; use dom::element::{Element, AttributeHandlers, HTMLAnchorElementTypeId}; use dom::event::{Event, EventMethods}; use dom::eventtarget::{EventTarget, NodeTargetTypeId}; use dom::htmlelement::HTMLElement; use dom::node::{Node, NodeHelpers, ElementNodeTypeId}; use dom::virtualmethods::VirtualMethods; use servo_util::namespace::Null; use servo_util::str::DOMString; #[deriving(Encodable)] pub struct HTMLAnchorElement { pub htmlelement: HTMLElement } impl HTMLAnchorElementDerived for EventTarget { fn is_htmlanchorelement(&self) -> bool { self.type_id == NodeTargetTypeId(ElementNodeTypeId(HTMLAnchorElementTypeId)) } } impl HTMLAnchorElement { pub fn new_inherited(localName: DOMString, document: &JSRef<Document>) -> HTMLAnchorElement { HTMLAnchorElement { htmlelement: HTMLElement::new_inherited(HTMLAnchorElementTypeId, localName, document) } } pub fn new(localName: DOMString, document: &JSRef<Document>) -> Temporary<HTMLAnchorElement> { let element = HTMLAnchorElement::new_inherited(localName, document); Node::reflect_node(box element, document, HTMLAnchorElementBinding::Wrap) } } pub trait HTMLAnchorElementMethods { } trait PrivateHTMLAnchorElementHelpers { fn handle_event_impl(&self, event: &JSRef<Event>); } impl<'a> PrivateHTMLAnchorElementHelpers for JSRef<'a, HTMLAnchorElement> { fn handle_event_impl(&self, event: &JSRef<Event>) { if "click" == event.Type().as_slice() && !event.DefaultPrevented() { let element: &JSRef<Element> = ElementCast::from_ref(self); let attr = element.get_attribute(Null, "href").root(); match attr { Some(ref href) => { let value = href.Value(); debug!("clicked on link to {:s}", value); let node: &JSRef<Node> = NodeCast::from_ref(self); let doc = node.owner_doc().root(); doc.load_anchor_href(value); } None => () } } } } impl<'a> VirtualMethods for JSRef<'a, HTMLAnchorElement> { fn super_type<'a>(&'a self) -> Option<&'a VirtualMethods+> { let htmlelement: &JSRef<HTMLElement> = HTMLElementCast::from_ref(self); Some(htmlelement as &VirtualMethods+) } fn handle_event(&self, event: &JSRef<Event>) { match self.super_type() { Some(s) => { s.handle_event(event); } None => {} } self.handle_event_impl(event); } } impl Reflectable for HTMLAnchorElement { fn reflector<'a>(&'a self) -> &'a Reflector { self.htmlelement.reflector() } }
mpl-2.0
DevinZ1993/LeetCode-Solutions
java/395.java
822
public class Solution { public int longestSubstring(String s, int k) { return solve(s, 0, s.length(), k); } private int solve(String s, int fromIdx, int toIdx, int k) { if (toIdx <= fromIdx) { return 0; } else { final int[] cnts = new int[26]; for (int i=fromIdx; i<toIdx; i++) { cnts[s.charAt(i)-'a']++; } int i = fromIdx, max = 0; for (int j=fromIdx; j<toIdx; j++) { final int idx = s.charAt(j)-'a'; if (cnts[idx] > 0 && cnts[idx] < k) { max = Math.max(max, solve(s, i, j, k)); i = j+1; } } return i == fromIdx? toIdx-fromIdx : Math.max(max, solve(s, i, toIdx, k)); } } }
mpl-2.0
lonnen/socorro
webapp-django/crashstats/signature/static/signature/js/signature_tab_reports.js
4836
/* global SignatureReport, socorro */ /** * Tab for displaying reports table. * Does not have any panels. * Controlled by a text input. * * @extends {SignatureReport.Tab} * @inheritdoc */ SignatureReport.ReportsTab = function (tabName) { var config = { panels: false, dataDisplayType: 'table', pagination: true, }; SignatureReport.Tab.call(this, tabName, config); }; SignatureReport.ReportsTab.prototype = SignatureReport.inherit(SignatureReport.Tab.prototype); // Extends loadControls to add a text input and some default fields. SignatureReport.ReportsTab.prototype.loadControls = function () { // For accessing this inside functions. var that = this; // Pick up necessary data from the DOM var columns = $('#mainbody').data('columns'); var fields = $('#mainbody').data('fields'); var sort = $('#mainbody').data('sort'); // Make the control elements: an input and an update button. // (The hidden input is for select2.) var columnsInputHidden = $('<input>', { type: 'hidden', name: '_columns', value: columns, }); this.$columnsInput = $('<input>', { type: 'text', name: '_columns_fake', value: columns, }); this.$sortInputHidden = $('<input>', { type: 'hidden', name: '_sort', value: sort, }); var updateButton = $('<button>', { type: 'submit', text: 'Update', }); // Append the controls. this.$controlsElement.append(this.$sortInputHidden, this.$columnsInput, columnsInputHidden, updateButton, $('<hr>')); // Make the columns input sortable. this.$columnsInput.select2({ data: fields, multiple: true, width: 'element', sortResults: socorro.search.sortResults, }); this.$columnsInput.on('change', function () { columnsInputHidden.val(that.$columnsInput.val()); }); this.$columnsInput .select2('container') .find('ul.select2-choices') .sortable({ containment: 'parent', start: function () { that.$columnsInput.select2('onSortStart'); }, update: function () { that.$columnsInput.select2('onSortEnd'); }, }); // On clicking the update button, loadContent is called. updateButton.on('click', function (e) { e.preventDefault(); that.loadContent(that.$contentElement); }); }; // Extends getParamsForUrl to do two extra things: // 1) add the columns parameters // 2) add the page parameter SignatureReport.ReportsTab.prototype.getParamsForUrl = function () { // Get the params as usual. var params = SignatureReport.getParamsWithSignature(); // Get the columns for the input. var columns = this.$columnsInput.select2('data'); if (columns) { params._columns = $.map(columns, function (column) { return column.id; }); } // Get the sort for the input. params._sort = this.$sortInputHidden.val().trim().split(',') || []; // Get the page number. params.page = this.page || SignatureReport.pageNum; return params; }; // Extends buildUrl to also replace the history. SignatureReport.ReportsTab.prototype.buildUrl = function (params) { // Build the query string. var queryString = '?' + Qs.stringify(params, { indices: false }); // Replace the history. window.history.replaceState(params, null, queryString); // Return the whole URL. return this.dataUrl + queryString; }; SignatureReport.ReportsTab.prototype.onAjaxSuccess = function (contentElement, data) { var tab = this; contentElement.empty().append($(data)); var headers = this.generateTablesorterHeaders($('.tablesorter')); // Disable sorting with the first column, `Crash ID` headers[0] = { sorter: false, }; $('.tablesorter').tablesorter({ headers: headers }); this.bindPaginationLinks(contentElement); // Make sure there are more than 1 page of results. If not, // do not activate server-side sorting, rely on the // default client-side sorting. if ($('.pagination a', contentElement).length) { $('.sort-header', contentElement).click(function (e) { e.preventDefault(); var thisElt = $(this); // Update the sort field. var fieldName = thisElt.data('field-name'); var sortArr = tab.$sortInputHidden.val().split(','); // First remove all previous mentions of that field. sortArr = sortArr.filter(function (item) { return item !== fieldName && item !== '-' + fieldName; }); // Now add it in the order that follows this sequence: // ascending -> descending -> none if (thisElt.hasClass('headerSortDown')) { sortArr.unshift('-' + fieldName); } else if (!thisElt.hasClass('headerSortDown') && !thisElt.hasClass('headerSortUp')) { sortArr.unshift(fieldName); } tab.$sortInputHidden.val(sortArr.join(',')); tab.loadContent(tab.$contentElement); }); } };
mpl-2.0
jaygumji/Enigma
Enigma/src/Enigma.Test/Properties/AssemblyInfo.cs
693
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("73b58b64-6bca-44ab-9b63-7a4b164fb1f8")]
mpl-2.0
terraform-providers/terraform-provider-aws
aws/resource_aws_config_configuration_aggregator_test.go
11973
package aws import ( "fmt" "log" "testing" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/service/configservice" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func init() { resource.AddTestSweepers("aws_config_configuration_aggregator", &resource.Sweeper{ Name: "aws_config_configuration_aggregator", F: testSweepConfigConfigurationAggregators, }) } func testSweepConfigConfigurationAggregators(region string) error { client, err := sharedClientForRegion(region) if err != nil { return fmt.Errorf("Error getting client: %s", err) } conn := client.(*AWSClient).configconn resp, err := conn.DescribeConfigurationAggregators(&configservice.DescribeConfigurationAggregatorsInput{}) if err != nil { if testSweepSkipSweepError(err) { log.Printf("[WARN] Skipping Config Configuration Aggregators sweep for %s: %s", region, err) return nil } return fmt.Errorf("Error retrieving config configuration aggregators: %s", err) } if len(resp.ConfigurationAggregators) == 0 { log.Print("[DEBUG] No config configuration aggregators to sweep") return nil } log.Printf("[INFO] Found %d config configuration aggregators", len(resp.ConfigurationAggregators)) for _, agg := range resp.ConfigurationAggregators { log.Printf("[INFO] Deleting config configuration aggregator %s", *agg.ConfigurationAggregatorName) _, err := conn.DeleteConfigurationAggregator(&configservice.DeleteConfigurationAggregatorInput{ ConfigurationAggregatorName: agg.ConfigurationAggregatorName, }) if err != nil { return fmt.Errorf("Error deleting config configuration aggregator %s: %s", *agg.ConfigurationAggregatorName, err) } } return nil } func TestAccAWSConfigConfigurationAggregator_account(t *testing.T) { var ca configservice.ConfigurationAggregator rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_config_configuration_aggregator.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSConfigConfigurationAggregatorDestroy, Steps: []resource.TestStep{ { Config: testAccAWSConfigConfigurationAggregatorConfig_account(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSConfigConfigurationAggregatorExists(resourceName, &ca), testAccCheckAWSConfigConfigurationAggregatorName(resourceName, rName, &ca), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.#", "1"), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.0.account_ids.#", "1"), testAccCheckResourceAttrAccountID(resourceName, "account_aggregation_source.0.account_ids.0"), resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.0.regions.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "account_aggregation_source.0.regions.0", "data.aws_region.current", "name"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSConfigConfigurationAggregator_organization(t *testing.T) { var ca configservice.ConfigurationAggregator rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_config_configuration_aggregator.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSConfigConfigurationAggregatorDestroy, Steps: []resource.TestStep{ { Config: testAccAWSConfigConfigurationAggregatorConfig_organization(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSConfigConfigurationAggregatorExists(resourceName, &ca), testAccCheckAWSConfigConfigurationAggregatorName(resourceName, rName, &ca), resource.TestCheckResourceAttr(resourceName, "name", rName), resource.TestCheckResourceAttr(resourceName, "organization_aggregation_source.#", "1"), resource.TestCheckResourceAttrPair(resourceName, "organization_aggregation_source.0.role_arn", "aws_iam_role.r", "arn"), resource.TestCheckResourceAttr(resourceName, "organization_aggregation_source.0.all_regions", "true"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, }, }) } func TestAccAWSConfigConfigurationAggregator_switch(t *testing.T) { rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_config_configuration_aggregator.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t); testAccOrganizationsAccountPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSConfigConfigurationAggregatorDestroy, Steps: []resource.TestStep{ { Config: testAccAWSConfigConfigurationAggregatorConfig_account(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.#", "1"), resource.TestCheckResourceAttr(resourceName, "organization_aggregation_source.#", "0"), ), }, { Config: testAccAWSConfigConfigurationAggregatorConfig_organization(rName), Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr(resourceName, "account_aggregation_source.#", "0"), resource.TestCheckResourceAttr(resourceName, "organization_aggregation_source.#", "1"), ), }, }, }) } func TestAccAWSConfigConfigurationAggregator_tags(t *testing.T) { var ca configservice.ConfigurationAggregator rName := acctest.RandomWithPrefix("tf-acc-test") resourceName := "aws_config_configuration_aggregator.example" resource.ParallelTest(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, CheckDestroy: testAccCheckAWSConfigConfigurationAggregatorDestroy, Steps: []resource.TestStep{ { Config: testAccAWSConfigConfigurationAggregatorConfig_tags(rName, "foo", "bar", "fizz", "buzz"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSConfigConfigurationAggregatorExists(resourceName, &ca), testAccCheckAWSConfigConfigurationAggregatorName(resourceName, rName, &ca), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), resource.TestCheckResourceAttr(resourceName, "tags.foo", "bar"), resource.TestCheckResourceAttr(resourceName, "tags.fizz", "buzz"), ), }, { Config: testAccAWSConfigConfigurationAggregatorConfig_tags(rName, "foo", "bar2", "fizz2", "buzz2"), Check: resource.ComposeTestCheckFunc( testAccCheckAWSConfigConfigurationAggregatorExists(resourceName, &ca), testAccCheckAWSConfigConfigurationAggregatorName(resourceName, rName, &ca), resource.TestCheckResourceAttr(resourceName, "tags.%", "3"), resource.TestCheckResourceAttr(resourceName, "tags.Name", rName), resource.TestCheckResourceAttr(resourceName, "tags.foo", "bar2"), resource.TestCheckResourceAttr(resourceName, "tags.fizz2", "buzz2"), ), }, { ResourceName: resourceName, ImportState: true, ImportStateVerify: true, }, { Config: testAccAWSConfigConfigurationAggregatorConfig_account(rName), Check: resource.ComposeTestCheckFunc( testAccCheckAWSConfigConfigurationAggregatorExists(resourceName, &ca), testAccCheckAWSConfigConfigurationAggregatorName(resourceName, rName, &ca), resource.TestCheckResourceAttr(resourceName, "tags.%", "0"), ), }, }, }) } func testAccCheckAWSConfigConfigurationAggregatorName(n, desired string, obj *configservice.ConfigurationAggregator) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not found: %s", n) } if rs.Primary.Attributes["name"] != *obj.ConfigurationAggregatorName { return fmt.Errorf("Expected name: %q, given: %q", desired, *obj.ConfigurationAggregatorName) } return nil } } func testAccCheckAWSConfigConfigurationAggregatorExists(n string, obj *configservice.ConfigurationAggregator) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { return fmt.Errorf("Not Found: %s", n) } if rs.Primary.ID == "" { return fmt.Errorf("No config configuration aggregator ID is set") } conn := testAccProvider.Meta().(*AWSClient).configconn out, err := conn.DescribeConfigurationAggregators(&configservice.DescribeConfigurationAggregatorsInput{ ConfigurationAggregatorNames: []*string{aws.String(rs.Primary.Attributes["name"])}, }) if err != nil { return fmt.Errorf("Failed to describe config configuration aggregator: %s", err) } if len(out.ConfigurationAggregators) < 1 { return fmt.Errorf("No config configuration aggregator found when describing %q", rs.Primary.Attributes["name"]) } ca := out.ConfigurationAggregators[0] *obj = *ca return nil } } func testAccCheckAWSConfigConfigurationAggregatorDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*AWSClient).configconn for _, rs := range s.RootModule().Resources { if rs.Type != "aws_config_configuration_aggregator" { continue } resp, err := conn.DescribeConfigurationAggregators(&configservice.DescribeConfigurationAggregatorsInput{ ConfigurationAggregatorNames: []*string{aws.String(rs.Primary.Attributes["name"])}, }) if err == nil { if len(resp.ConfigurationAggregators) != 0 && *resp.ConfigurationAggregators[0].ConfigurationAggregatorName == rs.Primary.Attributes["name"] { return fmt.Errorf("config configuration aggregator still exists: %s", rs.Primary.Attributes["name"]) } } } return nil } func testAccAWSConfigConfigurationAggregatorConfig_account(rName string) string { return fmt.Sprintf(` data "aws_region" "current" {} resource "aws_config_configuration_aggregator" "example" { name = %q account_aggregation_source { account_ids = [data.aws_caller_identity.current.account_id] regions = [data.aws_region.current.name] } } data "aws_caller_identity" "current" { } `, rName) } func testAccAWSConfigConfigurationAggregatorConfig_organization(rName string) string { return fmt.Sprintf(` resource "aws_organizations_organization" "test" {} resource "aws_config_configuration_aggregator" "example" { depends_on = [aws_iam_role_policy_attachment.example] name = %[1]q organization_aggregation_source { all_regions = true role_arn = aws_iam_role.example.arn } } data "aws_partition" "current" {} resource "aws_iam_role" "example" { name = %[1]q assume_role_policy = <<EOF { "Version": "2012-10-17", "Statement": [ { "Sid": "", "Effect": "Allow", "Principal": { "Service": "config.${data.aws_partition.current.dns_suffix}" }, "Action": "sts:AssumeRole" } ] } EOF } resource "aws_iam_role_policy_attachment" "example" { role = aws_iam_role.example.name policy_arn = "arn:${data.aws_partition.current.partition}:iam::aws:policy/service-role/AWSConfigRoleForOrganizations" } `, rName) } func testAccAWSConfigConfigurationAggregatorConfig_tags(rName, tagKey1, tagValue1, tagKey2, tagValue2 string) string { return fmt.Sprintf(` data "aws_region" "current" {} resource "aws_config_configuration_aggregator" "example" { name = %[1]q account_aggregation_source { account_ids = [data.aws_caller_identity.current.account_id] regions = [data.aws_region.current.name] } tags = { Name = %[1]q %[2]s = %[3]q %[4]s = %[5]q } } data "aws_caller_identity" "current" {} `, rName, tagKey1, tagValue1, tagKey2, tagValue2) }
mpl-2.0
codekidX/storage-chooser
storagechooser/src/main/java/com/codekidlabs/storagechooser/animators/MemorybarAnimation.java
838
package com.codekidlabs.storagechooser.animators; import android.view.animation.Animation; import android.view.animation.Transformation; import android.widget.ProgressBar; /** * display a nice animation when chooser dialog is shown */ public class MemorybarAnimation extends Animation { private ProgressBar progressBar; private float from; private float to; public MemorybarAnimation(ProgressBar progressBar, int from, int to) { this.progressBar = progressBar; this.from = from; this.to = to; } @Override protected void applyTransformation(float interpolatedTime, Transformation t) { super.applyTransformation(interpolatedTime, t); float animatedProgress = from + (to - from) * interpolatedTime; progressBar.setProgress((int) animatedProgress); } }
mpl-2.0
oracle/terraform-provider-baremetal
vendor/github.com/oracle/oci-go-sdk/v46/core/instance_pool_placement_configuration.go
2329
// Copyright (c) 2016, 2018, 2021, Oracle and/or its affiliates. All rights reserved. // This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may choose either license. // Code generated. DO NOT EDIT. // Core Services API // // API covering the Networking (https://docs.cloud.oracle.com/iaas/Content/Network/Concepts/overview.htm), // Compute (https://docs.cloud.oracle.com/iaas/Content/Compute/Concepts/computeoverview.htm), and // Block Volume (https://docs.cloud.oracle.com/iaas/Content/Block/Concepts/overview.htm) services. Use this API // to manage resources such as virtual cloud networks (VCNs), compute instances, and // block storage volumes. // package core import ( "github.com/oracle/oci-go-sdk/v46/common" ) // InstancePoolPlacementConfiguration The location for where an instance pool will place instances. type InstancePoolPlacementConfiguration struct { // The availability domain to place instances. // Example: `Uocm:PHX-AD-1` AvailabilityDomain *string `mandatory:"true" json:"availabilityDomain"` // The OCID (https://docs.cloud.oracle.com/iaas/Content/General/Concepts/identifiers.htm) of the primary subnet to place instances. PrimarySubnetId *string `mandatory:"true" json:"primarySubnetId"` // The fault domains to place instances. // If you don't provide any values, the system makes a best effort to distribute // instances across all fault domains based on capacity. // To distribute the instances evenly across selected fault domains, provide a // set of fault domains. For example, you might want instances to be evenly // distributed if your applications require high availability. // To get a list of fault domains, use the // ListFaultDomains operation // in the Identity and Access Management Service API. // Example: `[FAULT-DOMAIN-1, FAULT-DOMAIN-2, FAULT-DOMAIN-3]` FaultDomains []string `mandatory:"false" json:"faultDomains"` // The set of secondary VNIC data for instances in the pool. SecondaryVnicSubnets []InstancePoolPlacementSecondaryVnicSubnet `mandatory:"false" json:"secondaryVnicSubnets"` } func (m InstancePoolPlacementConfiguration) String() string { return common.PointerString(m) }
mpl-2.0
mozilla/kanbanzilla
test/spec/directives/growwhenclicked.js
409
'use strict'; describe('Directive: growwhenclicked', function () { beforeEach(module('kanbanzillaApp')); var element; it('should make hidden element visible', inject(function ($rootScope, $compile) { element = angular.element('<growwhenclicked></growwhenclicked>'); element = $compile(element)($rootScope); expect(element.text()).toBe('this is the growwhenclicked directive'); })); });
mpl-2.0
aviarypl/mozilla-l10n-addons-frontend
tests/unit/core/reducers/test_languageTools.js
1981
import reducer, { fetchLanguageTools, getAllLanguageTools, initialState, loadLanguageTools, } from 'core/reducers/languageTools'; import { createFakeLanguageTool } from 'tests/unit/helpers'; import { dispatchClientMetadata } from 'tests/unit/amo/helpers'; describe(__filename, () => { it('initializes properly', () => { const state = reducer(undefined, {}); expect(state).toEqual(initialState); }); it('stores language tools', () => { const language = createFakeLanguageTool(); const state = reducer( undefined, loadLanguageTools({ languageTools: [language], }), ); expect(state).toEqual({ byID: { [language.id]: language, }, }); }); it('ignores unrelated actions', () => { const language = createFakeLanguageTool(); const firstState = reducer( undefined, loadLanguageTools({ languageTools: [language], }), ); expect(reducer(firstState, { type: 'UNRELATED_ACTION' })).toEqual( firstState, ); }); describe('fetchLanguageTools', () => { it('requires an errorHandlerId', () => { expect(() => { fetchLanguageTools(); }).toThrow('errorHandlerId is required'); }); }); describe('loadLanguageTools', () => { it('requires language tools', () => { expect(() => { loadLanguageTools(); }).toThrow('languageTools are required'); }); }); describe('getAllLanguageTools', () => { it('returns an empty array when no languages are stored', () => { const { state } = dispatchClientMetadata(); expect(getAllLanguageTools(state)).toEqual([]); }); it('returns an array of languages', () => { const language = createFakeLanguageTool(); const { store } = dispatchClientMetadata(); store.dispatch(loadLanguageTools({ languageTools: [language] })); expect(getAllLanguageTools(store.getState())).toEqual([language]); }); }); });
mpl-2.0
CN-UPB/OpenBarista
components/decaf-masta/decaf_masta/components/database/public_port.py
1401
## # Copyright 2016 DECaF Project Group, University of Paderborn # This file is part of the decaf orchestration framework # All Rights Reserved. # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. ## __author__ = 'Kristian Hinnenthal' __date__ = '$13-okt-2015 14:15:27$' from sqlalchemy import Column, Integer, String, ForeignKey from sqlalchemy.orm import relationship from .mastadatabase import Base from .datacenter import Datacenter from sqlalchemy.dialects.postgresql import UUID class PublicPort(Base): __tablename__ = 'public_ports' public_port_id = Column(Integer, primary_key=True, autoincrement=True) vm_instance_id = Column(UUID(True), nullable=False) type = Column(String(250), nullable=False) interface_instance_id = Column(String(250), nullable=False) internal = Column(String(250), nullable=False) external = Column(String(250), nullable=False) physical_port = Column(String(250), nullable=False) port_os_id = Column(String(250), nullable=False) port_os_ip = Column(String(250), nullable=False) datacenter_id = Column(Integer, ForeignKey('datacenters.datacenter_id'), nullable=False) scenario_instance_id = Column(UUID(True), ForeignKey('scenarios.scenario_instance_id'), nullable=False)
mpl-2.0
tmhorne/celtx
xpcom/ds/nsCRT.cpp
11025
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is mozilla.org code. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either of the GNU General Public License Version 2 or later (the "GPL"), * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ /** * MODULE NOTES: * @update gess7/30/98 * * Much as I hate to do it, we were using string compares wrong. * Often, programmers call functions like strcmp(s1,s2), and pass * one or more null strings. Rather than blow up on these, I've * added quick checks to ensure that cases like this don't cause * us to fail. * * In general, if you pass a null into any of these string compare * routines, we simply return 0. */ #include "nsCRT.h" #include "nsIServiceManager.h" #include "nsCharTraits.h" #include "prbit.h" #define ADD_TO_HASHVAL(hashval, c) \ hashval = PR_ROTATE_LEFT32(hashval, 4) ^ (c); //---------------------------------------------------------------------- //////////////////////////////////////////////////////////////////////////////// // My lovely strtok routine #define IS_DELIM(m, c) ((m)[(c) >> 3] & (1 << ((c) & 7))) #define SET_DELIM(m, c) ((m)[(c) >> 3] |= (1 << ((c) & 7))) #define DELIM_TABLE_SIZE 32 char* nsCRT::strtok(char* string, const char* delims, char* *newStr) { NS_ASSERTION(string, "Unlike regular strtok, the first argument cannot be null."); char delimTable[DELIM_TABLE_SIZE]; PRUint32 i; char* result; char* str = string; for (i = 0; i < DELIM_TABLE_SIZE; i++) delimTable[i] = '\0'; for (i = 0; delims[i]; i++) { SET_DELIM(delimTable, static_cast<PRUint8>(delims[i])); } NS_ASSERTION(delims[i] == '\0', "too many delimiters"); // skip to beginning while (*str && IS_DELIM(delimTable, static_cast<PRUint8>(*str))) { str++; } result = str; // fix up the end of the token while (*str) { if (IS_DELIM(delimTable, static_cast<PRUint8>(*str))) { *str++ = '\0'; break; } str++; } *newStr = str; return str == result ? NULL : result; } //////////////////////////////////////////////////////////////////////////////// /** * Compare unichar string ptrs, stopping at the 1st null * NOTE: If both are null, we return 0. * NOTE: We terminate the search upon encountering a NULL * * @update gess 11/10/99 * @param s1 and s2 both point to unichar strings * @return 0 if they match, -1 if s1<s2; 1 if s1>s2 */ PRInt32 nsCRT::strcmp(const PRUnichar* s1, const PRUnichar* s2) { if(s1 && s2) { for (;;) { PRUnichar c1 = *s1++; PRUnichar c2 = *s2++; if (c1 != c2) { if (c1 < c2) return -1; return 1; } if ((0==c1) || (0==c2)) break; } } else { if (s1) // s2 must have been null return -1; if (s2) // s1 must have been null return 1; } return 0; } /** * Compare unichar string ptrs, stopping at the 1st null or nth char. * NOTE: If either is null, we return 0. * NOTE: We DO NOT terminate the search upon encountering NULL's before N * * @update gess 11/10/99 * @param s1 and s2 both point to unichar strings * @return 0 if they match, -1 if s1<s2; 1 if s1>s2 */ PRInt32 nsCRT::strncmp(const PRUnichar* s1, const PRUnichar* s2, PRUint32 n) { if(s1 && s2) { if(n != 0) { do { PRUnichar c1 = *s1++; PRUnichar c2 = *s2++; if (c1 != c2) { if (c1 < c2) return -1; return 1; } } while (--n != 0); } } return 0; } PRUnichar* nsCRT::strdup(const PRUnichar* str) { PRUint32 len = nsCRT::strlen(str); return strndup(str, len); } PRUnichar* nsCRT::strndup(const PRUnichar* str, PRUint32 len) { nsCppSharedAllocator<PRUnichar> shared_allocator; PRUnichar* rslt = shared_allocator.allocate(len + 1); // add one for the null // PRUnichar* rslt = new PRUnichar[len + 1]; if (rslt == NULL) return NULL; memcpy(rslt, str, len * sizeof(PRUnichar)); rslt[len] = 0; return rslt; } /** * |nsCRT::HashCode| is identical to |PL_HashString|, which tests * (http://bugzilla.mozilla.org/showattachment.cgi?attach_id=26596) * show to be the best hash among several other choices. * * We re-implement it here rather than calling it for two reasons: * (1) in this interface, we also calculate the length of the * string being hashed; and (2) the narrow and wide and `buffer' versions here * will hash equivalent strings to the same value, e.g., "Hello" and L"Hello". */ PRUint32 nsCRT::HashCode(const char* str, PRUint32* resultingStrLen) { PRUint32 h = 0; const char* s = str; if (!str) return h; unsigned char c; while ( (c = *s++) ) ADD_TO_HASHVAL(h, c); if ( resultingStrLen ) *resultingStrLen = (s-str)-1; return h; } PRUint32 nsCRT::HashCode(const char* start, PRUint32 length) { PRUint32 h = 0; const char* s = start; const char* end = start + length; unsigned char c; while ( s < end ) { c = *s++; ADD_TO_HASHVAL(h, c); } return h; } PRUint32 nsCRT::HashCode(const PRUnichar* str, PRUint32* resultingStrLen) { PRUint32 h = 0; const PRUnichar* s = str; if (!str) return h; PRUnichar c; while ( (c = *s++) ) ADD_TO_HASHVAL(h, c); if ( resultingStrLen ) *resultingStrLen = (s-str)-1; return h; } PRUint32 nsCRT::HashCodeAsUTF8(const PRUnichar* start, PRUint32 length) { PRUint32 h = 0; const PRUnichar* s = start; const PRUnichar* end = start + length; PRUint16 W1 = 0; // the first UTF-16 word in a two word tuple PRUint32 U = 0; // the current char as UCS-4 int code_length = 0; // the number of bytes in the UTF-8 sequence for the current char PRUint16 W; while ( s < end ) { W = *s++; /* * On the fly, decoding from UTF-16 (and/or UCS-2) into UTF-8 as per * http://www.ietf.org/rfc/rfc2781.txt * http://www.ietf.org/rfc/rfc3629.txt */ if ( !W1 ) { if ( !IS_SURROGATE(W) ) { U = W; if ( W <= 0x007F ) code_length = 1; else if ( W <= 0x07FF ) code_length = 2; else code_length = 3; } else if ( NS_IS_HIGH_SURROGATE(W) && s < end) { W1 = W; continue; } else { // Treat broken characters as the Unicode replacement // character 0xFFFD U = 0xFFFD; code_length = 3; NS_WARNING("Got low surrogate but no previous high surrogate"); } } else { // as required by the standard, this code is careful to // throw out illegal sequences if ( NS_IS_LOW_SURROGATE(W) ) { U = SURROGATE_TO_UCS4(W1, W); NS_ASSERTION(IS_VALID_CHAR(U), "How did this happen?"); code_length = 4; } else { // Treat broken characters as the Unicode replacement // character 0xFFFD U = 0xFFFD; code_length = 3; NS_WARNING("High surrogate not followed by low surrogate"); // The pointer to the next character points to the second 16-bit // value, not beyond it, as per Unicode 5.0.0 Chapter 3 C10, only // the first code unit of an illegal sequence must be treated as // an illegally terminated code unit sequence (also Chapter 3 // D91, "isolated [not paired and ill-formed] UTF-16 code units // in the range D800..DFFF are ill-formed"). --s; } W1 = 0; } static const PRUint16 sBytePrefix[5] = { 0x0000, 0x0000, 0x00C0, 0x00E0, 0x00F0 }; static const PRUint16 sShift[5] = { 0, 0, 6, 12, 18 }; /* * Unlike the algorithm in * http://www.ietf.org/rfc/rfc3629.txt we must calculate the * bytes in left to right order so that our hash result * matches what the narrow version would calculate on an * already UTF-8 string. */ // hash the first (and often, only, byte) ADD_TO_HASHVAL(h, (sBytePrefix[code_length] | (U>>sShift[code_length]))); // an unrolled loop for hashing any remaining bytes in this // sequence switch ( code_length ) { // falling through in each case case 4: ADD_TO_HASHVAL(h, (0x80 | ((U>>12) & 0x003F))); case 3: ADD_TO_HASHVAL(h, (0x80 | ((U>>6 ) & 0x003F))); case 2: ADD_TO_HASHVAL(h, (0x80 | ( U & 0x003F))); default: code_length = 0; break; } } return h; } PRUint32 nsCRT::BufferHashCode(const PRUnichar* s, PRUint32 len) { PRUint32 h = 0; const PRUnichar* done = s + len; while ( s < done ) h = PR_ROTATE_LEFT32(h, 4) ^ PRUint16(*s++); // cast to unsigned to prevent possible sign extension return h; } // This should use NSPR but NSPR isn't exporting its PR_strtoll function // Until then... PRInt64 nsCRT::atoll(const char *str) { if (!str) return LL_Zero(); PRInt64 ll = LL_Zero(), digitll = LL_Zero(); while (*str && *str >= '0' && *str <= '9') { LL_MUL(ll, ll, 10); LL_UI2L(digitll, (*str - '0')); LL_ADD(ll, ll, digitll); str++; } return ll; }
mpl-2.0
CoderLine/alphaTab
src/rendering/glyphs/ChordDiagramGlyph.ts
5998
import { Chord } from '@src/model/Chord'; import { ICanvas, TextAlign, TextBaseline } from '@src/platform/ICanvas'; import { EffectGlyph } from '@src/rendering/glyphs/EffectGlyph'; import { MusicFontSymbol } from '@src/model/MusicFontSymbol'; import { RenderingResources } from '@src/RenderingResources'; export class ChordDiagramGlyph extends EffectGlyph { private static readonly Padding: number = 5; private static readonly Frets: number = 5; private static readonly CircleRadius: number = 2.5; private static readonly StringSpacing: number = 10; private static readonly FretSpacing: number = 12; private _chord: Chord; private _textRow: number = 0; private _fretRow: number = 0; private _firstFretSpacing: number = 0; public constructor(x: number, y: number, chord: Chord) { super(x, y); this._chord = chord; } public override doLayout(): void { super.doLayout(); const scale = this.scale; let res: RenderingResources = this.renderer.resources; this._textRow = res.effectFont.size * 1.5 * scale; this._fretRow = res.effectFont.size * 1.5 * scale; if (this._chord.firstFret > 1) { this._firstFretSpacing = ChordDiagramGlyph.FretSpacing * scale; } else { this._firstFretSpacing = 0; } this.height = this._textRow + this._fretRow + (ChordDiagramGlyph.Frets - 1) * ChordDiagramGlyph.FretSpacing * scale + 2 * ChordDiagramGlyph.Padding * scale; this.width = this._firstFretSpacing + (this._chord.staff.tuning.length - 1) * ChordDiagramGlyph.StringSpacing * scale + 2 * ChordDiagramGlyph.Padding * scale; } public override paint(cx: number, cy: number, canvas: ICanvas): void { cx += this.x + ChordDiagramGlyph.Padding * this.scale + this._firstFretSpacing; cy += this.y; let w: number = this.width - 2 * ChordDiagramGlyph.Padding * this.scale + this.scale - this._firstFretSpacing; let stringSpacing: number = ChordDiagramGlyph.StringSpacing * this.scale; let fretSpacing: number = ChordDiagramGlyph.FretSpacing * this.scale; let res: RenderingResources = this.renderer.resources; let circleRadius: number = ChordDiagramGlyph.CircleRadius * this.scale; let align: TextAlign = canvas.textAlign; let baseline: TextBaseline = canvas.textBaseline; canvas.font = res.effectFont; canvas.textAlign = TextAlign.Center; canvas.textBaseline = TextBaseline.Top; if (this._chord.showName) { canvas.fillText(this._chord.name, cx + this.width / 2, cy + res.effectFont.size / 2); } cy += this._textRow; cx += stringSpacing / 2; canvas.font = res.fretboardNumberFont; canvas.textBaseline = TextBaseline.Middle; for (let i: number = 0; i < this._chord.staff.tuning.length; i++) { let x: number = cx + i * stringSpacing; let y: number = cy + this._fretRow / 2; let fret: number = this._chord.strings[this._chord.staff.tuning.length - i - 1]; if (fret < 0) { canvas.fillMusicFontSymbol(x, y, this.scale, MusicFontSymbol.FretboardX, true); } else if (fret === 0) { canvas.fillMusicFontSymbol(x, y, this.scale, MusicFontSymbol.FretboardO, true); } else { fret -= this._chord.firstFret - 1; canvas.fillText(fret.toString(), x, y); } } cy += this._fretRow; for (let i: number = 0; i < this._chord.staff.tuning.length; i++) { let x: number = cx + i * stringSpacing; canvas.fillRect(x, cy, 1, fretSpacing * ChordDiagramGlyph.Frets + this.scale); } if (this._chord.firstFret > 1) { canvas.textAlign = TextAlign.Left; canvas.fillText(this._chord.firstFret.toString(), cx - this._firstFretSpacing, cy + fretSpacing / 2); } canvas.fillRect(cx, cy - this.scale, w, 2 * this.scale); for (let i: number = 0; i <= ChordDiagramGlyph.Frets; i++) { let y: number = cy + i * fretSpacing; canvas.fillRect(cx, y, w, this.scale); } let barreLookup = new Map<number, number[]>(); for (let barreFret of this._chord.barreFrets) { let strings: number[] = [-1, -1]; barreLookup.set(barreFret - this._chord.firstFret, strings); } for (let guitarString: number = 0; guitarString < this._chord.strings.length; guitarString++) { let fret: number = this._chord.strings[guitarString]; if (fret > 0) { fret -= this._chord.firstFret; if (barreLookup.has(fret)) { let info = barreLookup.get(fret)!; if (info[0] === -1 || guitarString < info[0]) { info[0] = guitarString; } if (info[1] === -1 || guitarString > info[1]) { info[1] = guitarString; } } let y: number = cy + fret * fretSpacing + fretSpacing / 2 + 0.5 * this.scale; let x: number = cx + (this._chord.strings.length - guitarString - 1) * stringSpacing; canvas.fillCircle(x, y, circleRadius); } } for(const [fret, strings] of barreLookup) { let y: number = cy + fret * fretSpacing + fretSpacing / 2 + 0.5 * this.scale; let xLeft: number = cx + (this._chord.strings.length - strings[1] - 1) * stringSpacing; let xRight: number = cx + (this._chord.strings.length - strings[0] - 1) * stringSpacing; canvas.fillRect(xLeft, y - circleRadius, xRight - xLeft, circleRadius * 2); } canvas.textAlign = align; canvas.textBaseline = baseline; } }
mpl-2.0
SergeantHawke/Steampunk
vendor/phpixie/cache/classes/PHPixie/Cache/Memcache.php
1174
<?php namespace PHPixie\Cache; /** * Memcache cache driver. * @package Cache */ class Memcache extends Cache { /** * Memcache instance * @var Memcache * @access protected */ protected $_memcache; /** * Creates a memcache cache instance. * * @param string $config Name of the configuration to initialize * @access public */ public function __construct($pixie, $config) { parent::__construct($pixie, $config); $this->_memcache = new \Memcache(); $connected = $this->_memcache->connect( $this->pixie->config->get("cache.{$config}.memcached_host"), $this->pixie->config->get("cache.{$config}.memcached_port") ); if (!$connected) throw new Exception("Could not connect to memcached server"); } protected function _set($key, $value, $lifetime) { if (!$this->_memcache->replace($key, $value, false, $lifetime)) $this->_memcache->set($key, $value, false, $lifetime); } protected function _get($key) { if ($data = $this->_memcache->get($key)) return $data; } public function clear() { $this->_memcache->flush(); } protected function _delete($key) { $this->_memcache->delete($key); } }
mpl-2.0
jaygumji/Enigma
Enigma/src/Enigma.PerformanceTest/ProtoBufTimesTest.cs
1538
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks; using Enigma.Testing.Fakes.Entities; namespace Enigma.ProofOfConcept { public class ProtoBufTimesTest : IConsoleCommand { public void Invoke() { var graph = DataBlock.Filled(); var watch = new Stopwatch(); watch.Start(); Console.WriteLine("Initializing ProtoBuf.NET serialization test..."); var protobuf = new ProtocolBuffer.ProtocolBufferBinaryConverter<DataBlock>(); var length = protobuf.Convert(graph).Length; Console.WriteLine("Initialization time: " + watch.Elapsed); Console.WriteLine("MinSize of data: " + length); watch.Restart(); for (var i = 0; i < 10000; i++) { protobuf.Convert(graph); } Console.WriteLine("Serialization time: " + watch.Elapsed); watch.Restart(); Parallel.For(0, 10000, new ParallelOptions { MaxDegreeOfParallelism = 4 }, (idx) => { protobuf.Convert(graph); }); Console.WriteLine("Parallel serialization time: " + watch.Elapsed); Console.WriteLine("Enigma serialization test completed"); } } }
mpl-2.0
jembi/openhim-encounter-orchestrator
src/main/java/org/hl7/v3/Supine.java
738
package org.hl7.v3; import javax.xml.bind.annotation.XmlEnum; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Supine. * * <p>The following schema fragment specifies the expected content contained within this class. * <p> * <pre> * &lt;simpleType name="Supine"> * &lt;restriction base="{urn:hl7-org:v3}cs"> * &lt;enumeration value="SUP"/> * &lt;enumeration value="RTRD"/> * &lt;enumeration value="TRD"/> * &lt;/restriction> * &lt;/simpleType> * </pre> * */ @XmlType(name = "Supine") @XmlEnum public enum Supine { SUP, RTRD, TRD; public String value() { return name(); } public static Supine fromValue(String v) { return valueOf(v); } }
mpl-2.0
tmhorne/celtx
extensions/irc/xul/content/about/about.js
5286
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (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.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is ChatZilla. * * The Initial Developer of the Original Code is James Ross. * Portions created by the Initial Developer are Copyright (C) 2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * James Ross <[email protected]> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ var ownerClient = null; // To be able to load static.js, we need a few things defined first: function CIRCNetwork() {} function CIRCServer() {} function CIRCChannel() {} function CIRCUser() {} function CIRCChanUser() {} function CIRCDCCUser() {} function CIRCDCCChat() {} function CIRCDCCFile() {} function CIRCDCCFileTransfer() {} // Our friend from messages.js: function getMsg(msgName, params, deflt) { return client.messageManager.getMsg(msgName, params, deflt); } function onLoad() { const propsPath = "chrome://chatzilla/locale/chatzilla.properties"; // Find our owner, if we have one. ownerClient = window.arguments ? window.arguments[0].client : null; if (ownerClient) ownerClient.aboutDialog = window; client.entities = new Object(); client.messageManager = new MessageManager(client.entities); client.messageManager.loadBrands(); client.defaultBundle = client.messageManager.addBundle(propsPath); var version = getVersionInfo(); client.userAgent = getMsg(MSG_VERSION_REPLY, [version.cz, version.ua]); var verLabel = document.getElementById("version"); var verString = verLabel.getAttribute("format").replace("%S", version.cz); verLabel.setAttribute("value", verString); verLabel.setAttribute("condition", __cz_condition); var localizers = document.getElementById("localizers"); var localizerNames = getMsg("locale.authors", null, ""); if (localizerNames && (localizerNames.substr(0, 11) != "XXX REPLACE")) { localizerNames = localizerNames.split(/\s*;\s*/); for (var i = 0; i < localizerNames.length; i++) { var loc = document.createElement("label"); loc.setAttribute("value", localizerNames[i]); localizers.appendChild(loc); } } else { var localizersHeader = document.getElementById("localizers-header"); localizersHeader.style.display = "none"; localizers.style.display = "none"; } if (window.opener) { // Force the window to be the right size now, not later. window.sizeToContent(); // Position it centered over, but never up or left of parent. var opener = window.opener; var sx = Math.max((opener.outerWidth - window.outerWidth ) / 2, 0); var sy = Math.max((opener.outerHeight - window.outerHeight) / 2, 0); window.moveTo(opener.screenX + sx, opener.screenY + sy); } /* Find and focus the dialog's default button (OK), otherwise the focus * lands on the first focusable content - the homepage link. Links in XUL * look horrible when focused. */ var binding = document.documentElement; var defaultButton = binding.getButton(binding.defaultButton); if (defaultButton) setTimeout(function() { defaultButton.focus() }, 0); } function onUnload() { if (ownerClient) delete ownerClient.aboutDialog; } function copyVersion() { const cbID = Components.interfaces.nsIClipboard.kGlobalClipboard; var cb = getService("@mozilla.org/widget/clipboard;1", "nsIClipboard"); var tr = newObject("@mozilla.org/widget/transferable;1", "nsITransferable"); var str = newObject("@mozilla.org/supports-string;1", "nsISupportsString"); str.data = client.userAgent; tr.setTransferData("text/unicode", str, str.data.length * 2); cb.setData(tr, null, cbID); } function openHomepage() { if (ownerClient) ownerClient.dispatch("goto-url", {url: MSG_SOURCE_REPLY}); else window.opener.open(MSG_SOURCE_REPLY, "_blank"); }
mpl-2.0
tmhorne/celtx
embedding/tests/wxEmbed/GeckoWindowCreator.cpp
2416
/* ***** BEGIN LICENSE BLOCK ***** * Version: Mozilla-sample-code 1.0 * * Copyright (c) 2002 Netscape Communications Corporation and * other contributors * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this Mozilla sample 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. * * Contributor(s): * Adam Lock <[email protected]> * * ***** END LICENSE BLOCK ***** */ #include "GeckoWindowCreator.h" #include "GeckoContainer.h" #include "nsIWebBrowserChrome.h" #include "nsString.h" GeckoWindowCreator::GeckoWindowCreator() { } GeckoWindowCreator::~GeckoWindowCreator() { } NS_IMPL_ISUPPORTS1(GeckoWindowCreator, nsIWindowCreator) NS_IMETHODIMP GeckoWindowCreator::CreateChromeWindow(nsIWebBrowserChrome *parent, PRUint32 chromeFlags, nsIWebBrowserChrome **_retval) { NS_ENSURE_ARG_POINTER(_retval); *_retval = nsnull; if (!parent) return NS_ERROR_FAILURE; nsCOMPtr<nsIGeckoContainer> geckoContainer = do_QueryInterface(parent); if (!geckoContainer) return NS_ERROR_FAILURE; nsCAutoString role; geckoContainer->GetRole(role); if (stricmp(role.get(), "browser") == 0) { GeckoContainerUI *pUI = NULL; geckoContainer->GetContainerUI(&pUI); if (pUI) { return pUI->CreateBrowserWindow(chromeFlags, parent, _retval); } } return NS_ERROR_FAILURE; }
mpl-2.0
aalgo/TSCBPT
include/tsc/bpt/TemporalStability.hpp
3330
/* * TemporalStability.hpp * * Copyright (c) 2015 Alberto Alonso Gonzalez * * This Source Code Form is subject to the terms of the * Mozilla Public License, v. 2.0. * If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. * * Created on: 17/07/2015 * Author: Alberto Alonso-Gonzalez */ #ifndef TEMPORALSTABILITY_HPP_ #define TEMPORALSTABILITY_HPP_ #include <armadillo> #include <functional> namespace tscbpt { template <class NodePointer, class ValueType = double> struct GeodesicVectorChangeMeasureFull: public std::unary_function<NodePointer, ValueType> { ValueType operator()(const NodePointer a) const { ValueType res = ValueType(); const size_t covariances = a->getModel().getNumCovariances(); const size_t comparations = covariances - 1; arma::cx_mat vma[covariances]; for(size_t i = 0; i < covariances; ++i){ vma[i] = to_arma<arma::cx_mat>::from(a->getModel().getCovariance(i)); } #pragma omp parallel for num_threads(min(static_cast<int>(comparations), omp_get_max_threads())) schedule(dynamic, 1) shared(vma) reduction(+:res) default(none) for(size_t i = 0; i < comparations; ++i){ for(size_t j = i+1; j < covariances; ++j){ arma::cx_vec eigval; arma::cx_mat eigvec; arma::eig_gen(eigval, eigvec, solve(vma[i], vma[j])); res += sqrt(accu(pow(log(abs(eigval)),2))); } } return res / (comparations*covariances/2.0); } }; template <class NodePointer, class ValueType = double> struct DiagonalGeodesicVectorChangeMeasureFull: public std::unary_function<NodePointer, ValueType> { ValueType operator()(NodePointer a) const { static const ValueType DG_MIN_THRESHOLD = 1e-12; ValueType res = ValueType(); for(size_t i = 0; i < a->getModel().getNumCovariances() - 1; ++i){ for(size_t j = i+1; j < a->getModel().getNumCovariances(); ++j){ double tmp = 0; for(size_t k = 0; k < a->getModel().subMatrix_size; ++k){ tmp += pow(log(max(a->getModel().getCovariance(i)(k, k).real(), DG_MIN_THRESHOLD) / max(a->getModel().getCovariance(j)(k, k).real(), DG_MIN_THRESHOLD)), 2); } res += sqrt(tmp); } } return res / ((a->getModel().getNumCovariances() - 1) * (a->getModel().getNumCovariances()) / 2); } }; template <class NodePointer, class SimilarityMeasure, class ValueType = double> struct SimilarityToRegion: public std::unary_function<NodePointer, ValueType> { SimilarityToRegion(NodePointer pRefNode, SimilarityMeasure pSim = SimilarityMeasure()) : refNode(pRefNode), measure(pSim){ } ValueType operator()(NodePointer a) const { return measure(refNode, a); } private: NodePointer refNode; SimilarityMeasure measure; }; template <class NodePointer, class ValueType = double> struct GeodesicVectorPairChangeMeasure: public std::unary_function<NodePointer, ValueType> { GeodesicVectorPairChangeMeasure(size_t a, size_t b): _a(a), _b(b){} ValueType operator()(const NodePointer a) const { arma::cx_vec eigval; arma::cx_mat eigvec; arma::eig_gen(eigval, eigvec, solve( to_arma<arma::cx_mat>::from(a->getModel().getCovariance(_a)), to_arma<arma::cx_mat>::from(a->getModel().getCovariance(_b)))); return ValueType(sqrt(accu(pow(log(abs(eigval)),2)))); } private: size_t _a, _b; }; } /* namespace tscbpt */ #endif /* TEMPORALSTABILITY_HPP_ */
mpl-2.0
leowmjw/consul
command/agent/command_test.go
10813
package agent import ( "fmt" "log" "os" "os/exec" "path/filepath" "reflect" "strings" "testing" "github.com/hashicorp/consul/command/base" "github.com/hashicorp/consul/testutil" "github.com/hashicorp/consul/testutil/retry" "github.com/hashicorp/consul/version" "github.com/mitchellh/cli" ) func baseCommand(ui *cli.MockUi) base.Command { return base.Command{ Flags: base.FlagSetNone, UI: ui, } } func TestCommand_implements(t *testing.T) { var _ cli.Command = new(Command) } func TestValidDatacenter(t *testing.T) { shouldMatch := []string{ "dc1", "east-aws-001", "PROD_aws01-small", } noMatch := []string{ "east.aws", "east!aws", "first,second", } for _, m := range shouldMatch { if !validDatacenter.MatchString(m) { t.Fatalf("expected match: %s", m) } } for _, m := range noMatch { if validDatacenter.MatchString(m) { t.Fatalf("expected no match: %s", m) } } } // TestConfigFail should test command line flags that lead to an immediate error. func TestConfigFail(t *testing.T) { tests := []struct { args []string out string }{ { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise", "0.0.0.0"}, out: "==> Advertise address cannot be 0.0.0.0\n", }, { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise", "::"}, out: "==> Advertise address cannot be ::\n", }, { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise", "[::]"}, out: "==> Advertise address cannot be [::]\n", }, { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise-wan", "0.0.0.0"}, out: "==> Advertise WAN address cannot be 0.0.0.0\n", }, { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise-wan", "::"}, out: "==> Advertise WAN address cannot be ::\n", }, { args: []string{"agent", "-server", "-data-dir", "foo", "-advertise-wan", "[::]"}, out: "==> Advertise WAN address cannot be [::]\n", }, } for _, tt := range tests { t.Run(strings.Join(tt.args, " "), func(t *testing.T) { cmd := exec.Command("consul", tt.args...) b, err := cmd.CombinedOutput() if got, want := err, "exit status 1"; got == nil || got.Error() != want { t.Fatalf("got err %q want %q", got, want) } if got, want := string(b), tt.out; got != want { t.Fatalf("got %q want %q", got, want) } }) } } func TestRetryJoin(t *testing.T) { dir, agent := makeAgent(t, nextConfig()) defer os.RemoveAll(dir) defer agent.Shutdown() conf2 := nextConfig() tmpDir := testutil.TempDir(t, "consul") defer os.RemoveAll(tmpDir) doneCh := make(chan struct{}) shutdownCh := make(chan struct{}) defer func() { close(shutdownCh) <-doneCh }() cmd := &Command{ Version: version.Version, ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } serfAddr := fmt.Sprintf( "%s:%d", agent.config.BindAddr, agent.config.Ports.SerfLan) serfWanAddr := fmt.Sprintf( "%s:%d", agent.config.BindAddr, agent.config.Ports.SerfWan) args := []string{ "-server", "-bind", agent.config.BindAddr, "-data-dir", tmpDir, "-node", fmt.Sprintf(`"%s"`, conf2.NodeName), "-advertise", agent.config.BindAddr, "-retry-join", serfAddr, "-retry-interval", "1s", "-retry-join-wan", serfWanAddr, "-retry-interval-wan", "1s", } go func() { if code := cmd.Run(args); code != 0 { log.Printf("bad: %d", code) } close(doneCh) }() retry.Run(t, func(r *retry.R) { if got, want := len(agent.LANMembers()), 2; got != want { r.Fatalf("got %d LAN members want %d", got, want) } if got, want := len(agent.WANMembers()), 2; got != want { r.Fatalf("got %d WAN members want %d", got, want) } }) } func TestReadCliConfig(t *testing.T) { tmpDir := testutil.TempDir(t, "consul") defer os.RemoveAll(tmpDir) shutdownCh := make(chan struct{}) defer close(shutdownCh) // Test config parse { cmd := &Command{ args: []string{ "-data-dir", tmpDir, "-node", `"a"`, "-advertise-wan", "1.2.3.4", "-serf-wan-bind", "4.3.2.1", "-serf-lan-bind", "4.3.2.2", "-node-meta", "somekey:somevalue", }, ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } config := cmd.readConfig() if config.AdvertiseAddrWan != "1.2.3.4" { t.Fatalf("expected -advertise-addr-wan 1.2.3.4 got %s", config.AdvertiseAddrWan) } if config.SerfWanBindAddr != "4.3.2.1" { t.Fatalf("expected -serf-wan-bind 4.3.2.1 got %s", config.SerfWanBindAddr) } if config.SerfLanBindAddr != "4.3.2.2" { t.Fatalf("expected -serf-lan-bind 4.3.2.2 got %s", config.SerfLanBindAddr) } if len(config.Meta) != 1 || config.Meta["somekey"] != "somevalue" { t.Fatalf("expected somekey=somevalue, got %v", config.Meta) } } // Test multiple node meta flags { cmd := &Command{ args: []string{ "-data-dir", tmpDir, "-node-meta", "somekey:somevalue", "-node-meta", "otherkey:othervalue", }, ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } expected := map[string]string{ "somekey": "somevalue", "otherkey": "othervalue", } config := cmd.readConfig() if !reflect.DeepEqual(config.Meta, expected) { t.Fatalf("bad: %v %v", config.Meta, expected) } } // Test LeaveOnTerm and SkipLeaveOnInt defaults for server mode { ui := new(cli.MockUi) cmd := &Command{ args: []string{ "-node", `"server1"`, "-server", "-data-dir", tmpDir, }, ShutdownCh: shutdownCh, Command: baseCommand(ui), } config := cmd.readConfig() if config == nil { t.Fatalf(`Expected non-nil config object: %s`, ui.ErrorWriter.String()) } if config.Server != true { t.Errorf(`Expected -server to be true`) } if (*config.LeaveOnTerm) != false { t.Errorf(`Expected LeaveOnTerm to be false in server mode`) } if (*config.SkipLeaveOnInt) != true { t.Errorf(`Expected SkipLeaveOnInt to be true in server mode`) } } // Test LeaveOnTerm and SkipLeaveOnInt defaults for client mode { ui := new(cli.MockUi) cmd := &Command{ args: []string{ "-data-dir", tmpDir, "-node", `"client"`, }, ShutdownCh: shutdownCh, Command: baseCommand(ui), } config := cmd.readConfig() if config == nil { t.Fatalf(`Expected non-nil config object: %s`, ui.ErrorWriter.String()) } if config.Server != false { t.Errorf(`Expected server to be false`) } if (*config.LeaveOnTerm) != true { t.Errorf(`Expected LeaveOnTerm to be true in client mode`) } if *config.SkipLeaveOnInt != false { t.Errorf(`Expected SkipLeaveOnInt to be false in client mode`) } } // Test empty node name { cmd := &Command{ args: []string{"-node", `""`}, ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } config := cmd.readConfig() if config != nil { t.Errorf(`Expected -node="" to fail`) } } } func TestRetryJoinFail(t *testing.T) { conf := nextConfig() tmpDir := testutil.TempDir(t, "consul") defer os.RemoveAll(tmpDir) shutdownCh := make(chan struct{}) defer close(shutdownCh) cmd := &Command{ ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } serfAddr := fmt.Sprintf("%s:%d", conf.BindAddr, conf.Ports.SerfLan) args := []string{ "-bind", conf.BindAddr, "-data-dir", tmpDir, "-retry-join", serfAddr, "-retry-max", "1", "-retry-interval", "10ms", } if code := cmd.Run(args); code == 0 { t.Fatalf("bad: %d", code) } } func TestRetryJoinWanFail(t *testing.T) { conf := nextConfig() tmpDir := testutil.TempDir(t, "consul") defer os.RemoveAll(tmpDir) shutdownCh := make(chan struct{}) defer close(shutdownCh) cmd := &Command{ ShutdownCh: shutdownCh, Command: baseCommand(new(cli.MockUi)), } serfAddr := fmt.Sprintf("%s:%d", conf.BindAddr, conf.Ports.SerfWan) args := []string{ "-server", "-bind", conf.BindAddr, "-data-dir", tmpDir, "-retry-join-wan", serfAddr, "-retry-max-wan", "1", "-retry-interval-wan", "10ms", } if code := cmd.Run(args); code == 0 { t.Fatalf("bad: %d", code) } } func TestDiscoverEC2Hosts(t *testing.T) { if os.Getenv("AWS_REGION") == "" { t.Skip("AWS_REGION not set, skipping") } if os.Getenv("AWS_ACCESS_KEY_ID") == "" { t.Skip("AWS_ACCESS_KEY_ID not set, skipping") } if os.Getenv("AWS_SECRET_ACCESS_KEY") == "" { t.Skip("AWS_SECRET_ACCESS_KEY not set, skipping") } c := &Config{ RetryJoinEC2: RetryJoinEC2{ Region: os.Getenv("AWS_REGION"), TagKey: "ConsulRole", TagValue: "Server", }, } servers, err := c.discoverEc2Hosts(&log.Logger{}) if err != nil { t.Fatal(err) } if len(servers) != 3 { t.Fatalf("bad: %v", servers) } } func TestDiscoverGCEHosts(t *testing.T) { if os.Getenv("GCE_PROJECT") == "" { t.Skip("GCE_PROJECT not set, skipping") } if os.Getenv("GOOGLE_APPLICATION_CREDENTIALS") == "" && os.Getenv("GCE_CONFIG_CREDENTIALS") == "" { t.Skip("GOOGLE_APPLICATION_CREDENTIALS or GCE_CONFIG_CREDENTIALS not set, skipping") } c := &Config{ RetryJoinGCE: RetryJoinGCE{ ProjectName: os.Getenv("GCE_PROJECT"), ZonePattern: os.Getenv("GCE_ZONE"), TagValue: "consulrole-server", CredentialsFile: os.Getenv("GCE_CONFIG_CREDENTIALS"), }, } servers, err := c.discoverGCEHosts(log.New(os.Stderr, "", log.LstdFlags)) if err != nil { t.Fatal(err) } if len(servers) != 3 { t.Fatalf("bad: %v", servers) } } func TestProtectDataDir(t *testing.T) { dir := testutil.TempDir(t, "consul") defer os.RemoveAll(dir) if err := os.MkdirAll(filepath.Join(dir, "mdb"), 0700); err != nil { t.Fatalf("err: %v", err) } cfgFile := testutil.TempFile(t, "consul") defer os.Remove(cfgFile.Name()) content := fmt.Sprintf(`{"server": true, "data_dir": "%s"}`, dir) _, err := cfgFile.Write([]byte(content)) if err != nil { t.Fatalf("err: %v", err) } ui := new(cli.MockUi) cmd := &Command{ Command: baseCommand(ui), args: []string{"-config-file=" + cfgFile.Name()}, } if conf := cmd.readConfig(); conf != nil { t.Fatalf("should fail") } if out := ui.ErrorWriter.String(); !strings.Contains(out, dir) { t.Fatalf("expected mdb dir error, got: %s", out) } } func TestBadDataDirPermissions(t *testing.T) { dir := testutil.TempDir(t, "consul") defer os.RemoveAll(dir) dataDir := filepath.Join(dir, "mdb") if err := os.MkdirAll(dataDir, 0400); err != nil { t.Fatalf("err: %v", err) } defer os.RemoveAll(dataDir) ui := new(cli.MockUi) cmd := &Command{ Command: baseCommand(ui), args: []string{"-data-dir=" + dataDir, "-server=true"}, } if conf := cmd.readConfig(); conf != nil { t.Fatalf("Should fail with bad data directory permissions") } if out := ui.ErrorWriter.String(); !strings.Contains(out, "Permission denied") { t.Fatalf("expected permission denied error, got: %s", out) } }
mpl-2.0
DO-CV/sara
cpp/src/DO/Shakti/Halide/Resize.hpp
3811
// ========================================================================== // // This file is part of Sara, a basic set of libraries in C++ for computer // vision. // // Copyright (C) 2013-present David Ok <[email protected]> // // This Source Code Form is subject to the terms of the Mozilla Public // License v. 2.0. If a copy of the MPL was not distributed with this file, // you can obtain one at http://mozilla.org/MPL/2.0/. // ========================================================================== // //! @file #pragma once #include <DO/Sara/Core/Tensor.hpp> #include <DO/Shakti/Halide/Utilities.hpp> #include "shakti_enlarge_gpu.h" #include "shakti_reduce_32f_gpu.h" #include "shakti_scale_32f_gpu.h" namespace DO::Shakti::HalideBackend { auto scale(::Halide::Runtime::Buffer<float>& src, ::Halide::Runtime::Buffer<float>& dst) { shakti_scale_32f_gpu(src, dst.width(), dst.height(), dst); } auto reduce(::Halide::Runtime::Buffer<float>& src, ::Halide::Runtime::Buffer<float>& dst) { shakti_reduce_32f_gpu(src, dst.width(), dst.height(), dst); } auto enlarge(::Halide::Runtime::Buffer<float>& src, ::Halide::Runtime::Buffer<float>& dst) { shakti_enlarge_gpu(src, // src.width(), src.height(), // dst.width(), dst.height(), // dst); } auto scale(Sara::ImageView<float>& src, Sara::ImageView<float>& dst) { auto src_tensor_view = tensor_view(src).reshape( Eigen::Vector4i{1, 1, src.height(), src.width()}); auto dst_tensor_view = tensor_view(dst).reshape( Eigen::Vector4i{1, 1, dst.height(), dst.width()}); auto src_buffer = as_runtime_buffer(src_tensor_view); auto dst_buffer = as_runtime_buffer(dst_tensor_view); src_buffer.set_host_dirty(); dst_buffer.set_host_dirty(); scale(src_buffer, dst_buffer); dst_buffer.copy_to_host(); } auto reduce(Sara::ImageView<float>& src, Sara::ImageView<float>& dst) { auto src_tensor_view = tensor_view(src).reshape( Eigen::Vector4i{1, 1, src.height(), src.width()}); auto dst_tensor_view = tensor_view(dst).reshape( Eigen::Vector4i{1, 1, dst.height(), dst.width()}); auto src_buffer = as_runtime_buffer(src_tensor_view); auto dst_buffer = as_runtime_buffer(dst_tensor_view); src_buffer.set_host_dirty(); reduce(src_buffer, dst_buffer); dst_buffer.copy_to_host(); } auto enlarge(Sara::ImageView<float>& src, Sara::ImageView<float>& dst) { auto src_tensor_view = tensor_view(src).reshape( Eigen::Vector4i{1, 1, src.height(), src.width()}); auto dst_tensor_view = tensor_view(dst).reshape( Eigen::Vector4i{1, 1, dst.height(), dst.width()}); auto src_buffer = as_runtime_buffer(src_tensor_view); auto dst_buffer = as_runtime_buffer(dst_tensor_view); src_buffer.set_host_dirty(); enlarge(src_buffer, dst_buffer); dst_buffer.copy_to_host(); } auto enlarge(Sara::ImageView<Sara::Rgb32f>& src, Sara::ImageView<Sara::Rgb32f>& dst) { auto src_buffer = ::Halide::Runtime::Buffer<float>::make_interleaved( reinterpret_cast<float*>(src.data()), src.width(), src.height(), 3); auto dst_buffer = ::Halide::Runtime::Buffer<float>::make_interleaved( reinterpret_cast<float*>(dst.data()), dst.width(), dst.height(), 3); src_buffer.add_dimension(); dst_buffer.add_dimension(); src_buffer.set_host_dirty(); shakti_enlarge_gpu(src_buffer, // src.width(), src.height(), // dst.width(), dst.height(), // dst_buffer); dst_buffer.copy_to_host(); } } // namespace DO::Shakti::HalideBackend
mpl-2.0
Vikerus/dolphinphp
index.php
7482
<?php ini_set("auto_detect_line_endings", true); // Here we have to call the required functions and ready the user creation with a secure session. // Extended Use : This entire block of php is required. And must be at the top of your page. include_once 'includes/functions.php'; sec_session_start(); require_once 'includes/verifyme.php'; if($_SESSION['active'] == true){ echo "Logged in"; }else{ echo "Restricted"; } ?> <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content=""> <meta name="author" content=""> <link rel="shortcut icon" href="assets/img/favicon.png"> <title>Dolphinphp - PHP Powered Database</title> <!-- Bootstrap --> <link href="assets/css/bootstrap.css" rel="stylesheet"> <link href="assets/css/bootstrap-theme.css" rel="stylesheet"> <!-- Custom styles for this template --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <!-- These two javascripts' below are needed for the form to work! Extended Use: These are Required. --> <script src="assets/js/jquery.js"></script> <script> $(function () { var nua = navigator.userAgent var isAndroid = (nua.indexOf('Mozilla/5.0') > -1 && nua.indexOf('Android ') > -1 && nua.indexOf('AppleWebKit') > -1 && nua.indexOf('Chrome') === -1) if (isAndroid) { $('select.form-control').removeClass('form-control').css('width', '100%') } }) </script> </head> <body> <!-- The php snip-it below will show an error message if the variable $error_msg is set. Extended Use: This is Required. --> <?php if (!empty($error_msg)) { echo $error_msg; } ?> <div id="header"> <div class="container"> <div class="row"> <div class="col-lg-6" style="margin-top:-4px;"> <span class="form-inline" ><h2 class="subtitle" style="margin-top:-1px !important;"><h1 style="margin-top:10px !important; margin-bottom:-15px !important; ">Dolphinphp</h1>Powerful Mysql Db.</h2></span> <!-- This <form> reloads the page using entered values as the variables that make the script function. Extended Use: The action="", method="". and name="" are Required as is shown below! --> <form class="form-inline signup" action="register.php" method="post" name="registration_form"> <div class="form-group"> <!-- Here we have the <input> for email collection. Extended Use: The type="". id="", and name="" are Required as is shown below! --> <input type="text" class="form-control" id="email" name="email" placeholder="Enter your email address" /> </div> <!-- This is the <input> which allows Javascript to verify there is an email to submit. Extended Use: The type="", value="", and onclick="" are Required as is shown below! --> <input class="btn btn-theme" type="submit" value="Register"> </form> </div> </div> </div> </div> <!--left--><div class="container" id="main"> <div class="row"> <div class="well"> <h3 style="margin-top:5px !important;"> <div class="dropdown"> <a href="#" class="dropdown-toggle account" data-toggle="dropdown"> <div class="avatar"> <img src="" class="img-rounded" alt="avatar"> </div> <i class="fa fa-angle-down pull-right"></i> <div class="user-mini pull-right" style="margin-top:-10px;"> <span class="welcome" style="font-size:14px;">Welcome,</span> <span style="font-size:14px;" >User</span> </div> </a> <ul class="dropdown-menu"> <li> <a href="#"> <i class="fa fa-user"></i> <span>Profile</span> </a> </li> <li> <a href="ajax/page_messages.html" class="ajax-link"> <i class="fa fa-envelope"></i> <span>Messages</span> </a> </li> <li> <a href="ajax/gallery_simple.html" class="ajax-link"> <i class="fa fa-picture-o"></i> <span>Albums</span> </a> </li> <li> <a href="ajax/calendar.html" class="ajax-link"> <i class="fa fa-tasks"></i> <span>Tasks</span> </a> </li> <li> <a href="#"> <i class="fa fa-cog"></i> <span>Settings</span> </a> </li> <li> <a href="includes/logout.php"> <i class="fa fa-power-off"></i> <span>logout</span> </a> </li> </ul> </div> </h3></div> <div class="panel-body"> <h3 style="margin-top:5px !important;"> <div class="form-group"> <form class="form-horizontal" method="post" enctype="multipart/form-data" action="users/saveconvo.php"> <p>Enter a Friendcode to message:</p> <input class="form-control" type="text" name="friendid"> <label><p>Send Message:</p></label> <textarea class="form-control" style="width:auto; padding-right:12px;" name="inboxmsg" rows="4" cols="30">1200 Character Limit</textarea> <input class="btn btn-success pull-right" type="submit" name="submit9" value="Submit"></form> <ul class="list-inline"><li><a href="#"><i class="glyphicon glyphicon-align-left"></i></a></li><li><a href="#"><i class="glyphicon glyphicon-align-center"></i></a></li><li><a href="#"><i class="glyphicon glyphicon-align-right"></i></a></li></ul> </div> </h3> </div></div></div><!--/left--> <div class="container" id="main"> <div class="row"> <div class="well"> <h3>JustSearch: Image Uploader</h3> <h4>Supported File Types: ".gif" ".jpeg", ".jpg", ".png"</h4> <form action="upload_file.php" method="post" enctype="multipart/form-data"> <label for="file">Filename:</label> <input type="file" name="file" id="file"><br> <input type="submit" name="submit3" value="Submit"> </form> </div> </div> </div> <div id="footer"> <div class="container"> <p class="copyright">Copyright &copy; 2014-2015 - Vikerus</p> </div> </div> <script src="assets/js/bootstrap.min.js"></script> <?php //Begin beta dolphinphp// function test_input($data) { $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } // @comments front page // if(empty($_POST["bulletmsg"])){ if (isset($_POST["bulletmsg"])){ unset($_POST["bulletmsg"]); } } else{ echo "Comment written." . "<br>"; $file = '@comments.txt'; //The new person to add to the file $person = $_POST["bulletmsg"]; $personstruc = "@data" . ": " . date("m-d") . " : " . "$person" . "<hr>" ; //Write the contents to the file, // the FILE_APPEND flag to append the content to the end of the file //and the LOCK_EX flag to prevent anyone else writing to the file at the same time file_put_contents($file, $personstruc,FILE_APPEND | LOCK_EX); // } // // ?> </body> </html>
mpl-2.0
DominoTree/servo
tests/wpt/web-platform-tests/native-file-system/native_FileSystemWritableFileStream.tentative.https.manual.window.js
196
// META: script=/resources/testdriver.js // META: script=resources/test-helpers.js // META: script=resources/native-fs-test-helpers.js // META: script=script-tests/FileSystemWritableFileStream.js
mpl-2.0
yensa/Nalfein
scene.py
3160
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. import pygame from utils import Point, RenderQueue class Scene(object): """The Scene object represents a scene of the game.""" init = 0 end = 1 nextScene = None state = init elements = RenderQueue() def draw(self, surf): """Draws the scene on the screen""" for element in self.elements: element.draw(surf) def dispatch(self, event): if event.type == pygame.MOUSEBUTTONDOWN: self.onClick(event.button, event.pos) elif event.type == pygame.MOUSEBUTTONUP: self.onUnclick(event.button, event.pos) elif event.type == pygame.MOUSEMOTION: self.onMouseMotion(event.pos, event.rel, event.buttons) elif event.type == pygame.KEYDOWN: self.onKeyDown(event.key, event.mod, event.unicode) elif event.type == pygame.KEYUP: self.onKeyUp(event.key, event.mod) elif event.type == pygame.JOYBUTTONDOWN: self.onJoyClick(self, event.joy, event.button) elif event.type == pygame.JOYBUTTONUP: self.onJoyUnclick(self, event.joy, event.button) elif event.type == pygame.JOYAXISMOTION: self.onJoyMove(event.joy, event.axis, event.value) elif event.type == pygame.JOYBALLMOTION: self.onJoyBallMove(event.joy, event.ball, event.rel) elif event.type == pygame.JOYHATMOTION: self.onJoyHatMotion(event.joy, event.hat, event.value) elif event.type == pygame.USEREVENT: self.onUserEvent(event.code) def onKeyDown(self, key, mod, u): for element in self.elements: if hasattr(element, 'keydown') and element.focus: element.keydown(key, mod, u) def onKeyUp(self, key, mod): for element in self.elements: if hasattr(element, 'keyup') and element.focus: element.keyup(key, mod) def onClick(self, button, pos): for element in self.elements: element.focus = False if element.rect.collidepoint(pos): if hasattr(element, 'focus'): element.focus = True if hasattr(element, 'click'): element.click(button, Point(*pos)) def onUnclick(self, button, pos): for element in self.elements: if hasattr(element, 'unclick'): element.unclick(button, Point(*pos)) def onMouseMotion(self, pos, rel, buttons): pass def onJoyClick(self, joy, button): pass def onJoyUnclick(self, joy, button): pass def onJoyMove(self, joy, axis, value): pass def onJoyBallMove(self, joy, ball, rel): pass def onJoyHatMotion(self, joy, hat, value): pass def onUserEvent(self, code): for element in self.elements: if hasattr(element, 'userevent'): element.userevent(code)
mpl-2.0
Yukarumya/Yukarum-Redfoxes
toolkit/components/places/tests/unit/test_463863.js
1770
/* -*- indent-tabs-mode: nil; js-indent-level: 2 -*- */ /* vim:set ts=2 sw=2 sts=2 et: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ /* * TEST DESCRIPTION: * * This test checks that in a basic history query all transition types visits * appear but TRANSITION_EMBED and TRANSITION_FRAMED_LINK ones. */ var transitions = [ TRANSITION_LINK , TRANSITION_TYPED , TRANSITION_BOOKMARK , TRANSITION_EMBED , TRANSITION_FRAMED_LINK , TRANSITION_REDIRECT_PERMANENT , TRANSITION_REDIRECT_TEMPORARY , TRANSITION_DOWNLOAD ]; function runQuery(aResultType) { let options = PlacesUtils.history.getNewQueryOptions(); options.resultType = aResultType; let root = PlacesUtils.history.executeQuery(PlacesUtils.history.getNewQuery(), options).root; root.containerOpen = true; let cc = root.childCount; do_check_eq(cc, transitions.length - 2); for (let i = 0; i < cc; i++) { let node = root.getChild(i); // Check that all transition types but EMBED and FRAMED appear in results do_check_neq(node.uri.substr(6, 1), TRANSITION_EMBED); do_check_neq(node.uri.substr(6, 1), TRANSITION_FRAMED_LINK); } root.containerOpen = false; } function run_test() { run_next_test(); } add_task(function* test_execute() { // add visits, one for each transition type for (let transition of transitions) { yield PlacesTestUtils.addVisits({ uri: uri("http://" + transition + ".mozilla.org/"), transition }); } runQuery(Ci.nsINavHistoryQueryOptions.RESULTS_AS_VISIT); runQuery(Ci.nsINavHistoryQueryOptions.RESULTS_AS_URI); });
mpl-2.0
baetheus/nullbot
index.js
3525
'use strict'; /** * Module dependencies * @private */ var fs = require('fs'); var assert = require('assert-plus'); var bunyan = require('bunyan'); var restify = require('restify'); var shortid = require('shortid'); var createCore = require('nullbot-core'); var createClient = require('nullbot-client'); var createEvents = require('nullbot-events'); var createResponse = require('nullbot-response'); var utils = require('./lib/utils'); /** * Takes bot options and wraps nullbot-{core, client, events} along with a * restify route and returns a merged object. * @param {Object/String} options Either the bot token or an options object. * @return {Object} The bot object. */ function createBot(options) { // Options parsing var opts = typeof options === 'string' ? {token: options} : utils.shallowCopy(options); var that = {}; assert.optionalObject(opts, 'opts'); assert.string(opts.token, 'opts.token'); // Options defaults opts.name = opts.hasOwnProperty('name') ? opts.name : 'nullbot'; opts.url = opts.hasOwnProperty('url') ? opts.url : 'localhost'; opts.port = opts.hasOwnProperty('port') ? opts.port : 8443; opts.path = opts.hasOwnProperty('path') ? opts.path : '/' + shortid.generate(); opts.level = opts.hasOwnProperty('level') ? opts.level : 'info'; opts.cert = typeof opts.cert === 'string' ? fs.readFileSync(opts.cert) : opts.cert; opts.key = typeof opts.key === 'string' ? fs.readFileSync(opts.key) : opts.key; opts.hook = opts.hasOwnProperty('hook') ? opts.hook : opts.url + opts.path; if (opts.log && typeof opts.log === 'object') { opts.log = opts.log.child({module: opts.name}); } else { opts.log = bunyan.createLogger({name: opts.name, level: opts.level}); } // Create server, bot, client, and middleware. var response = createResponse(opts.log); var server = restify.createServer(opts); var events = createEvents(opts.log); var client = createClient(opts); var bot = createCore(opts); // Setup restify middleware server.use(restify.bodyParser({ mapParams: false })); server.post(opts.path, bot); // Setup bot middleware bot.filter('events').use(events); bot.filter('response').use(response); /** * Handles the response from setWebhook * @param {Error} err An error object * @param {Body} body A json response from Telegram */ function setWebhookHandler(err, body) { assert.ifError(err); if (body.ok) { opts.log.info('Webhook setup complete.'); } else { opts.log.error({body: body}, 'Set webhook failed.'); } } /** * Wraps server listen and set's webhook after server is started. * @return {[type]} [description] */ function listen() { server.listen(opts.port, function () { opts.log.info({name: server.name, url: opts.hook}, 'Server Started!'); var params = { url: opts.hook }; if (options.cert) { params.certificate = fs.createReadStream(options.cert); } client.setWebhook(params, setWebhookHandler); }); } // Bind internal functions to that that.listen = listen; that.server = server; that.events = events; that.log = opts.log; // Merge nullbot objects utils.merge(that, client); utils.merge(that, bot); return that; } /** * Module exports * @public */ module.exports = createBot;
mpl-2.0
SzecsenyiPeter/recovery-medical-system
RecoveryServer/RecoveryServer/Areas/HelpPage/App_Start/HelpPageConfig.cs
6499
// Uncomment the following to provide samples for PageResult<T>. Must also add the Microsoft.AspNet.WebApi.OData // package to your project. ////#define Handle_PageResultOfT using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Net.Http.Headers; using System.Reflection; using System.Web; using System.Web.Http; #if Handle_PageResultOfT using System.Web.Http.OData; #endif namespace RecoveryServer.Areas.HelpPage { /// <summary> /// Use this class to customize the Help Page. /// For example you can set a custom <see cref="System.Web.Http.Description.IDocumentationProvider"/> to supply the documentation /// or you can provide the samples for the requests/responses. /// </summary> public static class HelpPageConfig { [SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters", MessageId = "RecoveryServer.Areas.HelpPage.TextSample.#ctor(System.String)", Justification = "End users may choose to merge this string with existing localized resources.")] [SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", MessageId = "bsonspec", Justification = "Part of a URI.")] public static void Register(HttpConfiguration config) { //// Uncomment the following to use the documentation from XML documentation file. //config.SetDocumentationProvider(new XmlDocumentationProvider(HttpContext.Current.Server.MapPath("~/App_Data/XmlDocument.xml"))); //// Uncomment the following to use "sample string" as the sample for all actions that have string as the body parameter or return type. //// Also, the string arrays will be used for IEnumerable<string>. The sample objects will be serialized into different media type //// formats by the available formatters. //config.SetSampleObjects(new Dictionary<Type, object> //{ // {typeof(string), "sample string"}, // {typeof(IEnumerable<string>), new string[]{"sample 1", "sample 2"}} //}); // Extend the following to provide factories for types not handled automatically (those lacking parameterless // constructors) or for which you prefer to use non-default property values. Line below provides a fallback // since automatic handling will fail and GeneratePageResult handles only a single type. #if Handle_PageResultOfT config.GetHelpPageSampleGenerator().SampleObjectFactories.Add(GeneratePageResult); #endif // Extend the following to use a preset object directly as the sample for all actions that support a media // type, regardless of the body parameter or return type. The lines below avoid display of binary content. // The BsonMediaTypeFormatter (if available) is not used to serialize the TextSample object. config.SetSampleForMediaType( new TextSample("Binary JSON content. See http://bsonspec.org for details."), new MediaTypeHeaderValue("application/bson")); //// Uncomment the following to use "[0]=foo&[1]=bar" directly as the sample for all actions that support form URL encoded format //// and have IEnumerable<string> as the body parameter or return type. //config.SetSampleForType("[0]=foo&[1]=bar", new MediaTypeHeaderValue("application/x-www-form-urlencoded"), typeof(IEnumerable<string>)); //// Uncomment the following to use "1234" directly as the request sample for media type "text/plain" on the controller named "Values" //// and action named "Put". //config.SetSampleRequest("1234", new MediaTypeHeaderValue("text/plain"), "Values", "Put"); //// Uncomment the following to use the image on "../images/aspNetHome.png" directly as the response sample for media type "image/png" //// on the controller named "Values" and action named "Get" with parameter "id". //config.SetSampleResponse(new ImageSample("../images/aspNetHome.png"), new MediaTypeHeaderValue("image/png"), "Values", "Get", "id"); //// Uncomment the following to correct the sample request when the action expects an HttpRequestMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Get" were having string as the body parameter. //config.SetActualRequestType(typeof(string), "Values", "Get"); //// Uncomment the following to correct the sample response when the action returns an HttpResponseMessage with ObjectContent<string>. //// The sample will be generated as if the controller named "Values" and action named "Post" were returning a string. //config.SetActualResponseType(typeof(string), "Values", "Post"); } #if Handle_PageResultOfT private static object GeneratePageResult(HelpPageSampleGenerator sampleGenerator, Type type) { if (type.IsGenericType) { Type openGenericType = type.GetGenericTypeDefinition(); if (openGenericType == typeof(PageResult<>)) { // Get the T in PageResult<T> Type[] typeParameters = type.GetGenericArguments(); Debug.Assert(typeParameters.Length == 1); // Create an enumeration to pass as the first parameter to the PageResult<T> constuctor Type itemsType = typeof(List<>).MakeGenericType(typeParameters); object items = sampleGenerator.GetSampleObject(itemsType); // Fill in the other information needed to invoke the PageResult<T> constuctor Type[] parameterTypes = new Type[] { itemsType, typeof(Uri), typeof(long?), }; object[] parameters = new object[] { items, null, (long)ObjectGenerator.DefaultCollectionSize, }; // Call PageResult(IEnumerable<T> items, Uri nextPageLink, long? count) constructor ConstructorInfo constructor = type.GetConstructor(parameterTypes); return constructor.Invoke(parameters); } } return null; } #endif } }
mpl-2.0
jphp-compiler/develnext
develnext-designer/src/main/java/org/develnext/jphp/gui/designer/editor/tree/DirectoryTreeCell.java
4281
package org.develnext.jphp.gui.designer.editor.tree; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Node; import javafx.scene.SnapshotParameters; import javafx.scene.canvas.Canvas; import javafx.scene.canvas.GraphicsContext; import javafx.scene.control.Label; import javafx.scene.control.Tooltip; import javafx.scene.control.TreeView; import javafx.scene.control.cell.TextFieldTreeCell; import javafx.scene.image.ImageView; import javafx.scene.input.*; import javafx.scene.paint.Color; import javafx.scene.text.Text; import javafx.scene.text.TextFlow; import javafx.util.StringConverter; import org.develnext.jphp.ext.javafx.classes.text.UXFont; import org.develnext.jphp.ext.javafx.support.control.LabelEx; import java.io.File; import java.util.ArrayList; import java.util.List; public class DirectoryTreeCell extends TextFieldTreeCell<DirectoryTreeValue> { private boolean dragging = false; public DirectoryTreeCell() { super(new StringConverter<DirectoryTreeValue>() { private DirectoryTreeValue editItem; @Override public String toString(DirectoryTreeValue object) { editItem = object; return object.getText(); } @Override public DirectoryTreeValue fromString(String string) { String path = editItem.getPath(); return new DirectoryTreeValue(path, editItem.getCode(), string, editItem.getIcon(), editItem.getExpandIcon(), editItem.isFolder()); } }); setOnDragDetected(new EventHandler<MouseEvent>() { @Override public void handle(MouseEvent event) { DirectoryTreeView treeView = (DirectoryTreeView) getTreeView(); Object dragContent = treeView.getTreeSource().getDragContent(getTreeItem().getValue().getPath()); if (dragContent != null) { Node source = (Node) event.getSource(); if (dragContent instanceof List) { Dragboard dragboard = source.startDragAndDrop(TransferMode.MOVE); SnapshotParameters parameters = new SnapshotParameters(); parameters.setFill(Color.TRANSPARENT); Text text = new Text(getText()); text.setFont(getFont()); TextFlow textFlow = new TextFlow(text); textFlow.setPadding(new Insets(3)); dragboard.setDragView(textFlow.snapshot(parameters, null)); dragboard.setDragViewOffsetY(-15); dragboard.setDragViewOffsetX(-10); ClipboardContent content = new ClipboardContent(); content.putFiles((List<File>) dragContent); dragboard.setContent(content); } } } }); setOnDragEntered(new EventHandler<DragEvent>() { @Override public void handle(DragEvent event) { getTreeView().requestFocus(); getTreeView().getFocusModel().focus(getTreeView().getRow(getTreeItem())); if (!getTreeItem().isExpanded()) { getTreeItem().setExpanded(true); } } }); } @Override public void updateItem(DirectoryTreeValue item, boolean empty) { super.updateItem(item, empty); if (empty) { setText(null); setGraphic(null); setTooltip(null); } else { setText(item.getText()); setTooltip(new Tooltip(item.getText())); Node icon = item.getIcon(); /*if (item.getExpandIcon() != null) { icon = item.getExpandIcon(); }*/ if (item.getExpandIcon() != null && getChildren().size() > 0) { if (getTreeItem().isExpanded()) { icon = item.getExpandIcon(); } } setGraphic(icon); } } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
dom/broadcastchannel/BroadcastChannelService.cpp
3400
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* vim: set ts=8 sts=2 et sw=2 tw=80: */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "BroadcastChannelService.h" #include "BroadcastChannelParent.h" #include "mozilla/dom/File.h" #include "mozilla/dom/ipc/BlobParent.h" #include "mozilla/ipc/BackgroundParent.h" #ifdef XP_WIN #undef PostMessage #endif namespace mozilla { using namespace ipc; namespace dom { namespace { BroadcastChannelService* sInstance = nullptr; } // namespace BroadcastChannelService::BroadcastChannelService() { AssertIsOnBackgroundThread(); // sInstance is a raw BroadcastChannelService*. MOZ_ASSERT(!sInstance); sInstance = this; } BroadcastChannelService::~BroadcastChannelService() { AssertIsOnBackgroundThread(); MOZ_ASSERT(sInstance == this); MOZ_ASSERT(mAgents.Count() == 0); sInstance = nullptr; } // static already_AddRefed<BroadcastChannelService> BroadcastChannelService::GetOrCreate() { AssertIsOnBackgroundThread(); RefPtr<BroadcastChannelService> instance = sInstance; if (!instance) { instance = new BroadcastChannelService(); } return instance.forget(); } void BroadcastChannelService::RegisterActor(BroadcastChannelParent* aParent, const nsAString& aOriginChannelKey) { AssertIsOnBackgroundThread(); MOZ_ASSERT(aParent); nsTArray<BroadcastChannelParent*>* parents; if (!mAgents.Get(aOriginChannelKey, &parents)) { parents = new nsTArray<BroadcastChannelParent*>(); mAgents.Put(aOriginChannelKey, parents); } MOZ_ASSERT(!parents->Contains(aParent)); parents->AppendElement(aParent); } void BroadcastChannelService::UnregisterActor(BroadcastChannelParent* aParent, const nsAString& aOriginChannelKey) { AssertIsOnBackgroundThread(); MOZ_ASSERT(aParent); nsTArray<BroadcastChannelParent*>* parents; if (!mAgents.Get(aOriginChannelKey, &parents)) { MOZ_CRASH("Invalid state"); } parents->RemoveElement(aParent); if (parents->IsEmpty()) { mAgents.Remove(aOriginChannelKey); } } void BroadcastChannelService::PostMessage(BroadcastChannelParent* aParent, const ClonedMessageData& aData, const nsAString& aOriginChannelKey) { AssertIsOnBackgroundThread(); MOZ_ASSERT(aParent); nsTArray<BroadcastChannelParent*>* parents; if (!mAgents.Get(aOriginChannelKey, &parents)) { MOZ_CRASH("Invalid state"); } // We need to keep the array alive for the life-time of this operation. nsTArray<RefPtr<BlobImpl>> blobs; if (!aData.blobsParent().IsEmpty()) { blobs.SetCapacity(aData.blobsParent().Length()); for (uint32_t i = 0, len = aData.blobsParent().Length(); i < len; ++i) { RefPtr<BlobImpl> impl = static_cast<BlobParent*>(aData.blobsParent()[i])->GetBlobImpl(); MOZ_ASSERT(impl); blobs.AppendElement(impl); } } for (uint32_t i = 0; i < parents->Length(); ++i) { BroadcastChannelParent* parent = parents->ElementAt(i); MOZ_ASSERT(parent); if (parent != aParent) { parent->Deliver(aData); } } } } // namespace dom } // namespace mozilla
mpl-2.0
Yukarumya/Yukarum-Redfoxes
browser/base/content/test/urlbar/browser_urlbarSearchTelemetry.js
7425
"use strict"; Cu.import("resource:///modules/BrowserUITelemetry.jsm"); const SUGGEST_URLBAR_PREF = "browser.urlbar.suggest.searches"; const TEST_ENGINE_BASENAME = "searchSuggestionEngine.xml"; // Must run first. add_task(function* prepare() { Services.prefs.setBoolPref(SUGGEST_URLBAR_PREF, true); let engine = yield promiseNewSearchEngine(TEST_ENGINE_BASENAME); let oldCurrentEngine = Services.search.currentEngine; Services.search.currentEngine = engine; registerCleanupFunction(function* () { Services.prefs.clearUserPref(SUGGEST_URLBAR_PREF); Services.search.currentEngine = oldCurrentEngine; // Clicking urlbar results causes visits to their associated pages, so clear // that history now. yield PlacesTestUtils.clearHistory(); // Make sure the popup is closed for the next test. gURLBar.blur(); Assert.ok(!gURLBar.popup.popupOpen, "popup should be closed"); }); // Move the mouse away from the urlbar one-offs so that a one-off engine is // not inadvertently selected. yield new Promise(resolve => { EventUtils.synthesizeNativeMouseMove(window.document.documentElement, 0, 0, resolve); }); }); add_task(function* heuristicResultMouse() { yield compareCounts(function* () { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser); gURLBar.focus(); yield promiseAutocompleteResultPopup("heuristicResult"); let action = getActionAtIndex(0); Assert.ok(!!action, "there should be an action at index 0"); Assert.equal(action.type, "searchengine", "type should be searchengine"); let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser); gURLBar.popup.richlistbox.getItemAtIndex(0).click(); yield loadPromise; yield BrowserTestUtils.removeTab(tab); }); }); add_task(function* heuristicResultKeyboard() { yield compareCounts(function* () { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser); gURLBar.focus(); yield promiseAutocompleteResultPopup("heuristicResult"); let action = getActionAtIndex(0); Assert.ok(!!action, "there should be an action at index 0"); Assert.equal(action.type, "searchengine", "type should be searchengine"); let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser); EventUtils.sendKey("return"); yield loadPromise; yield BrowserTestUtils.removeTab(tab); }); }); add_task(function* searchSuggestionMouse() { yield compareCounts(function* () { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser); gURLBar.focus(); yield promiseAutocompleteResultPopup("searchSuggestion"); let idx = getFirstSuggestionIndex(); Assert.ok(idx >= 0, "there should be a first suggestion"); let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser); gURLBar.popup.richlistbox.getItemAtIndex(idx).click(); yield loadPromise; yield BrowserTestUtils.removeTab(tab); }); }); add_task(function* searchSuggestionKeyboard() { yield compareCounts(function* () { let tab = yield BrowserTestUtils.openNewForegroundTab(gBrowser); gURLBar.focus(); yield promiseAutocompleteResultPopup("searchSuggestion"); let idx = getFirstSuggestionIndex(); Assert.ok(idx >= 0, "there should be a first suggestion"); let loadPromise = BrowserTestUtils.browserLoaded(tab.linkedBrowser); while (idx--) { EventUtils.sendKey("down"); } EventUtils.sendKey("return"); yield loadPromise; yield BrowserTestUtils.removeTab(tab); }); }); /** * This does three things: gets current telemetry/FHR counts, calls * clickCallback, gets telemetry/FHR counts again to compare them to the old * counts. * * @param clickCallback Use this to open the urlbar popup and choose and click a * result. */ function* compareCounts(clickCallback) { // Search events triggered by clicks (not the Return key in the urlbar) are // recorded in three places: // * BrowserUITelemetry // * Telemetry histogram named "SEARCH_COUNTS" // * FHR let engine = Services.search.currentEngine; let engineID = "org.mozilla.testsearchsuggestions"; // First, get the current counts. // BrowserUITelemetry let uiTelemCount = 0; let bucket = BrowserUITelemetry.currentBucket; let events = BrowserUITelemetry.getToolbarMeasures().countableEvents; if (events[bucket] && events[bucket].search && events[bucket].search.urlbar) { uiTelemCount = events[bucket].search.urlbar; } // telemetry histogram SEARCH_COUNTS let histogramCount = 0; let histogramKey = engineID + ".urlbar"; let histogram; try { histogram = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS"); } catch (ex) { // No searches performed yet, not a problem. } if (histogram) { let snapshot = histogram.snapshot(); if (histogramKey in snapshot) { histogramCount = snapshot[histogramKey].sum; } } // FHR -- first make sure the engine has an identifier so that FHR is happy. Object.defineProperty(engine.wrappedJSObject, "identifier", { value: engineID }); gURLBar.focus(); yield clickCallback(); // Now get the new counts and compare them to the old. // BrowserUITelemetry events = BrowserUITelemetry.getToolbarMeasures().countableEvents; Assert.ok(bucket in events, "bucket should be recorded"); events = events[bucket]; Assert.ok("search" in events, "search should be recorded"); events = events.search; Assert.ok("urlbar" in events, "urlbar should be recorded"); Assert.equal(events.urlbar, uiTelemCount + 1, "clicked suggestion should be recorded"); // telemetry histogram SEARCH_COUNTS histogram = Services.telemetry.getKeyedHistogramById("SEARCH_COUNTS"); let snapshot = histogram.snapshot(); Assert.ok(histogramKey in snapshot, "histogram with key should be recorded"); Assert.equal(snapshot[histogramKey].sum, histogramCount + 1, "histogram sum should be incremented"); } /** * Returns the "action" object at the given index in the urlbar results: * { type, params: {}} * * @param index The index in the urlbar results. * @return An action object, or null if index >= number of results. */ function getActionAtIndex(index) { let controller = gURLBar.popup.input.controller; if (controller.matchCount <= index) { return null; } let url = controller.getValueAt(index); let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/); if (!mozActionMatch) { let msg = "result at index " + index + " is not a moz-action: " + url; Assert.ok(false, msg); throw new Error(msg); } let [, type, paramStr] = mozActionMatch; return { type, params: JSON.parse(paramStr), }; } /** * Returns the index of the first search suggestion in the urlbar results. * * @return An index, or -1 if there are no search suggestions. */ function getFirstSuggestionIndex() { let controller = gURLBar.popup.input.controller; let matchCount = controller.matchCount; for (let i = 0; i < matchCount; i++) { let url = controller.getValueAt(i); let mozActionMatch = url.match(/^moz-action:([^,]+),(.*)$/); if (mozActionMatch) { let [, type, paramStr] = mozActionMatch; let params = JSON.parse(paramStr); if (type == "searchengine" && "searchSuggestion" in params) { return i; } } } return -1; }
mpl-2.0
UtrsSoftware/ATMLWorkBench
ATMLLibraries/ATMLCommonLibrary/controls/manufacturer/ManufacturerContactListControl.cs
2152
/* * Copyright (c) 2014 Universal Technical Resource Services, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using ATMLModelLibrary.model.common; using ATMLModelLibrary.model.equipment; using ATMLCommonLibrary.forms; namespace ATMLCommonLibrary.controls.lists { public partial class ManufacturerContactListControl : ATMLListControl { private List<ManufacturerDataContact> _contacts = new List<ManufacturerDataContact>(); public List<ManufacturerDataContact> Contacts { get { ControlsToData(); return _contacts; } set { _contacts = value; DataToControls(); } } public ManufacturerContactListControl() { InitializeComponent(); InitListView(); } private void InitListView() { DataObjectName = "Contact"; DataObjectFormType = typeof(ContactForm); AddColumnData("Name", "name", .33); AddColumnData("Phone", "phoneNumber", .33); AddColumnData("Email", "email", .34); InitColumns(); } private void DataToControls() { if (_contacts != null) { lvList.Items.Clear(); foreach (ManufacturerDataContact contact in _contacts) AddListViewObject(contact); } } private void ControlsToData() { _contacts = null; if (lvList.Items.Count > 0) { _contacts = new List<ManufacturerDataContact>(); foreach (ListViewItem lvi in lvList.Items) _contacts.Add((ManufacturerDataContact)lvi.Tag); } } } }
mpl-2.0
jpetto/bedrock
media/js/firefox/australis/common.js
2606
;(function($, Mozilla) { 'use strict'; var pageId = $('body').prop('id'); var $window = $(window); var $syncAnim = $('.sync-anim'); var $laptop = $syncAnim.find('.laptop'); var $laptopScreen = $laptop.find('.inner'); var $phone = $syncAnim.find('.phone'); var $arrows = $laptop.find('.arrows'); // scroll to top of window for mask overlay if ($window.scrollTop() > 0 && (window.location.hash !== '#footer-email-form')) { $window.scrollTop(0); } // start in-page animations when user scrolls down from header $('#masthead').waypoint(function(direction) { if (direction === 'down') { syncAnimation(); this.destroy(); // execute waypoint once } }, { offset: -20 }); function syncAnimation() { $syncAnim.addClass('on'); $arrows.one('animationstart', function () { $laptopScreen.addClass('faded'); }); $arrows.one('animationend', function () { $laptopScreen.removeClass('faded'); }); $phone.one('animationend', '.passwords', function () { $syncAnim.addClass('complete'); }); } // link directly to Firefox Accounts when clicking the Sync CTA button Mozilla.UITour.getConfiguration('sync', function (config) { $('.sync-cta .button').each(function() { $(this).attr({ 'data-page-name': pageId, 'data-interaction': 'button click', 'data-element-location': 'Get Started with Sync' }).on('click', function(e) { e.preventDefault(); // Track sync button clicks window.dataLayer.push({ 'event': 'first-run-sync' }); if (Mozilla.Client.FirefoxMajorVersion >= 31) { Mozilla.UITour.showFirefoxAccounts(); } else { window.open(this.href, '_blank'); } }); }); }); // track learn more links $('.learn-more a').each(function() { $(this).attr({ 'data-page-name': pageId, 'data-interaction': 'button click', 'data-element-location': 'Get Started with Sync' }).on('click', function(e) { e.preventDefault(); // Track sync button clicks window.dataLayer.push({ 'event': 'first-run-sync' }); window.open(this.href, '_blank'); }); }); })(window.jQuery, window.Mozilla);
mpl-2.0
oracle/terraform-provider-baremetal
oci/oci_sweeper_test.go
3837
// Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. // Licensed under the Mozilla Public License v2.0 package oci import ( "context" "fmt" "log" "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/helper/resource" oci_identity "github.com/oracle/oci-go-sdk/v46/identity" ) /* This map holds the list of ocids for a given resourceType by compartment For Example : Submap1[vcn] : [vcn-1_ocid, vcn-2_ocid, ...] // In Compartment 1 Submap1[instance] : [instance-1_ocid, instance-2_ocid, ...] // In Compartment 1 SweeperResourceCompartmentIdMap[compartment-1_ocid] = Submap1 Submap2[vcn] : [vcn-1_ocid, vcn-2_ocid, ...] // In Compartment 2 Submap2[instance] : [instance-1_ocid, instance-2_ocid, ...] // In Compartment 2 SweeperResourceCompartmentIdMap[compartment-2_ocid] = Submap2 */ var SweeperResourceCompartmentIdMap map[string]map[string][]string /* This Map hold the ocids of the default resources. For example: vcn can have default dhcpOptions, routeTables and securityLists which should not be deleted individually. These default resources are deleted as part of deleting the vcn itself. In such cases we identify and add the default resource ocid into this map and the respective sweeper checks if the ocid of the resource be deleted is present in this map then it will skip that resource. */ var SweeperDefaultResourceId = make(map[string]bool) // issue-routing-tag: terraform/default func TestMain(m *testing.M) { resource.TestMain(m) } func addResourceIdToSweeperResourceIdMap(compartmentId string, resourceType string, resourceId string) { if _, ok := SweeperResourceCompartmentIdMap[compartmentId]; ok { resourceCompartmentIdMap := SweeperResourceCompartmentIdMap[compartmentId] if _, ok := resourceCompartmentIdMap[resourceType]; ok { resourceCompartmentIdMap[resourceType] = append(resourceCompartmentIdMap[resourceType], resourceId) } else { idList := []string{resourceId} resourceCompartmentIdMap := SweeperResourceCompartmentIdMap[compartmentId] resourceCompartmentIdMap[resourceType] = idList } } else { resourceCompartmentIdMap := map[string]map[string][]string{} resourceIdMap := make(map[string][]string) resourceIdList := []string{resourceId} resourceIdMap[resourceType] = resourceIdList resourceCompartmentIdMap[compartmentId] = resourceIdMap SweeperResourceCompartmentIdMap = resourceCompartmentIdMap } } func getResourceIdsToSweep(compartmentId string, resourceName string) []string { if _, ok := SweeperResourceCompartmentIdMap[compartmentId]; ok { resourceIdMap := SweeperResourceCompartmentIdMap[compartmentId] if _, ok := resourceIdMap[resourceName]; ok { return resourceIdMap[resourceName] } } return nil } func getAvalabilityDomains(compartmentId string) (map[string]string, error) { availabilityDomains := make(map[string]string) identityClient := GetTestClients(&schema.ResourceData{}).identityClient() adRequest := oci_identity.ListAvailabilityDomainsRequest{} adRequest.CompartmentId = &compartmentId ads, err := identityClient.ListAvailabilityDomains(context.Background(), adRequest) if err != nil { return availabilityDomains, fmt.Errorf("Error getting availability domains for compartment id : %s , %s \n", compartmentId, err) } for _, ad := range ads.Items { availabilityDomains[*ad.Id] = *ad.Name } return availabilityDomains, nil } func inSweeperExcludeList(sweeperName string) bool { excludeListSweeper := strings.Split(getEnvSettingWithBlankDefault("sweep_exclude_list"), ",") for _, sweeper := range excludeListSweeper { if strings.EqualFold(strings.Trim(sweeper, " "), sweeperName) { log.Printf("[DEBUG] Skip sweeper for %s", sweeperName) return true } } return false }
mpl-2.0
samuelkarp/purple-docker
plugin/account.go
3900
/* Copyright (c) 2017, Samuel Karp. All rights reserved. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package main import ( "sync" "unsafe" "context" log "github.com/cihub/seelog" "github.com/fsouza/go-dockerclient" ) // #cgo pkg-config: purple // #include "account.h" // #include "blist.h" import "C" // Account is a go struct encapsulating a PurpleAccount type Account struct { ctx context.Context cancel context.CancelFunc online bool cAccount *C.PurpleAccount dockerClient *docker.Client buddies map[string]*C.PurpleBuddy containers map[string]*Container lock sync.RWMutex funcQueue []func() funcQueueLock sync.Mutex } var accountMap map[*C.PurpleAccount]*Account var accountMapLock sync.RWMutex // NewAccount returns an Account from a PurpleAccount func NewAccount(ctx context.Context, cAccount *C.PurpleAccount) *Account { accountMapLock.Lock() defer accountMapLock.Unlock() if accountMap == nil { accountMap = map[*C.PurpleAccount]*Account{} } if account, ok := accountMap[cAccount]; ok { return account } accountCtx, cancel := context.WithCancel(ctx) account := &Account{ ctx: accountCtx, cancel: cancel, online: true, cAccount: cAccount, buddies: map[string]*C.PurpleBuddy{}, containers: map[string]*Container{}, funcQueue: []func(){}, } accountMap[cAccount] = account return account } func GetAccount(cAccount *C.PurpleAccount) (*Account, bool) { accountMapLock.RLock() defer accountMapLock.RUnlock() account, ok := accountMap[cAccount] return account, ok } func (account *Account) Cancel() { account.cancel() accountMapLock.Lock() defer accountMapLock.Unlock() delete(accountMap, account.cAccount) } func (account *Account) EventLoop() { account.funcQueueLock.Lock() localQueue := account.funcQueue account.funcQueue = []func(){} account.funcQueueLock.Unlock() select { case <-account.ctx.Done(): default: for _, function := range localQueue { function() } } } func (account *Account) enqueueFunction(function func()) { account.funcQueueLock.Lock() defer account.funcQueueLock.Unlock() account.funcQueue = append(account.funcQueue, function) } // SetConnected sets the account state to connected func (account *Account) SetConnected() { purpleConnection := C.purple_account_get_connection(account.cAccount) C.purple_connection_set_state(purpleConnection, C.PURPLE_CONNECTED) } // IsConnected returns whether the account is connected func (account *Account) IsConnected() bool { connected := C.purple_account_is_connected(account.cAccount) return connected != 0 } func (account *Account) ReceiveIM(from, message string) { receiveTime := C.time(nil) account.enqueueFunction(func() { account.lock.RLock() defer account.lock.RUnlock() if !account.online { return } cFrom := C.CString(from) defer C.free(unsafe.Pointer(cFrom)) cMessage := C.CString(message) defer C.free(unsafe.Pointer(cMessage)) conversation := C.purple_find_conversation_with_account(C.PURPLE_CONV_TYPE_IM, cFrom, account.cAccount) if conversation == nil { log.Tracef("creating new conversation with from %s", from) conversation = C.purple_conversation_new(C.PURPLE_CONV_TYPE_IM, account.cAccount, cFrom) if conversation == nil { log.Error("conversation is nil") return } } log.Tracef("Got conversation %p", conversation) C.purple_conversation_write(conversation, cFrom, cMessage, C.PURPLE_MESSAGE_RECV, receiveTime) log.Tracef("Called purple_conversation_write") }) } func (account *Account) SendIM(to, message string) error { account.lock.RLock() container := account.containers[to] account.lock.RUnlock() return container.ToStdinAttached(message) }
mpl-2.0
Phrozyn/MozDef
alerts/get_watchlist.py
3152
#!/usr/bin/env python # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # Copyright (c) 2014 Mozilla Corporation import requests import json from lib.alerttask import AlertTask from requests_jwt import JWTAuth from mozdef_util.utilities.logger import logger from mozdef_util.query_models import SearchQuery, QueryStringMatch class AlertWatchList(AlertTask): def main(self): self.parse_config('get_watchlist.conf', ['api_url', 'jwt_secret']) jwt_token = JWTAuth(self.config.jwt_secret) jwt_token.set_header_format('Bearer %s') # Connect to rest api and grab response r = requests.get(self.config.api_url, auth=jwt_token) status = r.status_code index = 0 if status == 200: status = r.status_code response = r.text terms_list = json.loads(response) while index < len(terms_list): term = terms_list[index] term = '"{}"'.format(term) self.watchterm = term index += 1 self.process_alert(term) else: logger.error('The watchlist request failed. Status {0}.\n'.format(status)) def process_alert(self, term): search_query = SearchQuery(minutes=20) content = QueryStringMatch(str(term)) search_query.add_must(content) self.filtersManual(search_query) self.searchEventsSimple() self.walkEvents() # Set alert properties def onEvent(self, event): category = 'watchlist' tags = ['watchtarget'] severity = 'WARNING' ev = event['_source'] user = '' sourceipaddress = '' hostname = '' source_data = '' user_data = '' # If the event severity is below what we want, just ignore # the event. if 'details' not in ev: return None if 'details' in ev: if 'sourceipaddress' in ev['details']: sourceipaddress = ev['details']['sourceipaddress'] source_data = 'from {}'.format(sourceipaddress) if 'username' in ev['details'] or 'originaluser' in ev['details'] or 'user' in ev['details']: if 'username' in ev['details']: user = ev['details']['username'] user_data = 'by {}'.format(user) elif 'originaluser' in ev['details']: user = ev['details']['originaluser'] user_data = 'by {}'.format(user) elif 'user' in ev['details']: user = ev['details']['user'] user_data = 'by {}'.format(user) if 'hostname' in ev: hostname = ev['hostname'] else: return None summary = 'Watchlist term {} detected {} {} on {}'.format(self.watchterm, user_data, source_data, hostname) return self.createAlertDict(summary, category, tags, [event], severity)
mpl-2.0
zyegfryed/packer
packer/build.go
8414
package packer import ( "fmt" "log" "sync" ) const ( // This is the key in configurations that is set to the name of the // build. BuildNameConfigKey = "packer_build_name" // This is the key in the configuration that is set to the type // of the builder that is run. This is useful for provisioners and // such who want to make use of this. BuilderTypeConfigKey = "packer_builder_type" // This is the key in configurations that is set to "true" when Packer // debugging is enabled. DebugConfigKey = "packer_debug" // This is the key in configurations that is set to "true" when Packer // force build is enabled. ForceConfigKey = "packer_force" ) // A Build represents a single job within Packer that is responsible for // building some machine image artifact. Builds are meant to be parallelized. type Build interface { // Name is the name of the build. This is unique across a single template, // but not absolutely unique. This is meant more to describe to the user // what is being built rather than being a unique identifier. Name() string // Prepare configures the various components of this build and reports // any errors in doing so (such as syntax errors, validation errors, etc.) Prepare() error // Run runs the actual builder, returning an artifact implementation // of what is built. If anything goes wrong, an error is returned. Run(Ui, Cache) ([]Artifact, error) // Cancel will cancel a running build. This will block until the build // is actually completely cancelled. Cancel() // SetDebug will enable/disable debug mode. Debug mode is always // enabled by adding the additional key "packer_debug" to boolean // true in the configuration of the various components. This must // be called prior to Prepare. // // When SetDebug is set to true, parallelism between builds is // strictly prohibited. SetDebug(bool) // SetForce will enable/disable forcing a build when artifacts exist. // // When SetForce is set to true, existing artifacts from the build are // deleted prior to the build. SetForce(bool) } // A build struct represents a single build job, the result of which should // be a single machine image artifact. This artifact may be comprised of // multiple files, of course, but it should be for only a single provider // (such as VirtualBox, EC2, etc.). type coreBuild struct { name string builder Builder builderConfig interface{} builderType string hooks map[string][]Hook postProcessors [][]coreBuildPostProcessor provisioners []coreBuildProvisioner debug bool force bool l sync.Mutex prepareCalled bool } // Keeps track of the post-processor and the configuration of the // post-processor used within a build. type coreBuildPostProcessor struct { processor PostProcessor processorType string config interface{} keepInputArtifact bool } // Keeps track of the provisioner and the configuration of the provisioner // within the build. type coreBuildProvisioner struct { provisioner Provisioner config []interface{} } // Returns the name of the build. func (b *coreBuild) Name() string { return b.name } // Prepare prepares the build by doing some initialization for the builder // and any hooks. This _must_ be called prior to Run. func (b *coreBuild) Prepare() (err error) { b.l.Lock() defer b.l.Unlock() if b.prepareCalled { panic("prepare already called") } b.prepareCalled = true packerConfig := map[string]interface{}{ BuildNameConfigKey: b.name, BuilderTypeConfigKey: b.builderType, DebugConfigKey: b.debug, ForceConfigKey: b.force, } // Prepare the builder err = b.builder.Prepare(b.builderConfig, packerConfig) if err != nil { log.Printf("Build '%s' prepare failure: %s\n", b.name, err) return } // Prepare the provisioners for _, coreProv := range b.provisioners { configs := make([]interface{}, len(coreProv.config), len(coreProv.config)+1) copy(configs, coreProv.config) configs = append(configs, packerConfig) if err = coreProv.provisioner.Prepare(configs...); err != nil { return } } // Prepare the post-processors for _, ppSeq := range b.postProcessors { for _, corePP := range ppSeq { err = corePP.processor.Configure(corePP.config, packerConfig) if err != nil { return } } } return } // Runs the actual build. Prepare must be called prior to running this. func (b *coreBuild) Run(originalUi Ui, cache Cache) ([]Artifact, error) { if !b.prepareCalled { panic("Prepare must be called first") } // Copy the hooks hooks := make(map[string][]Hook) for hookName, hookList := range b.hooks { hooks[hookName] = make([]Hook, len(hookList)) copy(hooks[hookName], hookList) } // Add a hook for the provisioners if we have provisioners if len(b.provisioners) > 0 { provisioners := make([]Provisioner, len(b.provisioners)) for i, p := range b.provisioners { provisioners[i] = p.provisioner } if _, ok := hooks[HookProvision]; !ok { hooks[HookProvision] = make([]Hook, 0, 1) } hooks[HookProvision] = append(hooks[HookProvision], &ProvisionHook{provisioners}) } hook := &DispatchHook{hooks} artifacts := make([]Artifact, 0, 1) // The builder just has a normal Ui, but prefixed builderUi := &PrefixedUi{ fmt.Sprintf("==> %s", b.Name()), fmt.Sprintf(" %s", b.Name()), originalUi, } log.Printf("Running builder: %s", b.builderType) builderArtifact, err := b.builder.Run(builderUi, hook, cache) if err != nil { return nil, err } // If there was no result, don't worry about running post-processors // because there is nothing they can do, just return. if builderArtifact == nil { return nil, nil } errors := make([]error, 0) keepOriginalArtifact := len(b.postProcessors) == 0 // Run the post-processors PostProcessorRunSeqLoop: for _, ppSeq := range b.postProcessors { priorArtifact := builderArtifact for i, corePP := range ppSeq { ppUi := &PrefixedUi{ fmt.Sprintf("==> %s (%s)", b.Name(), corePP.processorType), fmt.Sprintf(" %s (%s)", b.Name(), corePP.processorType), originalUi, } builderUi.Say(fmt.Sprintf("Running post-processor: %s", corePP.processorType)) artifact, keep, err := corePP.processor.PostProcess(ppUi, priorArtifact) if err != nil { errors = append(errors, fmt.Errorf("Post-processor failed: %s", err)) continue PostProcessorRunSeqLoop } if artifact == nil { log.Println("Nil artifact, halting post-processor chain.") continue PostProcessorRunSeqLoop } keep = keep || corePP.keepInputArtifact if i == 0 { // This is the first post-processor. We handle deleting // previous artifacts a bit different because multiple // post-processors may be using the original and need it. if !keepOriginalArtifact && keep { log.Printf( "Flagging to keep original artifact from post-processor '%s'", corePP.processorType) keepOriginalArtifact = true } } else { // We have a prior artifact. If we want to keep it, we append // it to the results list. Otherwise, we destroy it. if keep { artifacts = append(artifacts, priorArtifact) } else { log.Printf("Deleting prior artifact from post-processor '%s'", corePP.processorType) if err := priorArtifact.Destroy(); err != nil { errors = append(errors, fmt.Errorf("Failed cleaning up prior artifact: %s", err)) } } } priorArtifact = artifact } // Add on the last artifact to the results if priorArtifact != nil { artifacts = append(artifacts, priorArtifact) } } if keepOriginalArtifact { artifacts = append(artifacts, nil) copy(artifacts[1:], artifacts) artifacts[0] = builderArtifact } else { log.Printf("Deleting original artifact for build '%s'", b.name) if err := builderArtifact.Destroy(); err != nil { errors = append(errors, fmt.Errorf("Error destroying builder artifact: %s", err)) } } if len(errors) > 0 { err = &MultiError{errors} } return artifacts, err } func (b *coreBuild) SetDebug(val bool) { if b.prepareCalled { panic("prepare has already been called") } b.debug = val } func (b *coreBuild) SetForce(val bool) { if b.prepareCalled { panic("prepare has already been called") } b.force = val } // Cancels the build if it is running. func (b *coreBuild) Cancel() { b.builder.Cancel() }
mpl-2.0
LostKobrakai/MigrationsTutorial
wire/core/FileLog.php
13650
<?php /** * ProcessWire FileLog * * Creates and maintains a text-based log file. * * ProcessWire 2.8.x (development), Copyright 2016 by Ryan Cramer * https://processwire.com * */ class FileLog extends Wire { const defaultChunkSize = 12288; const debug = false; protected $logFilename = false; protected $itemsLogged = array(); protected $delimeter = "\t"; protected $maxLineLength = 8192; protected $fileExtension = 'txt'; protected $path = ''; /** * Construct the FileLog * * @param string $path Path where the log will be stored (path should have trailing slash) * This may optionally include the filename if you intend to leave the second param blank. * @param string $identifier Basename for the log file, not including the extension. * */ public function __construct($path, $identifier = '') { if($identifier) { $path = rtrim($path, '/') . '/'; $this->logFilename = "$path$identifier.{$this->fileExtension}"; } else { $this->logFilename = $path; $path = dirname($path) . '/'; } $this->path = $path; if(!is_dir($path)) $this->wire('files')->mkdir($path); } public function __get($key) { if($key == 'delimiter') return $this->delimeter; // @todo learn how to spell return parent::__get($key); } /** * Clean a string for use in a log file entry * * @param $str * @return mixed|string * */ protected function cleanStr($str) { $str = str_replace(array("\r\n", "\r", "\n"), ' ', trim($str)); if(strlen($str) > $this->maxLineLength) $str = substr($str, 0, $this->maxLineLength); return $str; } /** * Save the given log entry string * * @param $str * @return bool Success state * */ public function save($str) { if(!$this->logFilename) return false; $hash = md5($str); // if we've already logged this during this instance, then don't do it again if(in_array($hash, $this->itemsLogged)) return true; $ts = date("Y-m-d H:i:s"); $str = $this->cleanStr($str); if($fp = fopen($this->logFilename, "a")) { $trys = 0; $stop = false; while(!$stop) { if(flock($fp, LOCK_EX)) { fwrite($fp, "$ts{$this->delimeter}$str\n"); flock($fp, LOCK_UN); $this->itemsLogged[] = $hash; $stop = true; } else { usleep(2000); if($trys++ > 20) $stop = true; } } fclose($fp); $this->wire('files')->chmod($this->logFilename); return true; } else { return false; } } public function size() { return filesize($this->logFilename); } public function filename() { return basename($this->logFilename); } public function pathname() { return $this->logFilename; } public function mtime() { return filemtime($this->logFilename); } /** * Get lines from the end of a file based on chunk size (deprecated) * * @param int $chunkSize * @param int $chunkNum * @return array * @deprecated Use find() instead * */ public function get($chunkSize = 0, $chunkNum = 1) { return $this->getChunkArray($chunkNum, $chunkSize); } /** * Get lines from the end of a file based on chunk size * * @param int $chunkSize * @param int $chunkNum * @param bool $reverse * @return array * */ protected function getChunkArray($chunkNum = 1, $chunkSize = 0, $reverse = true) { if($chunkSize < 1) $chunkSize = self::defaultChunkSize; $lines = explode("\n", $this->getChunk($chunkNum, $chunkSize, $reverse)); foreach($lines as $key => $line) { $line = trim($line); if(!strlen($line)) { unset($lines[$key]); } else { $lines[$key] = $line; } } if($reverse) $lines = array_reverse($lines); return $lines; } /** * Get a chunk of data (string) from the end of the log file * * Returned string is automatically adjusted at the beginning and * ending to contain only full log lines. * * @param int $chunkNum Current pagination number (default=1) * @param int $chunkSize Number of bytes to retrieve (default=12288) * @param bool $reverse True=pull from end of file, false=pull from beginning (default=true) * @return string * */ protected function getChunk($chunkNum = 1, $chunkSize = 0, $reverse = true) { if($chunkSize < 1) $chunkSize = self::defaultChunkSize; if($reverse) { $offset = -1 * ($chunkSize * $chunkNum); } else { $offset = $chunkSize * ($chunkNum-1); } if(self::debug) $this->message("chunkNum=$chunkNum, chunkSize=$chunkSize, offset=$offset, filesize=" . filesize($this->logFilename)); $data = ''; $totalChunks = $this->getTotalChunks($chunkSize); if($chunkNum > $totalChunks) return $data; if(!$fp = fopen($this->logFilename, "r")) return $data; fseek($fp, $offset, ($reverse ? SEEK_END : SEEK_SET)); // make chunk include up to beginning of first line fseek($fp, -1, SEEK_CUR); while(ftell($fp) > 0) { $chr = fread($fp, 1); if($chr == "\n") break; fseek($fp, -2, SEEK_CUR); $data = $chr . $data; } // get the big part of the chunk fseek($fp, $offset, ($reverse ? SEEK_END : SEEK_SET)); $data .= fread($fp, $chunkSize); // remove last partial line $pos = strrpos($data, "\n"); if($pos) $data = substr($data, 0, $pos); fclose($fp); return $data; } /** * Get the total number of chunks in the file * * @param int $chunkSize * @return int * */ protected function getTotalChunks($chunkSize = 0) { if($chunkSize < 1) $chunkSize = self::defaultChunkSize; $filesize = filesize($this->logFilename); return ceil($filesize / $chunkSize); } /** * Get total number of lines in the log file * * @return int * */ public function getTotalLines() { if(filesize($this->logFilename) < self::defaultChunkSize) { $data = file($this->logFilename); return count($data); } if(!$fp = fopen($this->logFilename, "r")) return 0; $totalLines = 0; while(!feof($fp)) { $data = fread($fp, self::defaultChunkSize); $totalLines += substr_count($data, "\n"); } fclose($fp); return $totalLines; } /** * Get log lines that lie within a date range * * @param int $dateFrom Starting date (unix timestamp or strtotime compatible string) * @param int $dateTo Ending date (unix timestamp or strtotime compatible string) * @param int $pageNum Current pagination number (default=1) * @param int $limit Items per pagination (default=100), or specify 0 for no limit. * @return array * */ public function getDate($dateFrom, $dateTo = 0, $pageNum = 1, $limit = 100) { $options = array( 'dateFrom' => $dateFrom, 'dateTo' => $dateTo, ); return $this->find($limit, $pageNum, $options); } /** * Return lines from the end of the log file, with various options * * @param int $limit Number of items to return (per pagination), or 0 for no limit. * @param int $pageNum Current pagination (default=1) * @param array $options * - text (string): Return only lines containing the given string of text * - reverse (bool): True=find from end of file, false=find from beginning (default=true) * - toFile (string): Send results to the given basename (default=none) * - dateFrom (unix timestamp): Return only lines newer than the given date (default=oldest) * - dateTo (unix timestamp): Return only lines older than the given date (default=now) * Note: dateFrom and dateTo may be combined to return a range. * @return int|array of strings (associative), each indexed by string containing slash separated * numeric values of: "current/total/start/end/total" which is useful with pagination. * If the 'toFile' option is used, then return value is instead an integer qty of lines written. * @throws Exception on fatal error * */ public function find($limit = 100, $pageNum = 1, array $options = array()) { $defaults = array( 'text' => null, 'dateFrom' => 0, 'dateTo' => 0, 'reverse' => true, 'toFile' => '', ); $options = array_merge($defaults, $options); $hasFilters = !empty($options['text']); if($options['dateFrom'] || $options['dateTo']) { if(!$options['dateTo']) $options['dateTo'] = time(); if(!ctype_digit("$options[dateFrom]")) $options['dateFrom'] = strtotime($options['dateFrom']); if(!ctype_digit("$options[dateTo]")) $options['dateTo'] = strtotime($options['dateTo']); $hasFilters = true; } if($options['toFile']) { $toFile = $this->path . basename($options['toFile']); $fp = fopen($toFile, 'w'); if(!$fp) throw new \Exception("Unable to open file for writing: $toFile"); } else { $toFile = ''; $fp = null; } $lines = array(); $start = ($pageNum-1) * $limit; $end = $start + $limit; $cnt = 0; // number that will be written or returned by this $n = 0; // number total $chunkNum = 0; $totalChunks = $this->getTotalChunks(self::defaultChunkSize); $stopNow = false; $chunkLineHashes = array(); while($chunkNum <= $totalChunks && !$stopNow) { $chunk = $this->getChunkArray(++$chunkNum, 0, $options['reverse']); if(empty($chunk)) break; foreach($chunk as $line) { $line = trim($line); $hash = md5($line); $valid = !isset($chunkLineHashes[$hash]); $chunkLineHashes[$hash] = 1; if($valid) $valid = $this->isValidLine($line, $options, $stopNow); if(!$hasFilters && $limit && count($lines) >= $limit) $stopNow = true; if($stopNow) break; if(!$valid) continue; $n++; if($limit && ($n <= $start || $n > $end)) continue; $cnt++; if($fp) { fwrite($fp, $line . "\n"); } else { if(self::debug) $line .= " (line $n, chunk $chunkNum, hash=$hash)"; $lines[$n] = $line; } } } $total = $hasFilters ? $n : $this->getTotalLines(); $end = $start + count($lines); if($end > $total) $end = $total; if(count($lines) < $limit && $total > $end) $total = $end; if($fp) { fclose($fp); $this->wire('files')->chmod($toFile); return $cnt; } foreach($lines as $key => $line) { unset($lines[$key]); $lines["$key/$total/$start/$end/$limit"] = $line; } return $lines; } /** * Returns whether the given log line is valid to be considered a log entry * * @param $line * @param array $options * @param bool $stopNow Populates this with true when it can determine no more lines are necessary. * @return bool|int Returns boolean true if valid, false if not. * If valid as a result of a date comparison, the unix timestmap for the line is returned. * */ protected function isValidLine($line, array $options, &$stopNow) { // 4 7 10 // $test = '2013-10-22 15:18:43'; if(strlen($line) < 20) return false; if($line[19] != $this->delimeter) return false; if($line[4] != "-") return false; if($line[7] != "-") return false; if($line[10] != " ") return false; if(!empty($options['text'])) { if(stripos($line, $options['text']) === false) return false; } if(!empty($options['dateFrom']) && !empty($options['dateTo'])) { $parts = explode($this->delimeter, $line); $date = strtotime($parts[0]); if($date >= $options['dateFrom'] && $date <= $options['dateTo']) return true; if($date < $options['dateFrom'] && $options['reverse']) $stopNow = true; if($date > $options['dateTo'] && !$options['reverse']) $stopNow = true; return false; } return true; } /** * Prune to number of bytes * * @param $bytes * @return bool|int * @deprecated use pruneBytes() or pruneLines() instead * */ public function prune($bytes) { return $this->pruneBytes($bytes); } /** * Prune log file to specified number of bytes (from the end) * * @param int $bytes * @return int|bool positive integer on success, 0 if no prune necessary, or boolean false on failure. * */ public function pruneBytes($bytes) { $filename = $this->logFilename; if(!$filename || !file_exists($filename) || filesize($filename) <= $bytes) return 0; $fpr = fopen($filename, "r"); $fpw = fopen("$filename.new", "w"); if(!$fpr || !$fpw) return false; fseek($fpr, ($bytes * -1), SEEK_END); fgets($fpr, $this->maxLineLength); // first line likely just a partial line, so skip it $cnt = 0; while(!feof($fpr)) { $line = fgets($fpr, $this->maxLineLength); fwrite($fpw, $line); $cnt++; } fclose($fpw); fclose($fpr); if($cnt) { unlink($filename); rename("$filename.new", $filename); $this->wire('files')->chmod($filename); } else { @unlink("$filename.new"); } return $cnt; } /** * Prune log file to contain only entries newer than $oldestDate * * @param int|string $oldestDate * @return int Number of lines written * */ public function pruneDate($oldestDate) { $toFile = $this->logFilename . '.new'; $qty = $this->find(0, 1, array( 'reverse' => false, 'toFile' => $toFile, 'dateFrom' => $oldestDate, 'dateTo' => time(), )); if(file_exists($toFile)) { unlink($this->logFilename); rename($toFile, $this->logFilename); return $qty; } return 0; } /** * Delete the log file * * @return bool * */ public function delete() { return @unlink($this->logFilename); } public function __toString() { return $this->filename(); } public function setDelimiter($c) { $this->delimeter = $c; } public function setDelimeter($c) { $this->setDelimiter($c); } public function setMaxLineLength($c) { $this->maxLineLength = (int) $c; } public function getMaxLineLength() { return $this->maxLineLength; } public function setFileExtension($ext) { $this->fileExtension = $ext; } }
mpl-2.0
erikjalevik/pfand
src/containers/PfNavigator.js
2092
import constants from '../constants' import RequestCollectionScreen from '../containers/RequestCollectionScreen' import ListCollectionsScreen from '../containers/ListCollectionsScreen' import React, { Component } from 'react' import { StyleSheet, Navigator, TouchableHighlight, Text } from 'react-native' const routes = [ {title: 'Add Collection', index: 0}, {title: 'List Collections', index: 1} ] const styles = StyleSheet.create({ navBar: { backgroundColor: constants.textColor }, navText: { color: constants.backgroundColor, fontSize: constants.buttonFontSize, padding: 10 } }) const navBar = ( <Navigator.NavigationBar routeMapper={{ LeftButton: (route, navigator, index, navState) => { if (index !== 0) { return ( <TouchableHighlight onPress={() => navigator.jumpBack()} displayName='BackButton'> <Text style={styles.navText}>Back</Text> </TouchableHighlight> ) } else { return null } }, RightButton: () => null, Title: (route) => { return <Text style={styles.navText} displayName='NavTitle'>{route.title}</Text> } }} style={styles.navBar} displayName='NavigationBar' />) export default class PfNavigator extends Component { displayName = 'PfNavigator' constructor(props) { super(props) } _renderScene(route, navigator) { const pushHandler = () => { navigator.jumpForward() } const popHandler = () => { navigator.jumpBack() } if (route.index === 0) { return <RequestCollectionScreen push={pushHandler} pop={popHandler} /> } else if (route.index === 1) { return <ListCollectionsScreen push={pushHandler} pop={popHandler} /> } else { throw new Error('Invalid route index') } } render() { return ( <Navigator initialRouteStack={routes} initialRoute={routes[0]} navigationBar={navBar} renderScene={this._renderScene} /> ) } }
mpl-2.0
asajeffrey/servo
tests/wpt/web-platform-tests/screen_enumeration/resources/screenenumeration-helpers.js
5220
"use strict"; // In Chromium-based browsers this implementation is provided by a polyfill // in order to reduce the amount of test-only code shipped to users. To enable // these tests the browser must be run with these options: // // --enable-blink-features=MojoJS,MojoJSTest async function loadChromiumResources() { const chromiumResources = [ '/gen/ui/gfx/mojom/color_space.mojom.js', '/gen/ui/gfx/mojom/buffer_types.mojom.js', '/gen/ui/gfx/mojom/display_color_spaces.mojom.js', '/gen/ui/gfx/geometry/mojom/geometry.mojom.js', '/gen/ui/display/mojom/display.mojom.js', '/gen/third_party/blink/public/mojom/screen_enumeration/screen_enumeration.mojom.js' ]; await loadMojoResources(chromiumResources); await loadScript('/resources/testdriver.js'); await loadScript('/resources/testdriver-vendor.js'); await loadScript('/resources/chromium/mock-screenenumeration.js'); } async function initialize_screen_enumeration_tests() { if (typeof ScreenEnumerationTest === "undefined") { const script = document.createElement('script'); script.src = '/resources/test-only-api.js'; script.async = false; const p = new Promise((resolve, reject) => { script.onload = () => { resolve(); }; script.onerror = e => { reject(e); }; }); document.head.appendChild(script); await p; if (isChromiumBased) { await loadChromiumResources(); } } assert_implements(ScreenEnumerationTest, 'Screen Enumeration testing interface is not available.'); let enumTest = new ScreenEnumerationTest(); await enumTest.initialize(); return enumTest; } function screen_enumeration_test(func, name, properties) { promise_test(async t => { let enumTest = await initialize_screen_enumeration_tests(); t.add_cleanup(enumTest.reset); await func(t, enumTest.getMockScreenEnumeration()); }, name, properties); } // Construct a mock display with provided properties function makeDisplay(id, bounds, work_area, scale_factor) { let myColorSpace = fillColorSpaceVector(); let myBufferFormat = fillBufferFormatVector(); let newDisplay = new display.mojom.Display({id: id, bounds: new gfx.mojom.Rect({x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height}), sizeInPixels: new gfx.mojom.Size({width: bounds.width, height: bounds.height}), maximumCursorSize: new gfx.mojom.Size({width: 20, height: 20}), workArea: new gfx.mojom.Rect({x: work_area.x, y: work_area.y, width: work_area.width, height: work_area.height}), deviceScaleFactor: scale_factor, rotation: display.mojom.Rotation.VALUE_0, touchSupport: display.mojom.TouchSupport.UNAVAILABLE, accelerometerSupport: display.mojom.AccelerometerSupport.UNAVAILABLE, colorSpaces: new gfx.mojom.DisplayColorSpaces({colorSpaces: myColorSpace, bufferFormats: myBufferFormat, sdrWhiteLevel: 1.0}), colorDepth: 10, depthPerComponent: 10, isMonochrome: true, displayFrequency: 120}); return newDisplay; } // Function to construct color space vector. // Values are purely random but mandatory. function fillColorSpaceVector() { let colorSpaceVector = []; for (let i = 0; i < 6; i++) { let colorSpace = new gfx.mojom.ColorSpace({ primaries: gfx.mojom.ColorSpacePrimaryID.BT709, transfer: gfx.mojom.ColorSpaceTransferID.BT709, matrix: gfx.mojom.ColorSpaceMatrixID.BT709, range: gfx.mojom.ColorSpaceRangeID.LIMITED, customPrimaryMatrix: fillCustomPrimaryMatrix(), transferParams: fillTransferParams()}); colorSpaceVector.push(colorSpace); } return colorSpaceVector; } function fillCustomPrimaryMatrix () { let matrix = [1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 3.1, 3.2, 3.3]; return matrix; } function fillTransferParams () { let params = [1.1, 1.2, 1.3, 2.1, 2.2, 2.3, 3.1]; return params; } // Function to construct buffer format vector. // Values are purely random but mandatory. function fillBufferFormatVector() { let bufferFormat = [gfx.mojom.BufferFormat.RGBA_8888, gfx.mojom.BufferFormat.RGBA_8888, gfx.mojom.BufferFormat.RGBA_8888, gfx.mojom.BufferFormat.RGBA_8888, gfx.mojom.BufferFormat.RGBA_8888, gfx.mojom.BufferFormat.RGBA_8888]; return bufferFormat; }
mpl-2.0
wx1988/strabon
runtime/src/test/java/eu/earthobservatory/runtime/monetdb/GeneralTests.java
2430
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * Copyright (C) 2010, 2011, 2012, Pyravlos Team * * http://www.strabon.di.uoa.gr/ */ package eu.earthobservatory.runtime.monetdb; import java.io.IOException; import java.sql.SQLException; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.openrdf.query.MalformedQueryException; import org.openrdf.query.QueryEvaluationException; import org.openrdf.query.TupleQueryResultHandlerException; /** * A set of simple tests on SPARQL query functionality * * @author George Garbis <[email protected]> */ public class GeneralTests extends eu.earthobservatory.runtime.generaldb.GeneralTests { @BeforeClass public static void beforeClass() throws Exception { strabon = TemplateTests.beforeClass("/more-tests.nt"); } @AfterClass public static void afterClass() throws SQLException { TemplateTests.afterClass(strabon); } @Test public void testQuerySpatialProperties() throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException { strabon.query(querySpatialPropertiesMonetDB,strabon.getSailRepoConnection()); } @Test public void testQuerySpatialPropertiesConst() throws MalformedQueryException, QueryEvaluationException, TupleQueryResultHandlerException, IOException { strabon.query(querySpatialPropertiesConstMonetDB,strabon.getSailRepoConnection()); } // /** // * @throws java.lang.Exception // */ // @Before // public void before() // throws Exception // { // // } // // /** // * @throws java.lang.Exception // */ // @After // public void after() // throws Exception // { // // Clean database // Statement stmt = conn.createStatement(); // ResultSet results = stmt.executeQuery("SELECT table_name FROM information_schema.tables WHERE " + // "table_schema='public' and table_name <> 'spatial_ref_sys' " + // "and table_name <> 'geometry_columns' and " + // "table_name <> 'geography_columns' and table_name <> 'locked'"); // while (results.next()) { // String table_name = results.getString("table_name"); // Statement stmt2 = conn.createStatement(); // stmt2.executeUpdate("DROP TABLE \""+table_name+"\""); // stmt2.close(); // } // // stmt.close(); // } }
mpl-2.0
WolframG/Rhino-Prov-Mod
src/org/mozilla/javascript/orginal/Interpreter.java
118300
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.javascript.orginal; import java.io.PrintStream; import java.io.Serializable; import java.util.List; import java.util.ArrayList; import org.mozilla.javascript.orginal.ast.FunctionNode; import org.mozilla.javascript.orginal.ast.ScriptNode; import org.mozilla.javascript.orginal.ScriptRuntime.NoSuchMethodShim; import org.mozilla.javascript.orginal.debug.DebugFrame; import static org.mozilla.javascript.orginal.UniqueTag.DOUBLE_MARK; public final class Interpreter extends Icode implements Evaluator { // data for parsing InterpreterData itsData; static final int EXCEPTION_TRY_START_SLOT = 0; static final int EXCEPTION_TRY_END_SLOT = 1; static final int EXCEPTION_HANDLER_SLOT = 2; static final int EXCEPTION_TYPE_SLOT = 3; static final int EXCEPTION_LOCAL_SLOT = 4; static final int EXCEPTION_SCOPE_SLOT = 5; // SLOT_SIZE: space for try start/end, handler, start, handler type, // exception local and scope local static final int EXCEPTION_SLOT_SIZE = 6; /** * Class to hold data corresponding to one interpreted call stack frame. */ private static class CallFrame implements Cloneable, Serializable { static final long serialVersionUID = -2843792508994958978L; CallFrame parentFrame; // amount of stack frames before this one on the interpretation stack int frameIndex; // If true indicates read-only frame that is a part of continuation boolean frozen; InterpretedFunction fnOrScript; InterpreterData idata; // Stack structure // stack[0 <= i < localShift]: arguments and local variables // stack[localShift <= i <= emptyStackTop]: used for local temporaries // stack[emptyStackTop < i < stack.length]: stack data // sDbl[i]: if stack[i] is UniqueTag.DOUBLE_MARK, sDbl[i] holds the number value Object[] stack; int[] stackAttributes; double[] sDbl; CallFrame varSource; // defaults to this unless continuation frame int localShift; int emptyStackTop; DebugFrame debuggerFrame; boolean useActivation; boolean isContinuationsTopFrame; Scriptable thisObj; // The values that change during interpretation Object result; double resultDbl; int pc; int pcPrevBranch; int pcSourceLineStart; Scriptable scope; int savedStackTop; int savedCallOp; Object throwable; CallFrame cloneFrozen() { if (!frozen) Kit.codeBug(); CallFrame copy; try { copy = (CallFrame)clone(); } catch (CloneNotSupportedException ex) { throw new IllegalStateException(); } // clone stack but keep varSource to point to values // from this frame to share variables. copy.stack = stack.clone(); copy.stackAttributes = stackAttributes.clone(); copy.sDbl = sDbl.clone(); copy.frozen = false; return copy; } } private static final class ContinuationJump implements Serializable { static final long serialVersionUID = 7687739156004308247L; CallFrame capturedFrame; CallFrame branchFrame; Object result; double resultDbl; ContinuationJump(NativeContinuation c, CallFrame current) { this.capturedFrame = (CallFrame)c.getImplementation(); if (this.capturedFrame == null || current == null) { // Continuation and current execution does not share // any frames if there is nothing to capture or // if there is no currently executed frames this.branchFrame = null; } else { // Search for branch frame where parent frame chains starting // from captured and current meet. CallFrame chain1 = this.capturedFrame; CallFrame chain2 = current; // First work parents of chain1 or chain2 until the same // frame depth. int diff = chain1.frameIndex - chain2.frameIndex; if (diff != 0) { if (diff < 0) { // swap to make sure that // chain1.frameIndex > chain2.frameIndex and diff > 0 chain1 = current; chain2 = this.capturedFrame; diff = -diff; } do { chain1 = chain1.parentFrame; } while (--diff != 0); if (chain1.frameIndex != chain2.frameIndex) Kit.codeBug(); } // Now walk parents in parallel until a shared frame is found // or until the root is reached. while (chain1 != chain2 && chain1 != null) { chain1 = chain1.parentFrame; chain2 = chain2.parentFrame; } this.branchFrame = chain1; if (this.branchFrame != null && !this.branchFrame.frozen) Kit.codeBug(); } } } private static CallFrame captureFrameForGenerator(CallFrame frame) { frame.frozen = true; CallFrame result = frame.cloneFrozen(); frame.frozen = false; // now isolate this frame from its previous context result.parentFrame = null; result.frameIndex = 0; return result; } static { // Checks for byte code consistencies, good compiler can eliminate them if (Token.LAST_BYTECODE_TOKEN > 127) { String str = "Violation of Token.LAST_BYTECODE_TOKEN <= 127"; System.err.println(str); throw new IllegalStateException(str); } if (MIN_ICODE < -128) { String str = "Violation of Interpreter.MIN_ICODE >= -128"; System.err.println(str); throw new IllegalStateException(str); } } public Object compile(CompilerEnvirons compilerEnv, ScriptNode tree, String encodedSource, boolean returnFunction) { CodeGenerator cgen = new CodeGenerator(); itsData = cgen.compile(compilerEnv, tree, encodedSource, returnFunction); return itsData; } public Script createScriptObject(Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createScript(itsData, staticSecurityDomain); } public void setEvalScriptFlag(Script script) { ((InterpretedFunction)script).idata.evalScriptFlag = true; } public Function createFunctionObject(Context cx, Scriptable scope, Object bytecode, Object staticSecurityDomain) { if(bytecode != itsData) { Kit.codeBug(); } return InterpretedFunction.createFunction(cx, scope, itsData, staticSecurityDomain); } private static int getShort(byte[] iCode, int pc) { return (iCode[pc] << 8) | (iCode[pc + 1] & 0xFF); } private static int getIndex(byte[] iCode, int pc) { return ((iCode[pc] & 0xFF) << 8) | (iCode[pc + 1] & 0xFF); } private static int getInt(byte[] iCode, int pc) { return (iCode[pc] << 24) | ((iCode[pc + 1] & 0xFF) << 16) | ((iCode[pc + 2] & 0xFF) << 8) | (iCode[pc + 3] & 0xFF); } private static int getExceptionHandler(CallFrame frame, boolean onlyFinally) { int[] exceptionTable = frame.idata.itsExceptionTable; if (exceptionTable == null) { // No exception handlers return -1; } // Icode switch in the interpreter increments PC immediately // and it is necessary to subtract 1 from the saved PC // to point it before the start of the next instruction. int pc = frame.pc - 1; // OPT: use binary search int best = -1, bestStart = 0, bestEnd = 0; for (int i = 0; i != exceptionTable.length; i += EXCEPTION_SLOT_SIZE) { int start = exceptionTable[i + EXCEPTION_TRY_START_SLOT]; int end = exceptionTable[i + EXCEPTION_TRY_END_SLOT]; if (!(start <= pc && pc < end)) { continue; } if (onlyFinally && exceptionTable[i + EXCEPTION_TYPE_SLOT] != 1) { continue; } if (best >= 0) { // Since handlers always nest and they never have shared end // although they can share start it is sufficient to compare // handlers ends if (bestEnd < end) { continue; } // Check the above assumption if (bestStart > start) Kit.codeBug(); // should be nested if (bestEnd == end) Kit.codeBug(); // no ens sharing } best = i; bestStart = start; bestEnd = end; } return best; } static void dumpICode(InterpreterData idata) { if (!Token.printICode) { return; } byte iCode[] = idata.itsICode; int iCodeLength = iCode.length; String[] strings = idata.itsStringTable; PrintStream out = System.out; out.println("ICode dump, for " + idata.itsName + ", length = " + iCodeLength); out.println("MaxStack = " + idata.itsMaxStack); int indexReg = 0; for (int pc = 0; pc < iCodeLength; ) { out.flush(); out.print(" [" + pc + "] "); int token = iCode[pc]; int icodeLength = bytecodeSpan(token); String tname = Icode.bytecodeName(token); int old_pc = pc; ++pc; switch (token) { default: if (icodeLength != 1) Kit.codeBug(); out.println(tname); break; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : { int newPC = pc + getShort(iCode, pc) - 1; out.println(tname + " " + newPC); pc += 2; break; } case Icode_VAR_INC_DEC : case Icode_NAME_INC_DEC : case Icode_PROP_INC_DEC : case Icode_ELEM_INC_DEC : case Icode_REF_INC_DEC: { int incrDecrType = iCode[pc]; out.println(tname + " " + incrDecrType); ++pc; break; } case Icode_CALLSPECIAL : { int callType = iCode[pc] & 0xFF; boolean isNew = (iCode[pc + 1] != 0); int line = getIndex(iCode, pc+2); out.println(tname+" "+callType+" "+isNew+" "+indexReg+" "+line); pc += 4; break; } case Token.CATCH_SCOPE: { boolean afterFisrtFlag = (iCode[pc] != 0); out.println(tname+" "+afterFisrtFlag); ++pc; } break; case Token.REGEXP : out.println(tname+" "+idata.itsRegExpLiterals[indexReg]); break; case Token.OBJECTLIT : case Icode_SPARE_ARRAYLIT : out.println(tname+" "+idata.literalIds[indexReg]); break; case Icode_CLOSURE_EXPR : case Icode_CLOSURE_STMT : out.println(tname+" "+idata.itsNestedFunctions[indexReg]); break; case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : case Token.NEW : out.println(tname+' '+indexReg); break; case Token.THROW : case Token.YIELD : case Icode_GENERATOR : case Icode_GENERATOR_END : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_SHORTNUMBER : { int value = getShort(iCode, pc); out.println(tname + " " + value); pc += 2; break; } case Icode_INTNUMBER : { int value = getInt(iCode, pc); out.println(tname + " " + value); pc += 4; break; } case Token.NUMBER : { double value = idata.itsDoubleTable[indexReg]; out.println(tname + " " + value); break; } case Icode_LINE : { int line = getIndex(iCode, pc); out.println(tname + " : " + line); pc += 2; break; } case Icode_REG_STR1: { String str = strings[0xFF & iCode[pc]]; out.println(tname + " \"" + str + '"'); ++pc; break; } case Icode_REG_STR2: { String str = strings[getIndex(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 2; break; } case Icode_REG_STR4: { String str = strings[getInt(iCode, pc)]; out.println(tname + " \"" + str + '"'); pc += 4; break; } case Icode_REG_IND_C0: indexReg = 0; out.println(tname); break; case Icode_REG_IND_C1: indexReg = 1; out.println(tname); break; case Icode_REG_IND_C2: indexReg = 2; out.println(tname); break; case Icode_REG_IND_C3: indexReg = 3; out.println(tname); break; case Icode_REG_IND_C4: indexReg = 4; out.println(tname); break; case Icode_REG_IND_C5: indexReg = 5; out.println(tname); break; case Icode_REG_IND1: { indexReg = 0xFF & iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } case Icode_REG_IND2: { indexReg = getIndex(iCode, pc); out.println(tname+" "+indexReg); pc += 2; break; } case Icode_REG_IND4: { indexReg = getInt(iCode, pc); out.println(tname+" "+indexReg); pc += 4; break; } case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: indexReg = iCode[pc]; out.println(tname+" "+indexReg); ++pc; break; } if (old_pc + icodeLength != pc) Kit.codeBug(); } int[] table = idata.itsExceptionTable; if (table != null) { out.println("Exception handlers: " +table.length / EXCEPTION_SLOT_SIZE); for (int i = 0; i != table.length; i += EXCEPTION_SLOT_SIZE) { int tryStart = table[i + EXCEPTION_TRY_START_SLOT]; int tryEnd = table[i + EXCEPTION_TRY_END_SLOT]; int handlerStart = table[i + EXCEPTION_HANDLER_SLOT]; int type = table[i + EXCEPTION_TYPE_SLOT]; int exceptionLocal = table[i + EXCEPTION_LOCAL_SLOT]; int scopeLocal = table[i + EXCEPTION_SCOPE_SLOT]; out.println(" tryStart="+tryStart+" tryEnd="+tryEnd +" handlerStart="+handlerStart +" type="+(type == 0 ? "catch" : "finally") +" exceptionLocal="+exceptionLocal); } } out.flush(); } private static int bytecodeSpan(int bytecode) { switch (bytecode) { case Token.THROW : case Token.YIELD: case Icode_GENERATOR: case Icode_GENERATOR_END: // source line return 1 + 2; case Icode_GOSUB : case Token.GOTO : case Token.IFEQ : case Token.IFNE : case Icode_IFEQ_POP : case Icode_LEAVEDQ : // target pc offset return 1 + 2; case Icode_CALLSPECIAL : // call type // is new // line number return 1 + 1 + 1 + 2; case Token.CATCH_SCOPE: // scope flag return 1 + 1; case Icode_VAR_INC_DEC: case Icode_NAME_INC_DEC: case Icode_PROP_INC_DEC: case Icode_ELEM_INC_DEC: case Icode_REF_INC_DEC: // type of ++/-- return 1 + 1; case Icode_SHORTNUMBER : // short number return 1 + 2; case Icode_INTNUMBER : // int number return 1 + 4; case Icode_REG_IND1: // ubyte index return 1 + 1; case Icode_REG_IND2: // ushort index return 1 + 2; case Icode_REG_IND4: // int index return 1 + 4; case Icode_REG_STR1: // ubyte string index return 1 + 1; case Icode_REG_STR2: // ushort string index return 1 + 2; case Icode_REG_STR4: // int string index return 1 + 4; case Icode_GETVAR1: case Icode_SETVAR1: case Icode_SETCONSTVAR1: // byte var index return 1 + 1; case Icode_LINE : // line number return 1 + 2; } if (!validBytecode(bytecode)) throw Kit.codeBug(); return 1; } static int[] getLineNumbers(InterpreterData data) { UintMap presentLines = new UintMap(); byte[] iCode = data.itsICode; int iCodeLength = iCode.length; for (int pc = 0; pc != iCodeLength;) { int bytecode = iCode[pc]; int span = bytecodeSpan(bytecode); if (bytecode == Icode_LINE) { if (span != 3) Kit.codeBug(); int line = getIndex(iCode, pc + 1); presentLines.put(line, 0); } pc += span; } return presentLines.getKeys(); } public void captureStackInfo(RhinoException ex) { Context cx = Context.getCurrentContext(); if (cx == null || cx.lastInterpreterFrame == null) { // No interpreter invocations ex.interpreterStackInfo = null; ex.interpreterLineData = null; return; } // has interpreter frame on the stack CallFrame[] array; if (cx.previousInterpreterInvocations == null || cx.previousInterpreterInvocations.size() == 0) { array = new CallFrame[1]; } else { int previousCount = cx.previousInterpreterInvocations.size(); if (cx.previousInterpreterInvocations.peek() == cx.lastInterpreterFrame) { // It can happen if exception was generated after // frame was pushed to cx.previousInterpreterInvocations // but before assignment to cx.lastInterpreterFrame. // In this case frames has to be ignored. --previousCount; } array = new CallFrame[previousCount + 1]; cx.previousInterpreterInvocations.toArray(array); } array[array.length - 1] = (CallFrame)cx.lastInterpreterFrame; int interpreterFrameCount = 0; for (int i = 0; i != array.length; ++i) { interpreterFrameCount += 1 + array[i].frameIndex; } int[] linePC = new int[interpreterFrameCount]; // Fill linePC with pc positions from all interpreter frames. // Start from the most nested frame int linePCIndex = interpreterFrameCount; for (int i = array.length; i != 0;) { --i; CallFrame frame = array[i]; while (frame != null) { --linePCIndex; linePC[linePCIndex] = frame.pcSourceLineStart; frame = frame.parentFrame; } } if (linePCIndex != 0) Kit.codeBug(); ex.interpreterStackInfo = array; ex.interpreterLineData = linePC; } public String getSourcePositionFromStack(Context cx, int[] linep) { CallFrame frame = (CallFrame)cx.lastInterpreterFrame; InterpreterData idata = frame.idata; if (frame.pcSourceLineStart >= 0) { linep[0] = getIndex(idata.itsICode, frame.pcSourceLineStart); } else { linep[0] = 0; } return idata.itsSourceFile; } public String getPatchedStack(RhinoException ex, String nativeStackTrace) { String tag = "org.mozilla.javascript.orginal.Interpreter.interpretLoop"; StringBuffer sb = new StringBuffer(nativeStackTrace.length() + 1000); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; int offset = 0; while (arrayIndex != 0) { --arrayIndex; int pos = nativeStackTrace.indexOf(tag, offset); if (pos < 0) { break; } // Skip tag length pos += tag.length(); // Skip until the end of line for (; pos != nativeStackTrace.length(); ++pos) { char c = nativeStackTrace.charAt(pos); if (c == '\n' || c == '\r') { break; } } sb.append(nativeStackTrace.substring(offset, pos)); offset = pos; CallFrame frame = array[arrayIndex]; while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; sb.append(lineSeparator); sb.append("\tat script"); if (idata.itsName != null && idata.itsName.length() != 0) { sb.append('.'); sb.append(idata.itsName); } sb.append('('); sb.append(idata.itsSourceFile); int pc = linePC[linePCIndex]; if (pc >= 0) { // Include line info only if available sb.append(':'); sb.append(getIndex(idata.itsICode, pc)); } sb.append(')'); frame = frame.parentFrame; } } sb.append(nativeStackTrace.substring(offset)); return sb.toString(); } public List<String> getScriptStack(RhinoException ex) { ScriptStackElement[][] stack = getScriptStackElements(ex); List<String> list = new ArrayList<String>(stack.length); String lineSeparator = SecurityUtilities.getSystemProperty("line.separator"); for (ScriptStackElement[] group : stack) { StringBuilder sb = new StringBuilder(); for (ScriptStackElement elem : group) { elem.renderJavaStyle(sb); sb.append(lineSeparator); } list.add(sb.toString()); } return list; } public ScriptStackElement[][] getScriptStackElements(RhinoException ex) { if (ex.interpreterStackInfo == null) { return null; } List<ScriptStackElement[]> list = new ArrayList<ScriptStackElement[]>(); CallFrame[] array = (CallFrame[])ex.interpreterStackInfo; int[] linePC = ex.interpreterLineData; int arrayIndex = array.length; int linePCIndex = linePC.length; while (arrayIndex != 0) { --arrayIndex; CallFrame frame = array[arrayIndex]; List<ScriptStackElement> group = new ArrayList<ScriptStackElement>(); while (frame != null) { if (linePCIndex == 0) Kit.codeBug(); --linePCIndex; InterpreterData idata = frame.idata; String fileName = idata.itsSourceFile; String functionName = null; int lineNumber = -1; int pc = linePC[linePCIndex]; if (pc >= 0) { lineNumber = getIndex(idata.itsICode, pc); } if (idata.itsName != null && idata.itsName.length() != 0) { functionName = idata.itsName; } frame = frame.parentFrame; group.add(new ScriptStackElement(fileName, functionName, lineNumber)); } list.add(group.toArray(new ScriptStackElement[group.size()])); } return list.toArray(new ScriptStackElement[list.size()][]); } static String getEncodedSource(InterpreterData idata) { if (idata.encodedSource == null) { return null; } return idata.encodedSource.substring(idata.encodedSourceStart, idata.encodedSourceEnd); } private static void initFunction(Context cx, Scriptable scope, InterpretedFunction parent, int index) { InterpretedFunction fn; fn = InterpretedFunction.createFunction(cx, scope, parent, index); ScriptRuntime.initFunction(cx, scope, fn, fn.idata.itsFunctionType, parent.idata.evalScriptFlag); } static Object interpret(InterpretedFunction ifun, Context cx, Scriptable scope, Scriptable thisObj, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) Kit.codeBug(); if (cx.interpreterSecurityDomain != ifun.securityDomain) { Object savedDomain = cx.interpreterSecurityDomain; cx.interpreterSecurityDomain = ifun.securityDomain; try { return ifun.securityController.callWithDomain( ifun.securityDomain, cx, ifun, scope, thisObj, args); } finally { cx.interpreterSecurityDomain = savedDomain; } } CallFrame frame = new CallFrame(); initFrame(cx, scope, thisObj, args, null, 0, args.length, ifun, null, frame); frame.isContinuationsTopFrame = cx.isContinuationsTopCall; cx.isContinuationsTopCall = false; return interpretLoop(cx, frame, null); } static class GeneratorState { GeneratorState(int operation, Object value) { this.operation = operation; this.value = value; } int operation; Object value; RuntimeException returnedException; } public static Object resumeGenerator(Context cx, Scriptable scope, int operation, Object savedState, Object value) { CallFrame frame = (CallFrame) savedState; GeneratorState generatorState = new GeneratorState(operation, value); if (operation == NativeGenerator.GENERATOR_CLOSE) { try { return interpretLoop(cx, frame, generatorState); } catch (RuntimeException e) { // Only propagate exceptions other than closingException if (e != value) throw e; } return Undefined.instance; } Object result = interpretLoop(cx, frame, generatorState); if (generatorState.returnedException != null) throw generatorState.returnedException; return result; } public static Object restartContinuation(NativeContinuation c, Context cx, Scriptable scope, Object[] args) { if (!ScriptRuntime.hasTopCall(cx)) { return ScriptRuntime.doTopCall(c, cx, scope, null, args); } Object arg; if (args.length == 0) { arg = Undefined.instance; } else { arg = args[0]; } CallFrame capturedFrame = (CallFrame)c.getImplementation(); if (capturedFrame == null) { // No frames to restart return arg; } ContinuationJump cjump = new ContinuationJump(c, null); cjump.result = arg; return interpretLoop(cx, null, cjump); } private static Object interpretLoop(Context cx, CallFrame frame, Object throwable) { // throwable holds exception object to rethrow or catch // It is also used for continuation restart in which case // it holds ContinuationJump final Object DBL_MRK = DOUBLE_MARK; final Object undefined = Undefined.instance; final boolean instructionCounting = (cx.instructionThreshold != 0); // arbitrary number to add to instructionCount when calling // other functions final int INVOCATION_COST = 100; // arbitrary exception cost for instruction counting final int EXCEPTION_COST = 100; String stringReg = null; int indexReg = -1; if (cx.lastInterpreterFrame != null) { // save the top frame from the previous interpretLoop // invocation on the stack if (cx.previousInterpreterInvocations == null) { cx.previousInterpreterInvocations = new ObjArray(); } cx.previousInterpreterInvocations.push(cx.lastInterpreterFrame); } // When restarting continuation throwable is not null and to jump // to the code that rewind continuation state indexReg should be set // to -1. // With the normal call throwable == null and indexReg == -1 allows to // catch bugs with using indeReg to access array elements before // initializing indexReg. GeneratorState generatorState = null; if (throwable != null) { if (throwable instanceof GeneratorState) { generatorState = (GeneratorState) throwable; // reestablish this call frame enterFrame(cx, frame, ScriptRuntime.emptyArgs, true); throwable = null; } else if (!(throwable instanceof ContinuationJump)) { // It should be continuation Kit.codeBug(); } } Object interpreterResult = null; double interpreterResultDbl = 0.0; StateLoop: for (;;) { withoutExceptions: try { if (throwable != null) { // Need to return both 'frame' and 'throwable' from // 'processThrowable', so just added a 'throwable' // member in 'frame'. frame = processThrowable(cx, throwable, frame, indexReg, instructionCounting); throwable = frame.throwable; frame.throwable = null; } else { if (generatorState == null && frame.frozen) Kit.codeBug(); } // Use local variables for constant values in frame // for faster access Object[] stack = frame.stack; double[] sDbl = frame.sDbl; Object[] vars = frame.varSource.stack; double[] varDbls = frame.varSource.sDbl; int[] varAttributes = frame.varSource.stackAttributes; byte[] iCode = frame.idata.itsICode; String[] strings = frame.idata.itsStringTable; // Use local for stackTop as well. Since execption handlers // can only exist at statement level where stack is empty, // it is necessary to save/restore stackTop only across // function calls and normal returns. int stackTop = frame.savedStackTop; // Store new frame in cx which is used for error reporting etc. cx.lastInterpreterFrame = frame; Loop: for (;;) { // Exception handler assumes that PC is already incremented // pass the instruction start when it searches the // exception handler int op = iCode[frame.pc++]; jumplessRun: { // Back indent to ease implementation reading switch (op) { case Icode_GENERATOR: { if (!frame.frozen) { // First time encountering this opcode: create new generator // object and return frame.pc--; // we want to come back here when we resume CallFrame generatorFrame = captureFrameForGenerator(frame); generatorFrame.frozen = true; NativeGenerator generator = new NativeGenerator(frame.scope, generatorFrame.fnOrScript, generatorFrame); frame.result = generator; break Loop; } else { // We are now resuming execution. Fall through to YIELD case. } } // fall through... case Token.YIELD: { if (!frame.frozen) { return freezeGenerator(cx, frame, stackTop, generatorState); } else { Object obj = thawGenerator(frame, stackTop, generatorState, op); if (obj != Scriptable.NOT_FOUND) { throwable = obj; break withoutExceptions; } continue Loop; } } case Icode_GENERATOR_END: { // throw StopIteration frame.frozen = true; int sourceLine = getIndex(iCode, frame.pc); generatorState.returnedException = new JavaScriptException( NativeIterator.getStopIterationObject(frame.scope), frame.idata.itsSourceFile, sourceLine); break Loop; } case Token.THROW: { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int sourceLine = getIndex(iCode, frame.pc); throwable = new JavaScriptException(value, frame.idata.itsSourceFile, sourceLine); break withoutExceptions; } case Token.RETHROW: { indexReg += frame.localShift; throwable = stack[indexReg]; break withoutExceptions; } case Token.GE : case Token.LE : case Token.GT : case Token.LT : { stackTop = doCompare(frame, op, stack, sDbl, stackTop); continue Loop; } case Token.IN : case Token.INSTANCEOF : { stackTop = doInOrInstanceof(cx, op, stack, sDbl, stackTop); continue Loop; } case Token.EQ : case Token.NE : { --stackTop; boolean valBln = doEquals(stack, sDbl, stackTop); valBln ^= (op == Token.NE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.SHEQ : case Token.SHNE : { --stackTop; boolean valBln = doShallowEquals(stack, sDbl, stackTop); valBln ^= (op == Token.SHNE); stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); continue Loop; } case Token.IFNE : if (stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Token.IFEQ : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } break jumplessRun; case Icode_IFEQ_POP : if (!stack_boolean(frame, stackTop--)) { frame.pc += 2; continue Loop; } stack[stackTop--] = null; break jumplessRun; case Token.GOTO : break jumplessRun; case Icode_GOSUB : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.pc + 2; break jumplessRun; case Icode_STARTSUB : if (stackTop == frame.emptyStackTop + 1) { // Call from Icode_GOSUB: store return PC address in the local indexReg += frame.localShift; stack[indexReg] = stack[stackTop]; sDbl[indexReg] = sDbl[stackTop]; --stackTop; } else { // Call from exception handler: exception object is already stored // in the local if (stackTop != frame.emptyStackTop) Kit.codeBug(); } continue Loop; case Icode_RETSUB : { // indexReg: local to store return address if (instructionCounting) { addInstructionCount(cx, frame, 0); } indexReg += frame.localShift; Object value = stack[indexReg]; if (value != DBL_MRK) { // Invocation from exception handler, restore object to rethrow throwable = value; break withoutExceptions; } // Normal return from GOSUB frame.pc = (int)sDbl[indexReg]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } case Icode_POP : stack[stackTop] = null; stackTop--; continue Loop; case Icode_POP_RESULT : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; stack[stackTop] = null; --stackTop; continue Loop; case Icode_DUP : stack[stackTop + 1] = stack[stackTop]; sDbl[stackTop + 1] = sDbl[stackTop]; stackTop++; continue Loop; case Icode_DUP2 : stack[stackTop + 1] = stack[stackTop - 1]; sDbl[stackTop + 1] = sDbl[stackTop - 1]; stack[stackTop + 2] = stack[stackTop]; sDbl[stackTop + 2] = sDbl[stackTop]; stackTop += 2; continue Loop; case Icode_SWAP : { Object o = stack[stackTop]; stack[stackTop] = stack[stackTop - 1]; stack[stackTop - 1] = o; double d = sDbl[stackTop]; sDbl[stackTop] = sDbl[stackTop - 1]; sDbl[stackTop - 1] = d; continue Loop; } case Token.RETURN : frame.result = stack[stackTop]; frame.resultDbl = sDbl[stackTop]; --stackTop; break Loop; case Token.RETURN_RESULT : break Loop; case Icode_RETUNDEF : frame.result = undefined; break Loop; case Token.BITNOT : { int rIntValue = stack_int32(frame, stackTop); stack[stackTop] = DBL_MRK; sDbl[stackTop] = ~rIntValue; continue Loop; } case Token.BITAND : case Token.BITOR : case Token.BITXOR : case Token.LSH : case Token.RSH : { stackTop = doBitOp(frame, op, stack, sDbl, stackTop); continue Loop; } case Token.URSH : { double lDbl = stack_double(frame, stackTop - 1); int rIntValue = stack_int32(frame, stackTop) & 0x1F; stack[--stackTop] = DBL_MRK; sDbl[stackTop] = ScriptRuntime.toUint32(lDbl) >>> rIntValue; continue Loop; } case Token.NEG : case Token.POS : { double rDbl = stack_double(frame, stackTop); stack[stackTop] = DBL_MRK; if (op == Token.NEG) { rDbl = -rDbl; } sDbl[stackTop] = rDbl; continue Loop; } case Token.ADD : --stackTop; doAdd(stack, sDbl, stackTop, cx); continue Loop; case Token.SUB : case Token.MUL : case Token.DIV : case Token.MOD : { stackTop = doArithmetic(frame, op, stack, sDbl, stackTop); continue Loop; } case Token.NOT : stack[stackTop] = ScriptRuntime.wrapBoolean( !stack_boolean(frame, stackTop)); continue Loop; case Token.BINDNAME : stack[++stackTop] = ScriptRuntime.bind(cx, frame.scope, stringReg); continue Loop; case Token.STRICT_SETNAME: case Token.SETNAME : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = op == Token.SETNAME ? ScriptRuntime.setName(lhs, rhs, cx, frame.scope, stringReg) : ScriptRuntime.strictSetName(lhs, rhs, cx, frame.scope, stringReg); continue Loop; } case Icode_SETCONST: { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Scriptable lhs = (Scriptable)stack[stackTop]; stack[stackTop] = ScriptRuntime.setConst(lhs, rhs, cx, stringReg); continue Loop; } case Token.DELPROP : case Icode_DELNAME : { stackTop = doDelName(cx, op, stack, sDbl, stackTop); continue Loop; } case Token.GETPROPNOWARN : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectPropNoWarn(lhs, stringReg, cx); continue Loop; } case Token.GETPROP : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getObjectProp(lhs, stringReg, cx, frame.scope); continue Loop; } case Token.SETPROP : { Object rhs = stack[stackTop]; if (rhs == DBL_MRK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setObjectProp(lhs, stringReg, rhs, cx); continue Loop; } case Icode_PROP_INC_DEC : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.propIncrDecr(lhs, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.GETELEM : { stackTop = doGetElem(cx, frame, stack, sDbl, stackTop); continue Loop; } case Token.SETELEM : { stackTop = doSetElem(cx, stack, sDbl, stackTop); continue Loop; } case Icode_ELEM_INC_DEC: { stackTop = doElemIncDec(cx, frame, iCode, stack, sDbl, stackTop); continue Loop; } case Token.GET_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refGet(ref, cx); continue Loop; } case Token.SET_REF : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refSet(ref, value, cx); continue Loop; } case Token.DEL_REF : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refDel(ref, cx); continue Loop; } case Icode_REF_INC_DEC : { Ref ref = (Ref)stack[stackTop]; stack[stackTop] = ScriptRuntime.refIncrDecr(ref, cx, iCode[frame.pc]); ++frame.pc; continue Loop; } case Token.LOCAL_LOAD : ++stackTop; indexReg += frame.localShift; stack[stackTop] = stack[indexReg]; sDbl[stackTop] = sDbl[indexReg]; continue Loop; case Icode_LOCAL_CLEAR : indexReg += frame.localShift; stack[indexReg] = null; continue Loop; case Icode_NAME_AND_THIS : // stringReg: name ++stackTop; stack[stackTop] = ScriptRuntime.getNameFunctionAndThis(stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; case Icode_PROP_AND_THIS: { Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); // stringReg: property stack[stackTop] = ScriptRuntime.getPropFunctionAndThis(obj, stringReg, cx, frame.scope); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_ELEM_AND_THIS: { Object obj = stack[stackTop - 1]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop - 1]); Object id = stack[stackTop]; if (id == DBL_MRK) id = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop - 1] = ScriptRuntime.getElemFunctionAndThis(obj, id, cx); stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_VALUE_AND_THIS : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.getValueFunctionAndThis(value, cx); ++stackTop; stack[stackTop] = ScriptRuntime.lastStoredScriptable(cx); continue Loop; } case Icode_CALLSPECIAL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } stackTop = doCallSpecial(cx, frame, stack, sDbl, stackTop, iCode, indexReg); continue Loop; } case Token.CALL : case Icode_TAIL_CALL : case Token.REF_CALL : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function thisObj arg0 .. argN -> result // indexReg: number of arguments stackTop -= 1 + indexReg; // CALL generation ensures that fun and funThisObj // are already Scriptable and Callable objects respectively Callable fun = (Callable)stack[stackTop]; Scriptable funThisObj = (Scriptable)stack[stackTop + 1]; if (op == Token.REF_CALL) { Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callRef(fun, funThisObj, outArgs, cx); continue Loop; } Scriptable calleeScope = frame.scope; if (frame.useActivation) { calleeScope = ScriptableObject.getTopLevelScope(frame.scope); } if (fun instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction)fun; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { // In principle tail call can re-use the current // frame and its stack arrays but it is hard to // do properly. Any exceptions that can legally // happen during frame re-initialization including // StackOverflowException during innocent looking // System.arraycopy may leave the current frame // data corrupted leading to undefined behaviour // in the catch code bellow that unwinds JS stack // on exceptions. Then there is issue about frame release // end exceptions there. // To avoid frame allocation a released frame // can be cached for re-use which would also benefit // non-tail calls but it is not clear that this caching // would gain in performance due to potentially // bad interaction with GC. callParentFrame = frame.parentFrame; // Release the current frame. See Bug #344501 to see why // it is being done here. exitFrame(cx, frame, null); } initFrame(cx, calleeScope, funThisObj, stack, sDbl, stackTop + 2, indexReg, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } frame = calleeFrame; continue StateLoop; } } if (fun instanceof NativeContinuation) { // Jump to the captured continuation ContinuationJump cjump; cjump = new ContinuationJump((NativeContinuation)fun, frame); // continuation result is the first argument if any // of continuation call if (indexReg == 0) { cjump.result = undefined; } else { cjump.result = stack[stackTop + 2]; cjump.resultDbl = sDbl[stackTop + 2]; } // Start the real unwind job throwable = cjump; break withoutExceptions; } if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (NativeContinuation.isContinuationConstructor(ifun)) { frame.stack[stackTop] = captureContinuation(cx, frame.parentFrame, false); continue Loop; } // Bug 405654 -- make best effort to keep Function.apply and // Function.call within this interpreter loop invocation if (BaseFunction.isApplyOrCall(ifun)) { Callable applyCallable = ScriptRuntime.getCallable(funThisObj); if (applyCallable instanceof InterpretedFunction) { InterpretedFunction iApplyCallable = (InterpretedFunction)applyCallable; if (frame.fnOrScript.securityDomain == iApplyCallable.securityDomain) { frame = initFrameForApplyOrCall(cx, frame, indexReg, stack, sDbl, stackTop, op, calleeScope, ifun, iApplyCallable); continue StateLoop; } } } } // Bug 447697 -- make best effort to keep __noSuchMethod__ within this // interpreter loop invocation if (fun instanceof NoSuchMethodShim) { // get the shim and the actual method NoSuchMethodShim noSuchMethodShim = (NoSuchMethodShim) fun; Callable noSuchMethodMethod = noSuchMethodShim.noSuchMethodMethod; // if the method is in fact an InterpretedFunction if (noSuchMethodMethod instanceof InterpretedFunction) { InterpretedFunction ifun = (InterpretedFunction) noSuchMethodMethod; if (frame.fnOrScript.securityDomain == ifun.securityDomain) { frame = initFrameForNoSuchMethod(cx, frame, indexReg, stack, sDbl, stackTop, op, funThisObj, calleeScope, noSuchMethodShim, ifun); continue StateLoop; } } } cx.lastInterpreterFrame = frame; frame.savedCallOp = op; frame.savedStackTop = stackTop; stack[stackTop] = fun.call(cx, calleeScope, funThisObj, getArgsArray(stack, sDbl, stackTop + 2, indexReg)); continue Loop; } case Token.NEW : { if (instructionCounting) { cx.instructionCount += INVOCATION_COST; } // stack change: function arg0 .. argN -> newResult // indexReg: number of arguments stackTop -= indexReg; Object lhs = stack[stackTop]; if (lhs instanceof InterpretedFunction) { InterpretedFunction f = (InterpretedFunction)lhs; if (frame.fnOrScript.securityDomain == f.securityDomain) { Scriptable newInstance = f.createObject(cx, frame.scope); CallFrame calleeFrame = new CallFrame(); initFrame(cx, frame.scope, newInstance, stack, sDbl, stackTop + 1, indexReg, f, frame, calleeFrame); stack[stackTop] = newInstance; frame.savedStackTop = stackTop; frame.savedCallOp = op; frame = calleeFrame; continue StateLoop; } } if (!(lhs instanceof Function)) { if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); throw ScriptRuntime.notFunctionError(lhs); } Function fun = (Function)lhs; if (fun instanceof IdFunctionObject) { IdFunctionObject ifun = (IdFunctionObject)fun; if (NativeContinuation.isContinuationConstructor(ifun)) { frame.stack[stackTop] = captureContinuation(cx, frame.parentFrame, false); continue Loop; } } Object[] outArgs = getArgsArray(stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = fun.construct(cx, frame.scope, outArgs); continue Loop; } case Token.TYPEOF : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.typeof(lhs); continue Loop; } case Icode_TYPEOFNAME : stack[++stackTop] = ScriptRuntime.typeofName(frame.scope, stringReg); continue Loop; case Token.STRING : stack[++stackTop] = stringReg; continue Loop; case Icode_SHORTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getShort(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_INTNUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Token.NUMBER : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = frame.idata.itsDoubleTable[indexReg]; continue Loop; case Token.NAME : stack[++stackTop] = ScriptRuntime.name(cx, frame.scope, stringReg); continue Loop; case Icode_NAME_INC_DEC : stack[++stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, stringReg, cx, iCode[frame.pc]); ++frame.pc; continue Loop; case Icode_SETCONSTVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETCONSTVAR : stackTop = doSetConstVar(frame, stack, sDbl, stackTop, vars, varDbls, varAttributes, indexReg); continue Loop; case Icode_SETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.SETVAR : stackTop = doSetVar(frame, stack, sDbl, stackTop, vars, varDbls, varAttributes, indexReg); continue Loop; case Icode_GETVAR1: indexReg = iCode[frame.pc++]; // fallthrough case Token.GETVAR : stackTop = doGetVar(frame, stack, sDbl, stackTop, vars, varDbls, indexReg); continue Loop; case Icode_VAR_INC_DEC : { stackTop = doVarIncDec(cx, frame, stack, sDbl, stackTop, vars, varDbls, indexReg); continue Loop; } case Icode_ZERO : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 0; continue Loop; case Icode_ONE : ++stackTop; stack[stackTop] = DBL_MRK; sDbl[stackTop] = 1; continue Loop; case Token.NULL : stack[++stackTop] = null; continue Loop; case Token.THIS : stack[++stackTop] = frame.thisObj; continue Loop; case Token.THISFN : stack[++stackTop] = frame.fnOrScript; continue Loop; case Token.FALSE : stack[++stackTop] = Boolean.FALSE; continue Loop; case Token.TRUE : stack[++stackTop] = Boolean.TRUE; continue Loop; case Icode_UNDEF : stack[++stackTop] = undefined; continue Loop; case Token.ENTERWITH : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterWith(lhs, cx, frame.scope); continue Loop; } case Token.LEAVEWITH : frame.scope = ScriptRuntime.leaveWith(frame.scope); continue Loop; case Token.CATCH_SCOPE : { // stack top: exception object // stringReg: name of exception variable // indexReg: local for exception scope --stackTop; indexReg += frame.localShift; boolean afterFirstScope = (frame.idata.itsICode[frame.pc] != 0); Throwable caughtException = (Throwable)stack[stackTop + 1]; Scriptable lastCatchScope; if (!afterFirstScope) { lastCatchScope = null; } else { lastCatchScope = (Scriptable)stack[indexReg]; } stack[indexReg] = ScriptRuntime.newCatchScope(caughtException, lastCatchScope, stringReg, cx, frame.scope); ++frame.pc; continue Loop; } case Token.ENUM_INIT_KEYS : case Token.ENUM_INIT_VALUES : case Token.ENUM_INIT_ARRAY : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; indexReg += frame.localShift; int enumType = op == Token.ENUM_INIT_KEYS ? ScriptRuntime.ENUMERATE_KEYS : op == Token.ENUM_INIT_VALUES ? ScriptRuntime.ENUMERATE_VALUES : ScriptRuntime.ENUMERATE_ARRAY; stack[indexReg] = ScriptRuntime.enumInit(lhs, cx, enumType); continue Loop; } case Token.ENUM_NEXT : case Token.ENUM_ID : { indexReg += frame.localShift; Object val = stack[indexReg]; ++stackTop; stack[stackTop] = (op == Token.ENUM_NEXT) ? (Object)ScriptRuntime.enumNext(val) : (Object)ScriptRuntime.enumId(val, cx); continue Loop; } case Token.REF_SPECIAL : { //stringReg: name of special property Object obj = stack[stackTop]; if (obj == DBL_MRK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.specialRef(obj, stringReg, cx); continue Loop; } case Token.REF_MEMBER: { //indexReg: flags stackTop = doRefMember(cx, stack, sDbl, stackTop, indexReg); continue Loop; } case Token.REF_NS_MEMBER: { //indexReg: flags stackTop = doRefNsMember(cx, stack, sDbl, stackTop, indexReg); continue Loop; } case Token.REF_NAME: { //indexReg: flags Object name = stack[stackTop]; if (name == DBL_MRK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(name, cx, frame.scope, indexReg); continue Loop; } case Token.REF_NS_NAME: { //indexReg: flags stackTop = doRefNsName(cx, frame, stack, sDbl, stackTop, indexReg); continue Loop; } case Icode_SCOPE_LOAD : indexReg += frame.localShift; frame.scope = (Scriptable)stack[indexReg]; continue Loop; case Icode_SCOPE_SAVE : indexReg += frame.localShift; stack[indexReg] = frame.scope; continue Loop; case Icode_CLOSURE_EXPR : stack[++stackTop] = InterpretedFunction.createFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Icode_CLOSURE_STMT : initFunction(cx, frame.scope, frame.fnOrScript, indexReg); continue Loop; case Token.REGEXP : Object re = frame.idata.itsRegExpLiterals[indexReg]; stack[++stackTop] = ScriptRuntime.wrapRegExp(cx, frame.scope, re); continue Loop; case Icode_LITERAL_NEW : // indexReg: number of values in the literal ++stackTop; stack[stackTop] = new int[indexReg]; ++stackTop; stack[stackTop] = new Object[indexReg]; sDbl[stackTop] = 0; continue Loop; case Icode_LITERAL_SET : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_GETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = -1; sDbl[stackTop] = i + 1; continue Loop; } case Icode_LITERAL_SETTER : { Object value = stack[stackTop]; --stackTop; int i = (int)sDbl[stackTop]; ((Object[])stack[stackTop])[i] = value; ((int[])stack[stackTop - 1])[i] = +1; sDbl[stackTop] = i + 1; continue Loop; } case Token.ARRAYLIT : case Icode_SPARE_ARRAYLIT : case Token.OBJECTLIT : { Object[] data = (Object[])stack[stackTop]; --stackTop; int[] getterSetters = (int[])stack[stackTop]; Object val; if (op == Token.OBJECTLIT) { Object[] ids = (Object[])frame.idata.literalIds[indexReg]; val = ScriptRuntime.newObjectLiteral(ids, data, getterSetters, cx, frame.scope); } else { int[] skipIndexces = null; if (op == Icode_SPARE_ARRAYLIT) { skipIndexces = (int[])frame.idata.literalIds[indexReg]; } val = ScriptRuntime.newArrayLiteral(data, skipIndexces, cx, frame.scope); } stack[stackTop] = val; continue Loop; } case Icode_ENTERDQ : { Object lhs = stack[stackTop]; if (lhs == DBL_MRK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; frame.scope = ScriptRuntime.enterDotQuery(lhs, frame.scope); continue Loop; } case Icode_LEAVEDQ : { boolean valBln = stack_boolean(frame, stackTop); Object x = ScriptRuntime.updateDotQuery(valBln, frame.scope); if (x != null) { stack[stackTop] = x; frame.scope = ScriptRuntime.leaveDotQuery(frame.scope); frame.pc += 2; continue Loop; } // reset stack and PC to code after ENTERDQ --stackTop; break jumplessRun; } case Token.DEFAULTNAMESPACE : { Object value = stack[stackTop]; if (value == DBL_MRK) value = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.setDefaultNamespace(value, cx); continue Loop; } case Token.ESCXMLATTR : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeAttributeValue(value, cx); } continue Loop; } case Token.ESCXMLTEXT : { Object value = stack[stackTop]; if (value != DBL_MRK) { stack[stackTop] = ScriptRuntime.escapeTextValue(value, cx); } continue Loop; } case Icode_DEBUGGER: if (frame.debuggerFrame != null) { frame.debuggerFrame.onDebuggerStatement(cx); } continue Loop; case Icode_LINE : frame.pcSourceLineStart = frame.pc; if (frame.debuggerFrame != null) { int line = getIndex(iCode, frame.pc); frame.debuggerFrame.onLineChange(cx, line); } frame.pc += 2; continue Loop; case Icode_REG_IND_C0: indexReg = 0; continue Loop; case Icode_REG_IND_C1: indexReg = 1; continue Loop; case Icode_REG_IND_C2: indexReg = 2; continue Loop; case Icode_REG_IND_C3: indexReg = 3; continue Loop; case Icode_REG_IND_C4: indexReg = 4; continue Loop; case Icode_REG_IND_C5: indexReg = 5; continue Loop; case Icode_REG_IND1: indexReg = 0xFF & iCode[frame.pc]; ++frame.pc; continue Loop; case Icode_REG_IND2: indexReg = getIndex(iCode, frame.pc); frame.pc += 2; continue Loop; case Icode_REG_IND4: indexReg = getInt(iCode, frame.pc); frame.pc += 4; continue Loop; case Icode_REG_STR_C0: stringReg = strings[0]; continue Loop; case Icode_REG_STR_C1: stringReg = strings[1]; continue Loop; case Icode_REG_STR_C2: stringReg = strings[2]; continue Loop; case Icode_REG_STR_C3: stringReg = strings[3]; continue Loop; case Icode_REG_STR1: stringReg = strings[0xFF & iCode[frame.pc]]; ++frame.pc; continue Loop; case Icode_REG_STR2: stringReg = strings[getIndex(iCode, frame.pc)]; frame.pc += 2; continue Loop; case Icode_REG_STR4: stringReg = strings[getInt(iCode, frame.pc)]; frame.pc += 4; continue Loop; default : dumpICode(frame.idata); throw new RuntimeException("Unknown icode : " + op + " @ pc : " + (frame.pc-1)); } // end of interpreter switch } // end of jumplessRun label block // This should be reachable only for jump implementation // when pc points to encoded target offset if (instructionCounting) { addInstructionCount(cx, frame, 2); } int offset = getShort(iCode, frame.pc); if (offset != 0) { // -1 accounts for pc pointing to jump opcode + 1 frame.pc += offset - 1; } else { frame.pc = frame.idata.longJumps. getExistingInt(frame.pc); } if (instructionCounting) { frame.pcPrevBranch = frame.pc; } continue Loop; } // end of Loop: for exitFrame(cx, frame, null); interpreterResult = frame.result; interpreterResultDbl = frame.resultDbl; if (frame.parentFrame != null) { frame = frame.parentFrame; if (frame.frozen) { frame = frame.cloneFrozen(); } setCallResult( frame, interpreterResult, interpreterResultDbl); interpreterResult = null; // Help GC continue StateLoop; } break StateLoop; } // end of interpreter withoutExceptions: try catch (Throwable ex) { if (throwable != null) { // This is serious bug and it is better to track it ASAP ex.printStackTrace(System.err); throw new IllegalStateException(); } throwable = ex; } // This should be reachable only after above catch or from // finally when it needs to propagate exception or from // explicit throw if (throwable == null) Kit.codeBug(); // Exception type final int EX_CATCH_STATE = 2; // Can execute JS catch final int EX_FINALLY_STATE = 1; // Can execute JS finally final int EX_NO_JS_STATE = 0; // Terminate JS execution int exState; ContinuationJump cjump = null; if (generatorState != null && generatorState.operation == NativeGenerator.GENERATOR_CLOSE && throwable == generatorState.value) { exState = EX_FINALLY_STATE; } else if (throwable instanceof JavaScriptException) { exState = EX_CATCH_STATE; } else if (throwable instanceof EcmaError) { // an offical ECMA error object, exState = EX_CATCH_STATE; } else if (throwable instanceof EvaluatorException) { exState = EX_CATCH_STATE; } else if (throwable instanceof ContinuationPending) { exState = EX_NO_JS_STATE; } else if (throwable instanceof RuntimeException) { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_FINALLY_STATE; } else if (throwable instanceof Error) { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_NO_JS_STATE; } else if (throwable instanceof ContinuationJump) { // It must be ContinuationJump exState = EX_FINALLY_STATE; cjump = (ContinuationJump)throwable; } else { exState = cx.hasFeature(Context.FEATURE_ENHANCED_JAVA_ACCESS) ? EX_CATCH_STATE : EX_FINALLY_STATE; } if (instructionCounting) { try { addInstructionCount(cx, frame, EXCEPTION_COST); } catch (RuntimeException ex) { throwable = ex; exState = EX_FINALLY_STATE; } catch (Error ex) { // Error from instruction counting // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } if (frame.debuggerFrame != null && throwable instanceof RuntimeException) { // Call debugger only for RuntimeException RuntimeException rex = (RuntimeException)throwable; try { frame.debuggerFrame.onExceptionThrown(cx, rex); } catch (Throwable ex) { // Any exception from debugger // => unconditionally terminate JS throwable = ex; cjump = null; exState = EX_NO_JS_STATE; } } for (;;) { if (exState != EX_NO_JS_STATE) { boolean onlyFinally = (exState != EX_CATCH_STATE); indexReg = getExceptionHandler(frame, onlyFinally); if (indexReg >= 0) { // We caught an exception, restart the loop // with exception pending the processing at the loop // start continue StateLoop; } } // No allowed exception handlers in this frame, unwind // to parent and try to look there exitFrame(cx, frame, throwable); frame = frame.parentFrame; if (frame == null) { break; } if (cjump != null && cjump.branchFrame == frame) { // Continuation branch point was hit, // restart the state loop to reenter continuation indexReg = -1; continue StateLoop; } } // No more frames, rethrow the exception or deal with continuation if (cjump != null) { if (cjump.branchFrame != null) { // The above loop should locate the top frame Kit.codeBug(); } if (cjump.capturedFrame != null) { // Restarting detached continuation indexReg = -1; continue StateLoop; } // Return continuation result to the caller interpreterResult = cjump.result; interpreterResultDbl = cjump.resultDbl; throwable = null; } break StateLoop; } // end of StateLoop: for(;;) // Do cleanups/restorations before the final return or throw if (cx.previousInterpreterInvocations != null && cx.previousInterpreterInvocations.size() != 0) { cx.lastInterpreterFrame = cx.previousInterpreterInvocations.pop(); } else { // It was the last interpreter frame on the stack cx.lastInterpreterFrame = null; // Force GC of the value cx.previousInterpreterInvocations cx.previousInterpreterInvocations = null; } if (throwable != null) { if (throwable instanceof RuntimeException) { throw (RuntimeException)throwable; } else { // Must be instance of Error or code bug throw (Error)throwable; } } return (interpreterResult != DBL_MRK) ? interpreterResult : ScriptRuntime.wrapNumber(interpreterResultDbl); } private static int doInOrInstanceof(Context cx, int op, Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop]; if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); boolean valBln; if (op == Token.IN) { valBln = ScriptRuntime.in(lhs, rhs, cx); } else { valBln = ScriptRuntime.instanceOf(lhs, rhs, cx); } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); return stackTop; } private static int doCompare(CallFrame frame, int op, Object[] stack, double[] sDbl, int stackTop) { --stackTop; Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; boolean valBln; object_compare: { number_compare: { double rDbl, lDbl; if (rhs == DOUBLE_MARK) { rDbl = sDbl[stackTop + 1]; lDbl = stack_double(frame, stackTop); } else if (lhs == DOUBLE_MARK) { rDbl = ScriptRuntime.toNumber(rhs); lDbl = sDbl[stackTop]; } else { break number_compare; } switch (op) { case Token.GE: valBln = (lDbl >= rDbl); break object_compare; case Token.LE: valBln = (lDbl <= rDbl); break object_compare; case Token.GT: valBln = (lDbl > rDbl); break object_compare; case Token.LT: valBln = (lDbl < rDbl); break object_compare; default: throw Kit.codeBug(); } } switch (op) { case Token.GE: valBln = ScriptRuntime.cmp_LE(rhs, lhs); break; case Token.LE: valBln = ScriptRuntime.cmp_LE(lhs, rhs); break; case Token.GT: valBln = ScriptRuntime.cmp_LT(rhs, lhs); break; case Token.LT: valBln = ScriptRuntime.cmp_LT(lhs, rhs); break; default: throw Kit.codeBug(); } } stack[stackTop] = ScriptRuntime.wrapBoolean(valBln); return stackTop; } private static int doBitOp(CallFrame frame, int op, Object[] stack, double[] sDbl, int stackTop) { int lIntValue = stack_int32(frame, stackTop - 1); int rIntValue = stack_int32(frame, stackTop); stack[--stackTop] = DOUBLE_MARK; switch (op) { case Token.BITAND: lIntValue &= rIntValue; break; case Token.BITOR: lIntValue |= rIntValue; break; case Token.BITXOR: lIntValue ^= rIntValue; break; case Token.LSH: lIntValue <<= rIntValue; break; case Token.RSH: lIntValue >>= rIntValue; break; } sDbl[stackTop] = lIntValue; return stackTop; } private static int doDelName(Context cx, int op, Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop]; if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.delete(lhs, rhs, cx, op == Icode_DELNAME); return stackTop; } private static int doGetElem(Context cx, CallFrame frame, Object[] stack, double[] sDbl, int stackTop) { --stackTop; Object lhs = stack[stackTop]; if (lhs == DOUBLE_MARK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DOUBLE_MARK) { value = ScriptRuntime.getObjectElem(lhs, id, cx, frame.scope); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.getObjectIndex(lhs, d, cx); } stack[stackTop] = value; return stackTop; } private static int doSetElem(Context cx, Object[] stack, double[] sDbl, int stackTop) { stackTop -= 2; Object rhs = stack[stackTop + 2]; if (rhs == DOUBLE_MARK) { rhs = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); } Object lhs = stack[stackTop]; if (lhs == DOUBLE_MARK) { lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); } Object value; Object id = stack[stackTop + 1]; if (id != DOUBLE_MARK) { value = ScriptRuntime.setObjectElem(lhs, id, rhs, cx); } else { double d = sDbl[stackTop + 1]; value = ScriptRuntime.setObjectIndex(lhs, d, rhs, cx); } stack[stackTop] = value; return stackTop; } private static int doElemIncDec(Context cx, CallFrame frame, byte[] iCode, Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop]; if (rhs == DOUBLE_MARK) rhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object lhs = stack[stackTop]; if (lhs == DOUBLE_MARK) lhs = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.elemIncrDecr(lhs, rhs, cx, iCode[frame.pc]); ++frame.pc; return stackTop; } private static int doCallSpecial(Context cx, CallFrame frame, Object[] stack, double[] sDbl, int stackTop, byte[] iCode, int indexReg) { int callType = iCode[frame.pc] & 0xFF; boolean isNew = (iCode[frame.pc + 1] != 0); int sourceLine = getIndex(iCode, frame.pc + 2); // indexReg: number of arguments if (isNew) { // stack change: function arg0 .. argN -> newResult stackTop -= indexReg; Object function = stack[stackTop]; if (function == DOUBLE_MARK) function = ScriptRuntime.wrapNumber(sDbl[stackTop]); Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 1, indexReg); stack[stackTop] = ScriptRuntime.newSpecial( cx, function, outArgs, frame.scope, callType); } else { // stack change: function thisObj arg0 .. argN -> result stackTop -= 1 + indexReg; // Call code generation ensure that stack here // is ... Callable Scriptable Scriptable functionThis = (Scriptable)stack[stackTop + 1]; Callable function = (Callable)stack[stackTop]; Object[] outArgs = getArgsArray( stack, sDbl, stackTop + 2, indexReg); stack[stackTop] = ScriptRuntime.callSpecial( cx, function, functionThis, outArgs, frame.scope, frame.thisObj, callType, frame.idata.itsSourceFile, sourceLine); } frame.pc += 4; return stackTop; } private static int doSetConstVar(CallFrame frame, Object[] stack, double[] sDbl, int stackTop, Object[] vars, double[] varDbls, int[] varAttributes, int indexReg) { if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { throw Context.reportRuntimeError1("msg.var.redecl", frame.idata.argNames[indexReg]); } if ((varAttributes[indexReg] & ScriptableObject.UNINITIALIZED_CONST) != 0) { vars[indexReg] = stack[stackTop]; varAttributes[indexReg] &= ~ScriptableObject.UNINITIALIZED_CONST; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DOUBLE_MARK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); String stringReg = frame.idata.argNames[indexReg]; if (frame.scope instanceof ConstProperties) { ConstProperties cp = (ConstProperties)frame.scope; cp.putConst(stringReg, frame.scope, val); } else throw Kit.codeBug(); } return stackTop; } private static int doSetVar(CallFrame frame, Object[] stack, double[] sDbl, int stackTop, Object[] vars, double[] varDbls, int[] varAttributes, int indexReg) { if (!frame.useActivation) { if ((varAttributes[indexReg] & ScriptableObject.READONLY) == 0) { vars[indexReg] = stack[stackTop]; varDbls[indexReg] = sDbl[stackTop]; } } else { Object val = stack[stackTop]; if (val == DOUBLE_MARK) val = ScriptRuntime.wrapNumber(sDbl[stackTop]); String stringReg = frame.idata.argNames[indexReg]; frame.scope.put(stringReg, frame.scope, val); } return stackTop; } private static int doGetVar(CallFrame frame, Object[] stack, double[] sDbl, int stackTop, Object[] vars, double[] varDbls, int indexReg) { ++stackTop; if (!frame.useActivation) { stack[stackTop] = vars[indexReg]; sDbl[stackTop] = varDbls[indexReg]; } else { String stringReg = frame.idata.argNames[indexReg]; stack[stackTop] = frame.scope.get(stringReg, frame.scope); } return stackTop; } private static int doVarIncDec(Context cx, CallFrame frame, Object[] stack, double[] sDbl, int stackTop, Object[] vars, double[] varDbls, int indexReg) { // indexReg : varindex ++stackTop; int incrDecrMask = frame.idata.itsICode[frame.pc]; if (!frame.useActivation) { stack[stackTop] = DOUBLE_MARK; Object varValue = vars[indexReg]; double d; if (varValue == DOUBLE_MARK) { d = varDbls[indexReg]; } else { d = ScriptRuntime.toNumber(varValue); vars[indexReg] = DOUBLE_MARK; } double d2 = ((incrDecrMask & Node.DECR_FLAG) == 0) ? d + 1.0 : d - 1.0; varDbls[indexReg] = d2; sDbl[stackTop] = ((incrDecrMask & Node.POST_FLAG) == 0) ? d2 : d; } else { String varName = frame.idata.argNames[indexReg]; stack[stackTop] = ScriptRuntime.nameIncrDecr(frame.scope, varName, cx, incrDecrMask); } ++frame.pc; return stackTop; } private static int doRefMember(Context cx, Object[] stack, double[] sDbl, int stackTop, int flags) { Object elem = stack[stackTop]; if (elem == DOUBLE_MARK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, elem, cx, flags); return stackTop; } private static int doRefNsMember(Context cx, Object[] stack, double[] sDbl, int stackTop, int flags) { Object elem = stack[stackTop]; if (elem == DOUBLE_MARK) elem = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DOUBLE_MARK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object obj = stack[stackTop]; if (obj == DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.memberRef(obj, ns, elem, cx, flags); return stackTop; } private static int doRefNsName(Context cx, CallFrame frame, Object[] stack, double[] sDbl, int stackTop, int flags) { Object name = stack[stackTop]; if (name == DOUBLE_MARK) name = ScriptRuntime.wrapNumber(sDbl[stackTop]); --stackTop; Object ns = stack[stackTop]; if (ns == DOUBLE_MARK) ns = ScriptRuntime.wrapNumber(sDbl[stackTop]); stack[stackTop] = ScriptRuntime.nameRef(ns, name, cx, frame.scope, flags); return stackTop; } /** * Call __noSuchMethod__. */ private static CallFrame initFrameForNoSuchMethod(Context cx, CallFrame frame, int indexReg, Object[] stack, double[] sDbl, int stackTop, int op, Scriptable funThisObj, Scriptable calleeScope, NoSuchMethodShim noSuchMethodShim, InterpretedFunction ifun) { // create an args array from the stack Object[] argsArray = null; // exactly like getArgsArray except that the first argument // is the method name from the shim int shift = stackTop + 2; Object[] elements = new Object[indexReg]; for (int i=0; i < indexReg; ++i, ++shift) { Object val = stack[shift]; if (val == DOUBLE_MARK) { val = ScriptRuntime.wrapNumber(sDbl[shift]); } elements[i] = val; } argsArray = new Object[2]; argsArray[0] = noSuchMethodShim.methodName; argsArray[1] = cx.newArray(calleeScope, elements); // exactly the same as if it's a regular InterpretedFunction CallFrame callParentFrame = frame; CallFrame calleeFrame = new CallFrame(); if (op == Icode_TAIL_CALL) { callParentFrame = frame.parentFrame; exitFrame(cx, frame, null); } // init the frame with the underlying method with the // adjusted args array and shim's function initFrame(cx, calleeScope, funThisObj, argsArray, null, 0, 2, ifun, callParentFrame, calleeFrame); if (op != Icode_TAIL_CALL) { frame.savedStackTop = stackTop; frame.savedCallOp = op; } return calleeFrame; } private static boolean doEquals(Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; if (rhs == DOUBLE_MARK) { if (lhs == DOUBLE_MARK) { return (sDbl[stackTop] == sDbl[stackTop + 1]); } else { return ScriptRuntime.eqNumber(sDbl[stackTop + 1], lhs); } } else { if (lhs == DOUBLE_MARK) { return ScriptRuntime.eqNumber(sDbl[stackTop], rhs); } else { return ScriptRuntime.eq(lhs, rhs); } } } private static boolean doShallowEquals(Object[] stack, double[] sDbl, int stackTop) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; final Object DBL_MRK = DOUBLE_MARK; double rdbl, ldbl; if (rhs == DBL_MRK) { rdbl = sDbl[stackTop + 1]; if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; } else if (lhs instanceof Number) { ldbl = ((Number)lhs).doubleValue(); } else { return false; } } else if (lhs == DBL_MRK) { ldbl = sDbl[stackTop]; if (rhs instanceof Number) { rdbl = ((Number)rhs).doubleValue(); } else { return false; } } else { return ScriptRuntime.shallowEq(lhs, rhs); } return (ldbl == rdbl); } private static CallFrame processThrowable(Context cx, Object throwable, CallFrame frame, int indexReg, boolean instructionCounting) { // Recovering from exception, indexReg contains // the index of handler if (indexReg >= 0) { // Normal exception handler, transfer // control appropriately if (frame.frozen) { // XXX Deal with exceptios!!! frame = frame.cloneFrozen(); } int[] table = frame.idata.itsExceptionTable; frame.pc = table[indexReg + EXCEPTION_HANDLER_SLOT]; if (instructionCounting) { frame.pcPrevBranch = frame.pc; } frame.savedStackTop = frame.emptyStackTop; int scopeLocal = frame.localShift + table[indexReg + EXCEPTION_SCOPE_SLOT]; int exLocal = frame.localShift + table[indexReg + EXCEPTION_LOCAL_SLOT]; frame.scope = (Scriptable)frame.stack[scopeLocal]; frame.stack[exLocal] = throwable; throwable = null; } else { // Continuation restoration ContinuationJump cjump = (ContinuationJump)throwable; // Clear throwable to indicate that exceptions are OK throwable = null; if (cjump.branchFrame != frame) Kit.codeBug(); // Check that we have at least one frozen frame // in the case of detached continuation restoration: // unwind code ensure that if (cjump.capturedFrame == null) Kit.codeBug(); // Need to rewind branchFrame, capturedFrame // and all frames in between int rewindCount = cjump.capturedFrame.frameIndex + 1; if (cjump.branchFrame != null) { rewindCount -= cjump.branchFrame.frameIndex; } int enterCount = 0; CallFrame[] enterFrames = null; CallFrame x = cjump.capturedFrame; for (int i = 0; i != rewindCount; ++i) { if (!x.frozen) Kit.codeBug(); if (isFrameEnterExitRequired(x)) { if (enterFrames == null) { // Allocate enough space to store the rest // of rewind frames in case all of them // would require to enter enterFrames = new CallFrame[rewindCount - i]; } enterFrames[enterCount] = x; ++enterCount; } x = x.parentFrame; } while (enterCount != 0) { // execute enter: walk enterFrames in the reverse // order since they were stored starting from // the capturedFrame, not branchFrame --enterCount; x = enterFrames[enterCount]; enterFrame(cx, x, ScriptRuntime.emptyArgs, true); } // Continuation jump is almost done: capturedFrame // points to the call to the function that captured // continuation, so clone capturedFrame and // emulate return that function with the suplied result frame = cjump.capturedFrame.cloneFrozen(); setCallResult(frame, cjump.result, cjump.resultDbl); // restart the execution } frame.throwable = throwable; return frame; } private static Object freezeGenerator(Context cx, CallFrame frame, int stackTop, GeneratorState generatorState) { if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { // Error: no yields when generator is closing throw ScriptRuntime.typeError0("msg.yield.closing"); } // return to our caller (which should be a method of NativeGenerator) frame.frozen = true; frame.result = frame.stack[stackTop]; frame.resultDbl = frame.sDbl[stackTop]; frame.savedStackTop = stackTop; frame.pc--; // we want to come back here when we resume ScriptRuntime.exitActivationFunction(cx); return (frame.result != DOUBLE_MARK) ? frame.result : ScriptRuntime.wrapNumber(frame.resultDbl); } private static Object thawGenerator(CallFrame frame, int stackTop, GeneratorState generatorState, int op) { // we are resuming execution frame.frozen = false; int sourceLine = getIndex(frame.idata.itsICode, frame.pc); frame.pc += 2; // skip line number data if (generatorState.operation == NativeGenerator.GENERATOR_THROW) { // processing a call to <generator>.throw(exception): must // act as if exception was thrown from resumption point return new JavaScriptException(generatorState.value, frame.idata.itsSourceFile, sourceLine); } if (generatorState.operation == NativeGenerator.GENERATOR_CLOSE) { return generatorState.value; } if (generatorState.operation != NativeGenerator.GENERATOR_SEND) throw Kit.codeBug(); if (op == Token.YIELD) frame.stack[stackTop] = generatorState.value; return Scriptable.NOT_FOUND; } private static CallFrame initFrameForApplyOrCall(Context cx, CallFrame frame, int indexReg, Object[] stack, double[] sDbl, int stackTop, int op, Scriptable calleeScope, IdFunctionObject ifun, InterpretedFunction iApplyCallable) { Scriptable applyThis; if (indexReg != 0) { Object obj = stack[stackTop + 2]; if (obj == DOUBLE_MARK) obj = ScriptRuntime.wrapNumber(sDbl[stackTop + 2]); applyThis = ScriptRuntime.toObjectOrNull(cx, obj); } else { applyThis = null; } if (applyThis == null) { // This covers the case of args[0] == (null|undefined) as well. applyThis = ScriptRuntime.getTopCallScope(cx); } if(op == Icode_TAIL_CALL) { exitFrame(cx, frame, null); frame = frame.parentFrame; } else { frame.savedStackTop = stackTop; frame.savedCallOp = op; } CallFrame calleeFrame = new CallFrame(); if(BaseFunction.isApply(ifun)) { Object[] callArgs = indexReg < 2 ? ScriptRuntime.emptyArgs : ScriptRuntime.getApplyArguments(cx, stack[stackTop + 3]); initFrame(cx, calleeScope, applyThis, callArgs, null, 0, callArgs.length, iApplyCallable, frame, calleeFrame); } else { // Shift args left for(int i = 1; i < indexReg; ++i) { stack[stackTop + 1 + i] = stack[stackTop + 2 + i]; sDbl[stackTop + 1 + i] = sDbl[stackTop + 2 + i]; } int argCount = indexReg < 2 ? 0 : indexReg - 1; initFrame(cx, calleeScope, applyThis, stack, sDbl, stackTop + 2, argCount, iApplyCallable, frame, calleeFrame); } frame = calleeFrame; return frame; } private static void initFrame(Context cx, Scriptable callerScope, Scriptable thisObj, Object[] args, double[] argsDbl, int argShift, int argCount, InterpretedFunction fnOrScript, CallFrame parentFrame, CallFrame frame) { InterpreterData idata = fnOrScript.idata; boolean useActivation = idata.itsNeedsActivation; DebugFrame debuggerFrame = null; if (cx.debugger != null) { debuggerFrame = cx.debugger.getFrame(cx, idata); if (debuggerFrame != null) { useActivation = true; } } if (useActivation) { // Copy args to new array to pass to enterActivationFunction // or debuggerFrame.onEnter if (argsDbl != null) { args = getArgsArray(args, argsDbl, argShift, argCount); } argShift = 0; argsDbl = null; } Scriptable scope; if (idata.itsFunctionType != 0) { scope = fnOrScript.getParentScope(); if (useActivation) { scope = ScriptRuntime.createFunctionActivation( fnOrScript, scope, args); } } else { scope = callerScope; ScriptRuntime.initScript(fnOrScript, thisObj, cx, scope, fnOrScript.idata.evalScriptFlag); } if (idata.itsNestedFunctions != null) { if (idata.itsFunctionType != 0 && !idata.itsNeedsActivation) Kit.codeBug(); for (int i = 0; i < idata.itsNestedFunctions.length; i++) { InterpreterData fdata = idata.itsNestedFunctions[i]; if (fdata.itsFunctionType == FunctionNode.FUNCTION_STATEMENT) { initFunction(cx, scope, fnOrScript, i); } } } // Initialize args, vars, locals and stack int emptyStackTop = idata.itsMaxVars + idata.itsMaxLocals - 1; int maxFrameArray = idata.itsMaxFrameArray; if (maxFrameArray != emptyStackTop + idata.itsMaxStack + 1) Kit.codeBug(); Object[] stack; int[] stackAttributes; double[] sDbl; boolean stackReuse; if (frame.stack != null && maxFrameArray <= frame.stack.length) { // Reuse stacks from old frame stackReuse = true; stack = frame.stack; stackAttributes = frame.stackAttributes; sDbl = frame.sDbl; } else { stackReuse = false; stack = new Object[maxFrameArray]; stackAttributes = new int[maxFrameArray]; sDbl = new double[maxFrameArray]; } int varCount = idata.getParamAndVarCount(); for (int i = 0; i < varCount; i++) { if (idata.getParamOrVarConst(i)) stackAttributes[i] = ScriptableObject.CONST; } int definedArgs = idata.argCount; if (definedArgs > argCount) { definedArgs = argCount; } // Fill the frame structure frame.parentFrame = parentFrame; frame.frameIndex = (parentFrame == null) ? 0 : parentFrame.frameIndex + 1; if(frame.frameIndex > cx.getMaximumInterpreterStackDepth()) { throw Context.reportRuntimeError("Exceeded maximum stack depth"); } frame.frozen = false; frame.fnOrScript = fnOrScript; frame.idata = idata; frame.stack = stack; frame.stackAttributes = stackAttributes; frame.sDbl = sDbl; frame.varSource = frame; frame.localShift = idata.itsMaxVars; frame.emptyStackTop = emptyStackTop; frame.debuggerFrame = debuggerFrame; frame.useActivation = useActivation; frame.thisObj = thisObj; // Initialize initial values of variables that change during // interpretation. frame.result = Undefined.instance; frame.pc = 0; frame.pcPrevBranch = 0; frame.pcSourceLineStart = idata.firstLinePC; frame.scope = scope; frame.savedStackTop = emptyStackTop; frame.savedCallOp = 0; System.arraycopy(args, argShift, stack, 0, definedArgs); if (argsDbl != null) { System.arraycopy(argsDbl, argShift, sDbl, 0, definedArgs); } for (int i = definedArgs; i != idata.itsMaxVars; ++i) { stack[i] = Undefined.instance; } if (stackReuse) { // Clean the stack part and space beyond stack if any // of the old array to allow to GC objects there for (int i = emptyStackTop + 1; i != stack.length; ++i) { stack[i] = null; } } enterFrame(cx, frame, args, false); } private static boolean isFrameEnterExitRequired(CallFrame frame) { return frame.debuggerFrame != null || frame.idata.itsNeedsActivation; } private static void enterFrame(Context cx, CallFrame frame, Object[] args, boolean continuationRestart) { boolean usesActivation = frame.idata.itsNeedsActivation; boolean isDebugged = frame.debuggerFrame != null; if(usesActivation || isDebugged) { Scriptable scope = frame.scope; if(scope == null) { Kit.codeBug(); } else if (continuationRestart) { // Walk the parent chain of frame.scope until a NativeCall is // found. Normally, frame.scope is a NativeCall when called // from initFrame() for a debugged or activatable function. // However, when called from interpretLoop() as part of // restarting a continuation, it can also be a NativeWith if // the continuation was captured within a "with" or "catch" // block ("catch" implicitly uses NativeWith to create a scope // to expose the exception variable). for(;;) { if(scope instanceof NativeWith) { scope = scope.getParentScope(); if (scope == null || (frame.parentFrame != null && frame.parentFrame.scope == scope)) { // If we get here, we didn't find a NativeCall in // the call chain before reaching parent frame's // scope. This should not be possible. Kit.codeBug(); break; // Never reached, but keeps the static analyzer // happy about "scope" not being null 5 lines above. } } else { break; } } } if (isDebugged) { frame.debuggerFrame.onEnter(cx, scope, frame.thisObj, args); } // Enter activation only when itsNeedsActivation true, // since debugger should not interfere with activation // chaining if (usesActivation) { ScriptRuntime.enterActivationFunction(cx, scope); } } } private static void exitFrame(Context cx, CallFrame frame, Object throwable) { if (frame.idata.itsNeedsActivation) { ScriptRuntime.exitActivationFunction(cx); } if (frame.debuggerFrame != null) { try { if (throwable instanceof Throwable) { frame.debuggerFrame.onExit(cx, true, throwable); } else { Object result; ContinuationJump cjump = (ContinuationJump)throwable; if (cjump == null) { result = frame.result; } else { result = cjump.result; } if (result == DOUBLE_MARK) { double resultDbl; if (cjump == null) { resultDbl = frame.resultDbl; } else { resultDbl = cjump.resultDbl; } result = ScriptRuntime.wrapNumber(resultDbl); } frame.debuggerFrame.onExit(cx, false, result); } } catch (Throwable ex) { System.err.println( "RHINO USAGE WARNING: onExit terminated with exception"); ex.printStackTrace(System.err); } } } private static void setCallResult(CallFrame frame, Object callResult, double callResultDbl) { if (frame.savedCallOp == Token.CALL) { frame.stack[frame.savedStackTop] = callResult; frame.sDbl[frame.savedStackTop] = callResultDbl; } else if (frame.savedCallOp == Token.NEW) { // If construct returns scriptable, // then it replaces on stack top saved original instance // of the object. if (callResult instanceof Scriptable) { frame.stack[frame.savedStackTop] = callResult; } } else { Kit.codeBug(); } frame.savedCallOp = 0; } public static NativeContinuation captureContinuation(Context cx) { if (cx.lastInterpreterFrame == null || !(cx.lastInterpreterFrame instanceof CallFrame)) { throw new IllegalStateException("Interpreter frames not found"); } return captureContinuation(cx, (CallFrame)cx.lastInterpreterFrame, true); } private static NativeContinuation captureContinuation(Context cx, CallFrame frame, boolean requireContinuationsTopFrame) { NativeContinuation c = new NativeContinuation(); ScriptRuntime.setObjectProtoAndParent( c, ScriptRuntime.getTopCallScope(cx)); // Make sure that all frames are frozen CallFrame x = frame; CallFrame outermost = frame; while (x != null && !x.frozen) { x.frozen = true; // Allow to GC unused stack space for (int i = x.savedStackTop + 1; i != x.stack.length; ++i) { // Allow to GC unused stack space x.stack[i] = null; x.stackAttributes[i] = ScriptableObject.EMPTY; } if (x.savedCallOp == Token.CALL) { // the call will always overwrite the stack top with the result x.stack[x.savedStackTop] = null; } else { if (x.savedCallOp != Token.NEW) Kit.codeBug(); // the new operator uses stack top to store the constructed // object so it shall not be cleared: see comments in // setCallResult } outermost = x; x = x.parentFrame; } if (requireContinuationsTopFrame) { while (outermost.parentFrame != null) outermost = outermost.parentFrame; if (!outermost.isContinuationsTopFrame) { throw new IllegalStateException("Cannot capture continuation " + "from JavaScript code not called directly by " + "executeScriptWithContinuations or " + "callFunctionWithContinuations"); } } c.initImplementation(frame); return c; } private static int stack_int32(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == UniqueTag.DOUBLE_MARK) { return ScriptRuntime.toInt32(frame.sDbl[i]); } else { return ScriptRuntime.toInt32(x); } } private static double stack_double(CallFrame frame, int i) { Object x = frame.stack[i]; if (x != UniqueTag.DOUBLE_MARK) { return ScriptRuntime.toNumber(x); } else { return frame.sDbl[i]; } } private static boolean stack_boolean(CallFrame frame, int i) { Object x = frame.stack[i]; if (x == Boolean.TRUE) { return true; } else if (x == Boolean.FALSE) { return false; } else if (x == UniqueTag.DOUBLE_MARK) { double d = frame.sDbl[i]; return d == d && d != 0.0; } else if (x == null || x == Undefined.instance) { return false; } else if (x instanceof Number) { double d = ((Number)x).doubleValue(); return (d == d && d != 0.0); } else if (x instanceof Boolean) { return ((Boolean)x).booleanValue(); } else { return ScriptRuntime.toBoolean(x); } } private static void doAdd(Object[] stack, double[] sDbl, int stackTop, Context cx) { Object rhs = stack[stackTop + 1]; Object lhs = stack[stackTop]; double d; boolean leftRightOrder; if (rhs == DOUBLE_MARK) { d = sDbl[stackTop + 1]; if (lhs == DOUBLE_MARK) { sDbl[stackTop] += d; return; } leftRightOrder = true; // fallthrough to object + number code } else if (lhs == DOUBLE_MARK) { d = sDbl[stackTop]; lhs = rhs; leftRightOrder = false; // fallthrough to object + number code } else { if (lhs instanceof Scriptable || rhs instanceof Scriptable) { stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof CharSequence || rhs instanceof CharSequence) { CharSequence lstr = ScriptRuntime.toCharSequence(lhs); CharSequence rstr = ScriptRuntime.toCharSequence(rhs); stack[stackTop] = new ConsString(lstr, rstr); } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); double rDbl = (rhs instanceof Number) ? ((Number)rhs).doubleValue() : ScriptRuntime.toNumber(rhs); stack[stackTop] = DOUBLE_MARK; sDbl[stackTop] = lDbl + rDbl; } return; } // handle object(lhs) + number(d) code if (lhs instanceof Scriptable) { rhs = ScriptRuntime.wrapNumber(d); if (!leftRightOrder) { Object tmp = lhs; lhs = rhs; rhs = tmp; } stack[stackTop] = ScriptRuntime.add(lhs, rhs, cx); } else if (lhs instanceof CharSequence) { CharSequence lstr = (CharSequence)lhs; CharSequence rstr = ScriptRuntime.toCharSequence(d); if (leftRightOrder) { stack[stackTop] = new ConsString(lstr, rstr); } else { stack[stackTop] = new ConsString(rstr, lstr); } } else { double lDbl = (lhs instanceof Number) ? ((Number)lhs).doubleValue() : ScriptRuntime.toNumber(lhs); stack[stackTop] = DOUBLE_MARK; sDbl[stackTop] = lDbl + d; } } private static int doArithmetic(CallFrame frame, int op, Object[] stack, double[] sDbl, int stackTop) { double rDbl = stack_double(frame, stackTop); --stackTop; double lDbl = stack_double(frame, stackTop); stack[stackTop] = DOUBLE_MARK; switch (op) { case Token.SUB: lDbl -= rDbl; break; case Token.MUL: lDbl *= rDbl; break; case Token.DIV: lDbl /= rDbl; break; case Token.MOD: lDbl %= rDbl; break; } sDbl[stackTop] = lDbl; return stackTop; } private static Object[] getArgsArray(Object[] stack, double[] sDbl, int shift, int count) { if (count == 0) { return ScriptRuntime.emptyArgs; } Object[] args = new Object[count]; for (int i = 0; i != count; ++i, ++shift) { Object val = stack[shift]; if (val == UniqueTag.DOUBLE_MARK) { val = ScriptRuntime.wrapNumber(sDbl[shift]); } args[i] = val; } return args; } private static void addInstructionCount(Context cx, CallFrame frame, int extra) { cx.instructionCount += frame.pc - frame.pcPrevBranch + extra; if (cx.instructionCount > cx.instructionThreshold) { cx.observeInstructionCount(cx.instructionCount); cx.instructionCount = 0; } } }
mpl-2.0
nxnfufunezn/servo
components/script/dom/htmlinputelement.rs
44062
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use caseless::compatibility_caseless_match_str; use dom::activation::Activatable; use dom::attr::{Attr, AttrValue}; use dom::bindings::cell::DOMRefCell; use dom::bindings::codegen::Bindings::AttrBinding::AttrMethods; use dom::bindings::codegen::Bindings::EventBinding::EventMethods; use dom::bindings::codegen::Bindings::HTMLInputElementBinding; use dom::bindings::codegen::Bindings::HTMLInputElementBinding::HTMLInputElementMethods; use dom::bindings::codegen::Bindings::KeyboardEventBinding::KeyboardEventMethods; use dom::bindings::error::{Error, ErrorResult}; use dom::bindings::global::GlobalRef; use dom::bindings::inheritance::Castable; use dom::bindings::js::{JS, LayoutJS, Root, RootedReference}; use dom::bindings::refcounted::Trusted; use dom::document::Document; use dom::element::{AttributeMutation, Element, RawLayoutElementHelpers, LayoutElementHelpers}; use dom::event::{Event, EventBubbles, EventCancelable}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::htmlfieldsetelement::HTMLFieldSetElement; use dom::htmlformelement::{FormControl, FormDatum, FormSubmitter, HTMLFormElement}; use dom::htmlformelement::{ResetFrom, SubmittedFrom}; use dom::keyboardevent::KeyboardEvent; use dom::node::{Node, NodeDamage, UnbindContext}; use dom::node::{document_from_node, window_from_node}; use dom::nodelist::NodeList; use dom::virtualmethods::VirtualMethods; use msg::constellation_msg::ConstellationChan; use script_thread::ScriptThreadEventCategory::InputEvent; use script_thread::{CommonScriptMsg, Runnable}; use script_traits::ScriptMsg as ConstellationMsg; use std::borrow::ToOwned; use std::cell::Cell; use string_cache::Atom; use style::element_state::*; use textinput::KeyReaction::{DispatchInput, Nothing, RedrawSelection, TriggerDefaultAction}; use textinput::Lines::Single; use textinput::TextInput; use util::str::{DOMString, search_index}; const DEFAULT_SUBMIT_VALUE: &'static str = "Submit"; const DEFAULT_RESET_VALUE: &'static str = "Reset"; #[derive(JSTraceable, PartialEq, Copy, Clone)] #[allow(dead_code)] #[derive(HeapSizeOf)] enum InputType { InputSubmit, InputReset, InputButton, InputText, InputFile, InputImage, InputCheckbox, InputRadio, InputPassword } #[derive(Debug, PartialEq)] enum ValueMode { Value, Default, DefaultOn, Filename, } #[dom_struct] pub struct HTMLInputElement { htmlelement: HTMLElement, input_type: Cell<InputType>, checked_changed: Cell<bool>, placeholder: DOMRefCell<DOMString>, value_changed: Cell<bool>, size: Cell<u32>, maxlength: Cell<i32>, #[ignore_heap_size_of = "#7193"] textinput: DOMRefCell<TextInput<ConstellationChan<ConstellationMsg>>>, activation_state: DOMRefCell<InputActivationState>, // https://html.spec.whatwg.org/multipage/#concept-input-value-dirty-flag value_dirty: Cell<bool>, // TODO: selected files for file input } #[derive(JSTraceable)] #[must_root] #[derive(HeapSizeOf)] struct InputActivationState { indeterminate: bool, checked: bool, checked_changed: bool, checked_radio: Option<JS<HTMLInputElement>>, // In case mutability changed was_mutable: bool, // In case the type changed old_type: InputType, } impl InputActivationState { fn new() -> InputActivationState { InputActivationState { indeterminate: false, checked: false, checked_changed: false, checked_radio: None, was_mutable: false, old_type: InputType::InputText } } } static DEFAULT_INPUT_SIZE: u32 = 20; static DEFAULT_MAX_LENGTH: i32 = -1; impl HTMLInputElement { fn new_inherited(localName: Atom, prefix: Option<DOMString>, document: &Document) -> HTMLInputElement { let chan = document.window().constellation_chan(); HTMLInputElement { htmlelement: HTMLElement::new_inherited_with_state(IN_ENABLED_STATE, localName, prefix, document), input_type: Cell::new(InputType::InputText), placeholder: DOMRefCell::new(DOMString::new()), checked_changed: Cell::new(false), value_changed: Cell::new(false), maxlength: Cell::new(DEFAULT_MAX_LENGTH), size: Cell::new(DEFAULT_INPUT_SIZE), textinput: DOMRefCell::new(TextInput::new(Single, DOMString::new(), chan, None)), activation_state: DOMRefCell::new(InputActivationState::new()), value_dirty: Cell::new(false), } } #[allow(unrooted_must_root)] pub fn new(localName: Atom, prefix: Option<DOMString>, document: &Document) -> Root<HTMLInputElement> { let element = HTMLInputElement::new_inherited(localName, prefix, document); Node::reflect_node(box element, document, HTMLInputElementBinding::Wrap) } pub fn type_(&self) -> Atom { self.upcast::<Element>() .get_attribute(&ns!(), &atom!("type")) .map_or_else(|| atom!(""), |a| a.value().as_atom().to_owned()) } // https://html.spec.whatwg.org/multipage/#input-type-attr-summary fn get_value_mode(&self) -> ValueMode { match self.input_type.get() { InputType::InputSubmit | InputType::InputReset | InputType::InputButton | InputType::InputImage => ValueMode::Default, InputType::InputCheckbox | InputType::InputRadio => ValueMode::DefaultOn, InputType::InputPassword | InputType::InputText => ValueMode::Value, InputType::InputFile => ValueMode::Filename, } } } pub trait LayoutHTMLInputElementHelpers { #[allow(unsafe_code)] unsafe fn get_value_for_layout(self) -> String; #[allow(unsafe_code)] unsafe fn get_size_for_layout(self) -> u32; #[allow(unsafe_code)] unsafe fn get_insertion_point_index_for_layout(self) -> Option<isize>; #[allow(unsafe_code)] unsafe fn get_checked_state_for_layout(self) -> bool; #[allow(unsafe_code)] unsafe fn get_indeterminate_state_for_layout(self) -> bool; } #[allow(unsafe_code)] unsafe fn get_raw_textinput_value(input: LayoutJS<HTMLInputElement>) -> DOMString { (*input.unsafe_get()).textinput.borrow_for_layout().get_content() } impl LayoutHTMLInputElementHelpers for LayoutJS<HTMLInputElement> { #[allow(unsafe_code)] unsafe fn get_value_for_layout(self) -> String { #[allow(unsafe_code)] unsafe fn get_raw_attr_value(input: LayoutJS<HTMLInputElement>, default: &str) -> String { let elem = input.upcast::<Element>(); let value = (*elem.unsafe_get()) .get_attr_val_for_layout(&ns!(), &atom!("value")) .unwrap_or(default); String::from(value) } match (*self.unsafe_get()).input_type.get() { InputType::InputCheckbox | InputType::InputRadio => String::new(), InputType::InputFile | InputType::InputImage => String::new(), InputType::InputButton => get_raw_attr_value(self, ""), InputType::InputSubmit => get_raw_attr_value(self, DEFAULT_SUBMIT_VALUE), InputType::InputReset => get_raw_attr_value(self, DEFAULT_RESET_VALUE), InputType::InputPassword => { let text = get_raw_textinput_value(self); if !text.is_empty() { // The implementation of get_insertion_point_index_for_layout expects a 1:1 mapping of chars. text.chars().map(|_| '●').collect() } else { String::from((*self.unsafe_get()).placeholder.borrow_for_layout().clone()) } }, _ => { let text = get_raw_textinput_value(self); if !text.is_empty() { // The implementation of get_insertion_point_index_for_layout expects a 1:1 mapping of chars. String::from(text) } else { String::from((*self.unsafe_get()).placeholder.borrow_for_layout().clone()) } }, } } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn get_size_for_layout(self) -> u32 { (*self.unsafe_get()).size.get() } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn get_insertion_point_index_for_layout(self) -> Option<isize> { if !(*self.unsafe_get()).upcast::<Element>().get_focus_state() { return None; } match (*self.unsafe_get()).input_type.get() { InputType::InputText => { let raw = self.get_value_for_layout(); Some(search_index((*self.unsafe_get()).textinput.borrow_for_layout().edit_point.index, raw.char_indices())) } InputType::InputPassword => { // Use the raw textinput to get the index as long as we use a 1:1 char mapping // in get_input_value_for_layout. let raw = get_raw_textinput_value(self); Some(search_index((*self.unsafe_get()).textinput.borrow_for_layout().edit_point.index, raw.char_indices())) } _ => None } } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn get_checked_state_for_layout(self) -> bool { self.upcast::<Element>().get_state_for_layout().contains(IN_CHECKED_STATE) } #[allow(unrooted_must_root)] #[allow(unsafe_code)] unsafe fn get_indeterminate_state_for_layout(self) -> bool { self.upcast::<Element>().get_state_for_layout().contains(IN_INDETERMINATE_STATE) } } impl HTMLInputElementMethods for HTMLInputElement { // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_getter!(Disabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fe-disabled make_bool_setter!(SetDisabled, "disabled"); // https://html.spec.whatwg.org/multipage/#dom-fae-form fn GetForm(&self) -> Option<Root<HTMLFormElement>> { self.form_owner() } // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked make_bool_getter!(DefaultChecked, "checked"); // https://html.spec.whatwg.org/multipage/#dom-input-defaultchecked make_bool_setter!(SetDefaultChecked, "checked"); // https://html.spec.whatwg.org/multipage/#dom-input-checked fn Checked(&self) -> bool { self.upcast::<Element>().get_state().contains(IN_CHECKED_STATE) } // https://html.spec.whatwg.org/multipage/#dom-input-checked fn SetChecked(&self, checked: bool) { self.update_checked_state(checked, true); } // https://html.spec.whatwg.org/multipage/#dom-input-readonly make_bool_getter!(ReadOnly, "readonly"); // https://html.spec.whatwg.org/multipage/#dom-input-readonly make_bool_setter!(SetReadOnly, "readonly"); // https://html.spec.whatwg.org/multipage/#dom-input-size make_uint_getter!(Size, "size", DEFAULT_INPUT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-input-size make_limited_uint_setter!(SetSize, "size", DEFAULT_INPUT_SIZE); // https://html.spec.whatwg.org/multipage/#dom-input-type make_enumerated_getter!(Type, "type", "text", ("hidden") | ("search") | ("tel") | ("url") | ("email") | ("password") | ("datetime") | ("date") | ("month") | ("week") | ("time") | ("datetime-local") | ("number") | ("range") | ("color") | ("checkbox") | ("radio") | ("file") | ("submit") | ("image") | ("reset") | ("button")); // https://html.spec.whatwg.org/multipage/#dom-input-type make_atomic_setter!(SetType, "type"); // https://html.spec.whatwg.org/multipage/#dom-input-value fn Value(&self) -> DOMString { match self.get_value_mode() { ValueMode::Value => self.textinput.borrow().get_content(), ValueMode::Default => { self.upcast::<Element>() .get_attribute(&ns!(), &atom!("value")) .map_or(DOMString::from(""), |a| DOMString::from(a.summarize().value)) } ValueMode::DefaultOn => { self.upcast::<Element>() .get_attribute(&ns!(), &atom!("value")) .map_or(DOMString::from("on"), |a| DOMString::from(a.summarize().value)) } ValueMode::Filename => { // TODO: return C:\fakepath\<first of selected files> when a file is selected DOMString::from("") } } } // https://html.spec.whatwg.org/multipage/#dom-input-value fn SetValue(&self, value: DOMString) -> ErrorResult { match self.get_value_mode() { ValueMode::Value => { self.textinput.borrow_mut().set_content(value); self.value_dirty.set(true); } ValueMode::Default | ValueMode::DefaultOn => { self.upcast::<Element>().set_string_attribute(&atom!("value"), value); } ValueMode::Filename => { if value.is_empty() { // TODO: empty list of selected files } else { return Err(Error::InvalidState); } } } self.value_changed.set(true); self.force_relayout(); Ok(()) } // https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue make_getter!(DefaultValue, "value"); // https://html.spec.whatwg.org/multipage/#dom-input-defaultvalue make_setter!(SetDefaultValue, "value"); // https://html.spec.whatwg.org/multipage/#attr-fe-name make_getter!(Name, "name"); // https://html.spec.whatwg.org/multipage/#attr-fe-name make_atomic_setter!(SetName, "name"); // https://html.spec.whatwg.org/multipage/#attr-input-placeholder make_getter!(Placeholder, "placeholder"); // https://html.spec.whatwg.org/multipage/#attr-input-placeholder make_setter!(SetPlaceholder, "placeholder"); // https://html.spec.whatwg.org/multipage/#dom-input-formaction make_url_or_base_getter!(FormAction, "formaction"); // https://html.spec.whatwg.org/multipage/#dom-input-formaction make_setter!(SetFormAction, "formaction"); // https://html.spec.whatwg.org/multipage/#dom-input-formenctype make_enumerated_getter!(FormEnctype, "formenctype", "application/x-www-form-urlencoded", ("text/plain") | ("multipart/form-data")); // https://html.spec.whatwg.org/multipage/#dom-input-formenctype make_setter!(SetFormEnctype, "formenctype"); // https://html.spec.whatwg.org/multipage/#dom-input-formmethod make_enumerated_getter!(FormMethod, "formmethod", "get", ("post") | ("dialog")); // https://html.spec.whatwg.org/multipage/#dom-input-formmethod make_setter!(SetFormMethod, "formmethod"); // https://html.spec.whatwg.org/multipage/#dom-input-formtarget make_getter!(FormTarget, "formtarget"); // https://html.spec.whatwg.org/multipage/#dom-input-formtarget make_setter!(SetFormTarget, "formtarget"); // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate make_bool_getter!(FormNoValidate, "formnovalidate"); // https://html.spec.whatwg.org/multipage/#attr-fs-formnovalidate make_bool_setter!(SetFormNoValidate, "formnovalidate"); // https://html.spec.whatwg.org/multipage/#dom-input-maxlength make_int_getter!(MaxLength, "maxlength", DEFAULT_MAX_LENGTH); // https://html.spec.whatwg.org/multipage/#dom-input-maxlength make_limited_int_setter!(SetMaxLength, "maxlength", DEFAULT_MAX_LENGTH); // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate fn Indeterminate(&self) -> bool { self.upcast::<Element>().get_state().contains(IN_INDETERMINATE_STATE) } // https://html.spec.whatwg.org/multipage/#dom-input-indeterminate fn SetIndeterminate(&self, val: bool) { self.upcast::<Element>().set_state(IN_INDETERMINATE_STATE, val) } // https://html.spec.whatwg.org/multipage/#dom-lfe-labels fn Labels(&self) -> Root<NodeList> { if self.type_() == atom!("hidden") { let window = window_from_node(self); NodeList::empty(&window) } else { self.upcast::<HTMLElement>().labels() } } } #[allow(unsafe_code)] fn broadcast_radio_checked(broadcaster: &HTMLInputElement, group: Option<&Atom>) { match group { None | Some(&atom!("")) => { // Radio input elements with a missing or empty name are alone in their // own group. return; }, _ => {}, } //TODO: if not in document, use root ancestor instead of document let owner = broadcaster.form_owner(); let doc = document_from_node(broadcaster); // This function is a workaround for lifetime constraint difficulties. fn do_broadcast(doc_node: &Node, broadcaster: &HTMLInputElement, owner: Option<&HTMLFormElement>, group: Option<&Atom>) { let iter = doc_node.query_selector_iter(DOMString::from("input[type=radio]")).unwrap() .filter_map(Root::downcast::<HTMLInputElement>) .filter(|r| in_same_group(r.r(), owner, group) && broadcaster != r.r()); for ref r in iter { if r.Checked() { r.SetChecked(false); } } } do_broadcast(doc.upcast(), broadcaster, owner.r(), group) } // https://html.spec.whatwg.org/multipage/#radio-button-group fn in_same_group(other: &HTMLInputElement, owner: Option<&HTMLFormElement>, group: Option<&Atom>) -> bool { other.input_type.get() == InputType::InputRadio && // TODO Both a and b are in the same home subtree. other.form_owner().r() == owner && match (other.get_radio_group_name(), group) { (Some(ref s1), Some(s2)) => compatibility_caseless_match_str(s1, s2) && s2 != &atom!(""), _ => false } } impl HTMLInputElement { fn force_relayout(&self) { let doc = document_from_node(self); doc.content_changed(self.upcast(), NodeDamage::OtherNodeDamage) } fn radio_group_updated(&self, group: Option<&Atom>) { if self.Checked() { broadcast_radio_checked(self, group); } } /// https://html.spec.whatwg.org/multipage/#constructing-the-form-data-set /// Steps range from 3.1 to 3.7 which related to the HTMLInputElement pub fn get_form_datum(&self, submitter: Option<FormSubmitter>) -> Option<FormDatum> { // Step 3.2 let ty = self.type_(); // Step 3.4 let name = self.Name(); let is_submitter = match submitter { Some(FormSubmitter::InputElement(s)) => { self == s }, _ => false }; match ty { // Step 3.1: it's a button but it is not submitter. atom!("submit") | atom!("button") | atom!("reset") if !is_submitter => return None, // Step 3.1: it's the "Checkbox" or "Radio Button" and whose checkedness is false. atom!("radio") | atom!("checkbox") => if !self.Checked() || name.is_empty() { return None; }, atom!("image") | atom!("file") => return None, // Unimplemented // Step 3.1: it's not the "Image Button" and doesn't have a name attribute. _ => if name.is_empty() { return None; } } // Step 3.6 Some(FormDatum { ty: DOMString::from(&*ty), // FIXME(ajeffrey): Convert directly from Atoms to DOMStrings name: name, value: self.Value() }) } // https://html.spec.whatwg.org/multipage/#radio-button-group fn get_radio_group_name(&self) -> Option<Atom> { //TODO: determine form owner self.upcast::<Element>() .get_attribute(&ns!(), &atom!("name")) .map(|name| name.value().as_atom().clone()) } fn update_checked_state(&self, checked: bool, dirty: bool) { self.upcast::<Element>().set_state(IN_CHECKED_STATE, checked); if dirty { self.checked_changed.set(true); } if self.input_type.get() == InputType::InputRadio && checked { broadcast_radio_checked(self, self.get_radio_group_name().as_ref()); } self.force_relayout(); //TODO: dispatch change event } pub fn get_indeterminate_state(&self) -> bool { self.Indeterminate() } // https://html.spec.whatwg.org/multipage/#concept-fe-mutable fn mutable(&self) -> bool { // https://html.spec.whatwg.org/multipage/#the-input-element:concept-fe-mutable // https://html.spec.whatwg.org/multipage/#the-readonly-attribute:concept-fe-mutable !(self.upcast::<Element>().get_disabled_state() || self.ReadOnly()) } // https://html.spec.whatwg.org/multipage/#the-input-element:concept-form-reset-control pub fn reset(&self) { match self.input_type.get() { InputType::InputRadio | InputType::InputCheckbox => { self.update_checked_state(self.DefaultChecked(), false); self.checked_changed.set(false); }, InputType::InputImage => (), _ => () } self.SetValue(self.DefaultValue()) .expect("Failed to reset input value to default."); self.value_dirty.set(false); self.value_changed.set(false); self.force_relayout(); } } impl VirtualMethods for HTMLInputElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn attribute_mutated(&self, attr: &Attr, mutation: AttributeMutation) { self.super_type().unwrap().attribute_mutated(attr, mutation); match attr.local_name() { &atom!("disabled") => { let disabled_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Input was already disabled before. return; }, AttributeMutation::Removed => false, }; let el = self.upcast::<Element>(); el.set_disabled_state(disabled_state); el.set_enabled_state(!disabled_state); el.check_ancestors_disabled_state_for_form_control(); }, &atom!("checked") if !self.checked_changed.get() => { let checked_state = match mutation { AttributeMutation::Set(None) => true, AttributeMutation::Set(Some(_)) => { // Input was already checked before. return; }, AttributeMutation::Removed => false, }; self.update_checked_state(checked_state, false); }, &atom!("size") => { let size = mutation.new_value(attr).map(|value| { value.as_uint() }); self.size.set(size.unwrap_or(DEFAULT_INPUT_SIZE)); } &atom!("type") => { match mutation { AttributeMutation::Set(_) => { let new_type = match attr.value().as_atom() { &atom!("button") => InputType::InputButton, &atom!("submit") => InputType::InputSubmit, &atom!("reset") => InputType::InputReset, &atom!("file") => InputType::InputFile, &atom!("radio") => InputType::InputRadio, &atom!("checkbox") => InputType::InputCheckbox, &atom!("password") => InputType::InputPassword, _ => InputType::InputText, }; // https://html.spec.whatwg.org/multipage/#input-type-change let (old_value_mode, old_idl_value) = (self.get_value_mode(), self.Value()); self.input_type.set(new_type); let new_value_mode = self.get_value_mode(); match (&old_value_mode, old_idl_value.is_empty(), new_value_mode) { // Step 1 (&ValueMode::Value, false, ValueMode::Default) | (&ValueMode::Value, false, ValueMode::DefaultOn) => { self.SetValue(old_idl_value) .expect("Failed to set input value on type change to a default ValueMode."); } // Step 2 (_, _, ValueMode::Value) if old_value_mode != ValueMode::Value => { self.SetValue(self.upcast::<Element>() .get_attribute(&ns!(), &atom!("value")) .map_or(DOMString::from(""), |a| DOMString::from(a.summarize().value))) .expect("Failed to set input value on type change to ValueMode::Value."); self.value_dirty.set(false); } // Step 3 (_, _, ValueMode::Filename) if old_value_mode != ValueMode::Filename => { self.SetValue(DOMString::from("")) .expect("Failed to set input value on type change to ValueMode::Filename."); } _ => {} } // Step 5 if new_type == InputType::InputRadio { self.radio_group_updated( self.get_radio_group_name().as_ref()); } // TODO: Step 6 - value sanitization }, AttributeMutation::Removed => { if self.input_type.get() == InputType::InputRadio { broadcast_radio_checked( self, self.get_radio_group_name().as_ref()); } self.input_type.set(InputType::InputText); } } }, &atom!("value") if !self.value_changed.get() => { let value = mutation.new_value(attr).map(|value| (**value).to_owned()); self.textinput.borrow_mut().set_content( value.map_or(DOMString::new(), DOMString::from)); }, &atom!("name") if self.input_type.get() == InputType::InputRadio => { self.radio_group_updated( mutation.new_value(attr).as_ref().map(|name| name.as_atom())); }, &atom!("maxlength") => { match *attr.value() { AttrValue::Int(_, value) => { if value < 0 { self.textinput.borrow_mut().max_length = None } else { self.textinput.borrow_mut().max_length = Some(value as usize) } }, _ => panic!("Expected an AttrValue::Int"), } } &atom!("placeholder") => { // FIXME(ajeffrey): Should we do in-place mutation of the placeholder? let mut placeholder = self.placeholder.borrow_mut(); placeholder.clear(); if let AttributeMutation::Set(_) = mutation { placeholder.extend( attr.value().chars().filter(|&c| c != '\n' && c != '\r')); } }, _ => {}, } } fn parse_plain_attribute(&self, name: &Atom, value: DOMString) -> AttrValue { match name { &atom!("name") => AttrValue::from_atomic(value), &atom!("size") => AttrValue::from_limited_u32(value, DEFAULT_INPUT_SIZE), &atom!("type") => AttrValue::from_atomic(value), &atom!("maxlength") => AttrValue::from_limited_i32(value, DEFAULT_MAX_LENGTH), _ => self.super_type().unwrap().parse_plain_attribute(name, value), } } fn bind_to_tree(&self, tree_in_doc: bool) { if let Some(ref s) = self.super_type() { s.bind_to_tree(tree_in_doc); } self.upcast::<Element>().check_ancestors_disabled_state_for_form_control(); } fn unbind_from_tree(&self, context: &UnbindContext) { self.super_type().unwrap().unbind_from_tree(context); let node = self.upcast::<Node>(); let el = self.upcast::<Element>(); if node.ancestors().any(|ancestor| ancestor.is::<HTMLFieldSetElement>()) { el.check_ancestors_disabled_state_for_form_control(); } else { el.check_disabled_attribute(); } } fn handle_event(&self, event: &Event) { if let Some(s) = self.super_type() { s.handle_event(event); } if event.type_() == atom!("click") && !event.DefaultPrevented() { if let InputType::InputRadio = self.input_type.get() { self.update_checked_state(true, true); } // TODO: Dispatch events for non activatable inputs // https://html.spec.whatwg.org/multipage/#common-input-element-events //TODO: set the editing position for text inputs document_from_node(self).request_focus(self.upcast()); } else if event.type_() == atom!("keydown") && !event.DefaultPrevented() && (self.input_type.get() == InputType::InputText || self.input_type.get() == InputType::InputPassword) { if let Some(keyevent) = event.downcast::<KeyboardEvent>() { // This can't be inlined, as holding on to textinput.borrow_mut() // during self.implicit_submission will cause a panic. let action = self.textinput.borrow_mut().handle_keydown(keyevent); match action { TriggerDefaultAction => { self.implicit_submission(keyevent.CtrlKey(), keyevent.ShiftKey(), keyevent.AltKey(), keyevent.MetaKey()); }, DispatchInput => { self.value_changed.set(true); if event.IsTrusted() { ChangeEventRunnable::send(self.upcast::<Node>()); } self.force_relayout(); event.PreventDefault(); } RedrawSelection => { self.force_relayout(); event.PreventDefault(); } Nothing => (), } } } } } impl FormControl for HTMLInputElement {} impl Activatable for HTMLInputElement { fn as_element(&self) -> &Element { self.upcast() } fn is_instance_activatable(&self) -> bool { match self.input_type.get() { // https://html.spec.whatwg.org/multipage/#submit-button-state-%28type=submit%29:activation-behaviour-2 // https://html.spec.whatwg.org/multipage/#reset-button-state-%28type=reset%29:activation-behaviour-2 // https://html.spec.whatwg.org/multipage/#checkbox-state-%28type=checkbox%29:activation-behaviour-2 // https://html.spec.whatwg.org/multipage/#radio-button-state-%28type=radio%29:activation-behaviour-2 InputType::InputSubmit | InputType::InputReset | InputType::InputCheckbox | InputType::InputRadio => self.mutable(), _ => false } } // https://html.spec.whatwg.org/multipage/#run-pre-click-activation-steps #[allow(unsafe_code)] fn pre_click_activation(&self) { let mut cache = self.activation_state.borrow_mut(); let ty = self.input_type.get(); cache.old_type = ty; cache.was_mutable = self.mutable(); if cache.was_mutable { match ty { // https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior // InputType::InputSubmit => (), // No behavior defined // https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior // InputType::InputSubmit => (), // No behavior defined InputType::InputCheckbox => { /* https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):pre-click-activation-steps cache current values of `checked` and `indeterminate` we may need to restore them later */ cache.indeterminate = self.Indeterminate(); cache.checked = self.Checked(); cache.checked_changed = self.checked_changed.get(); self.SetIndeterminate(false); self.SetChecked(!cache.checked); }, // https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):pre-click-activation-steps InputType::InputRadio => { //TODO: if not in document, use root ancestor instead of document let owner = self.form_owner(); let doc = document_from_node(self); let doc_node = doc.upcast::<Node>(); let group = self.get_radio_group_name();; // Safe since we only manipulate the DOM tree after finding an element let checked_member = doc_node.query_selector_iter(DOMString::from("input[type=radio]")) .unwrap() .filter_map(Root::downcast::<HTMLInputElement>) .find(|r| { in_same_group(r.r(), owner.r(), group.as_ref()) && r.Checked() }); cache.checked_radio = checked_member.r().map(JS::from_ref); cache.checked_changed = self.checked_changed.get(); self.SetChecked(true); } _ => () } } } // https://html.spec.whatwg.org/multipage/#run-canceled-activation-steps fn canceled_activation(&self) { let cache = self.activation_state.borrow(); let ty = self.input_type.get(); if cache.old_type != ty { // Type changed, abandon ship // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414 return; } match ty { // https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior // InputType::InputSubmit => (), // No behavior defined // https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior // InputType::InputReset => (), // No behavior defined // https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):canceled-activation-steps InputType::InputCheckbox => { // We want to restore state only if the element had been changed in the first place if cache.was_mutable { self.SetIndeterminate(cache.indeterminate); self.SetChecked(cache.checked); self.checked_changed.set(cache.checked_changed); } }, // https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):canceled-activation-steps InputType::InputRadio => { // We want to restore state only if the element had been changed in the first place if cache.was_mutable { let name = self.get_radio_group_name(); match cache.checked_radio.r() { Some(o) => { // Avoiding iterating through the whole tree here, instead // we can check if the conditions for radio group siblings apply if name == o.get_radio_group_name() && // TODO should be compatibility caseless self.form_owner() == o.form_owner() && // TODO Both a and b are in the same home subtree o.input_type.get() == InputType::InputRadio { o.SetChecked(true); } else { self.SetChecked(false); } }, None => self.SetChecked(false) }; self.checked_changed.set(cache.checked_changed); } } _ => () } } // https://html.spec.whatwg.org/multipage/#run-post-click-activation-steps fn activation_behavior(&self, _event: &Event, _target: &EventTarget) { let ty = self.input_type.get(); if self.activation_state.borrow().old_type != ty { // Type changed, abandon ship // https://www.w3.org/Bugs/Public/show_bug.cgi?id=27414 return; } match ty { InputType::InputSubmit => { // https://html.spec.whatwg.org/multipage/#submit-button-state-(type=submit):activation-behavior // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) if self.mutable() /* and document owner is fully active */ { self.form_owner().map(|o| { o.submit(SubmittedFrom::NotFromFormSubmitMethod, FormSubmitter::InputElement(self.clone())) }); } }, InputType::InputReset => { // https://html.spec.whatwg.org/multipage/#reset-button-state-(type=reset):activation-behavior // FIXME (Manishearth): support document owners (needs ability to get parent browsing context) if self.mutable() /* and document owner is fully active */ { self.form_owner().map(|o| { o.reset(ResetFrom::NotFromFormResetMethod) }); } }, InputType::InputCheckbox | InputType::InputRadio => { // https://html.spec.whatwg.org/multipage/#checkbox-state-(type=checkbox):activation-behavior // https://html.spec.whatwg.org/multipage/#radio-button-state-(type=radio):activation-behavior if self.mutable() { let target = self.upcast::<EventTarget>(); target.fire_event("input", EventBubbles::Bubbles, EventCancelable::NotCancelable); target.fire_event("change", EventBubbles::Bubbles, EventCancelable::NotCancelable); } }, _ => () } } // https://html.spec.whatwg.org/multipage/#implicit-submission #[allow(unsafe_code)] fn implicit_submission(&self, ctrlKey: bool, shiftKey: bool, altKey: bool, metaKey: bool) { let doc = document_from_node(self); let node = doc.upcast::<Node>(); let owner = self.form_owner(); let form = match owner { None => return, Some(ref f) => f }; if self.upcast::<Element>().click_in_progress() { return; } let submit_button; submit_button = node.query_selector_iter(DOMString::from("input[type=submit]")).unwrap() .filter_map(Root::downcast::<HTMLInputElement>) .find(|r| r.form_owner() == owner); match submit_button { Some(ref button) => { if button.is_instance_activatable() { button.synthetic_click_activation(ctrlKey, shiftKey, altKey, metaKey) } } None => { let inputs = node.query_selector_iter(DOMString::from("input")).unwrap() .filter_map(Root::downcast::<HTMLInputElement>) .filter(|input| { input.form_owner() == owner && match input.type_() { atom!("text") | atom!("search") | atom!("url") | atom!("tel") | atom!("email") | atom!("password") | atom!("datetime") | atom!("date") | atom!("month") | atom!("week") | atom!("time") | atom!("datetime-local") | atom!("number") => true, _ => false } }); if inputs.skip(1).next().is_some() { // lazily test for > 1 submission-blocking inputs return; } form.submit(SubmittedFrom::NotFromFormSubmitMethod, FormSubmitter::FormElement(form.r())); } } } } pub struct ChangeEventRunnable { element: Trusted<Node>, } impl ChangeEventRunnable { pub fn send(node: &Node) { let window = window_from_node(node); let window = window.r(); let chan = window.user_interaction_task_source(); let handler = Trusted::new(node, chan.clone()); let dispatcher = ChangeEventRunnable { element: handler, }; let _ = chan.send(CommonScriptMsg::RunnableMsg(InputEvent, box dispatcher)); } } impl Runnable for ChangeEventRunnable { fn handler(self: Box<ChangeEventRunnable>) { let target = self.element.root(); let window = window_from_node(target.r()); let window = window.r(); let event = Event::new(GlobalRef::Window(window), atom!("input"), EventBubbles::Bubbles, EventCancelable::NotCancelable); target.upcast::<EventTarget>().dispatch_event(&event); } }
mpl-2.0
wavebox/waveboxapp
classic/src/scenes/mailboxes/src/Scenes/AccountWizardScene/MailboxWizardScene/MailboxWizardSceneContent.js
4621
import PropTypes from 'prop-types' import React from 'react' import shallowCompare from 'react-addons-shallow-compare' import WizardPersonalise from './WizardPersonalise' import WizardAuth from './WizardAuth' import WizardConfigure from './WizardConfigure' import WizardStepperDialogContent from '../Common/WizardStepperDialogContent' import { ACCOUNT_TEMPLATE_TYPE_LIST, ACCOUNT_TEMPLATES } from 'shared/Models/ACAccounts/AccountTemplates' class MailboxWizardSceneContent extends React.Component { /* **************************************************************************/ // Class /* **************************************************************************/ static propTypes = { match: PropTypes.shape({ params: PropTypes.shape({ templateType: PropTypes.oneOf(ACCOUNT_TEMPLATE_TYPE_LIST).isRequired, accessMode: PropTypes.string.isRequired, step: PropTypes.string.isRequired, mailboxId: PropTypes.string }).isRequired }).isRequired } /* **************************************************************************/ // Component lifecycle /* **************************************************************************/ componentWillReceiveProps (nextProps) { if (this.props.match.params.templateType !== nextProps.match.params.templateType) { this.setState({ steps: this.generateStepsArray(nextProps.match.params.templateType) }) } } /* **************************************************************************/ // Data lifecycle /* **************************************************************************/ state = (() => { return { steps: this.generateStepsArray(this.props.match.params.templateType) } })() /** * Generates the steps array * @param templateType: the type of template * @return an array of step configs for the state */ generateStepsArray (templateType) { const template = ACCOUNT_TEMPLATES[templateType] if (template && template.hasAuthStep) { return [ { step: 0, text: 'Personalise', stepNumberText: '1' }, { step: 1, text: 'Sign in', stepNumberText: '2' }, { step: 2, text: 'Configure', stepNumberText: '3' } ] } else { return [ { step: 0, text: 'Personalise', stepNumberText: '1' }, { step: 2, text: 'Configure', stepNumberText: '2' } ] } } /* **************************************************************************/ // User Interaction /* **************************************************************************/ /** * Closes the modal * @param evt: the event that fired * @param destination='/' an optional destination when dismissin */ handleClose = (evt, destination) => { destination = typeof (destination) === 'string' && destination ? destination : '/' window.location.hash = destination } /** * Minimizes the auth step * @param evt: the event that fired */ handleMinimizeAuth = (evt) => { window.location.hash = '/' } /* **************************************************************************/ // Rendering /* **************************************************************************/ shouldComponentUpdate (nextProps, nextState) { return shallowCompare(this, nextProps, nextState) } /** * Renders the current step * @param currentStep: the step to render * @param template: the template type * @param accessMode: the access mode to use when creating the mailbox * @param mailboxId: the id of the mailbox * @return jsx */ renderStep (currentStep, template, accessMode, mailboxId) { switch (currentStep) { case 0: return ( <WizardPersonalise onRequestCancel={this.handleClose} template={ACCOUNT_TEMPLATES[template]} accessMode={accessMode} /> ) case 1: return ( <WizardAuth onRequestMinimize={this.handleMinimizeAuth} /> ) case 2: return ( <WizardConfigure onRequestCancel={this.handleClose} mailboxId={mailboxId} /> ) } } render () { const { steps } = this.state const { match } = this.props const currentStep = parseInt(match.params.step) return ( <WizardStepperDialogContent steps={steps} currentStep={currentStep}> {this.renderStep( currentStep, match.params.templateType, match.params.accessMode, match.params.mailboxId )} </WizardStepperDialogContent> ) } } export default MailboxWizardSceneContent
mpl-2.0
HadrienG2/testbench
src/noinline.rs
928
//! Inlining barriers for function calls //! //! Inlining is great for optimization. But it can cause problems in micro- //! benchmarking and multi-threaded validation as it leads some testing and //! benchmarking constructs to be optimized out. This module can be used to //! avoid this outcome without altering the function being called itself. /// Inlining barrier for FnOnce /// /// # Panics /// /// This function will propagate panics from the inner callable. #[inline(never)] pub fn call_once(callable: impl FnOnce()) { callable() } /// Inlining barrier for FnMut /// /// # Panics /// /// This function will propagate panics from the inner callable. #[inline(never)] pub fn call_mut(callable: &mut impl FnMut()) { callable() } /// Inlining barrier for Fn /// /// # Panics /// /// This function will propagate panics from the inner callable. #[inline(never)] pub fn call(callable: &impl Fn()) { callable() }
mpl-2.0
zeroae/consul
agent/consul/leader_test.go
20784
package consul import ( "os" "testing" "time" "github.com/hashicorp/consul/agent/consul/structs" "github.com/hashicorp/consul/api" "github.com/hashicorp/consul/testrpc" "github.com/hashicorp/consul/testutil/retry" "github.com/hashicorp/net-rpc-msgpackrpc" "github.com/hashicorp/serf/serf" ) func TestLeader_RegisterMember(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() // Try to join joinLAN(t, c1, s1) testrpc.WaitForLeader(t, s1.RPC, "dc1") // Client should be registered state := s1.fsm.State() retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } }) // Should have a check _, checks, err := state.NodeChecks(nil, c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if len(checks) != 1 { t.Fatalf("client missing check") } if checks[0].CheckID != structs.SerfCheckID { t.Fatalf("bad check: %v", checks[0]) } if checks[0].Name != structs.SerfCheckName { t.Fatalf("bad check: %v", checks[0]) } if checks[0].Status != api.HealthPassing { t.Fatalf("bad check: %v", checks[0]) } // Server should be registered _, node, err := state.GetNode(s1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if node == nil { t.Fatalf("server not registered") } // Service should be registered _, services, err := state.NodeServices(nil, s1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if _, ok := services.Services["consul"]; !ok { t.Fatalf("consul service not registered: %v", services) } } func TestLeader_FailedMember(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() testrpc.WaitForLeader(t, s1.RPC, "dc1") // Try to join joinLAN(t, c1, s1) // Fail the member c1.Shutdown() // Should be registered state := s1.fsm.State() retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } }) // Should have a check _, checks, err := state.NodeChecks(nil, c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if len(checks) != 1 { t.Fatalf("client missing check") } if checks[0].CheckID != structs.SerfCheckID { t.Fatalf("bad check: %v", checks[0]) } if checks[0].Name != structs.SerfCheckName { t.Fatalf("bad check: %v", checks[0]) } retry.Run(t, func(r *retry.R) { _, checks, err = state.NodeChecks(nil, c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if got, want := checks[0].Status, api.HealthCritical; got != want { r.Fatalf("got status %q want %q", got, want) } }) } func TestLeader_LeftMember(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() // Try to join joinLAN(t, c1, s1) state := s1.fsm.State() // Should be registered retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } }) // Node should leave c1.Leave() c1.Shutdown() // Should be deregistered retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node != nil { r.Fatal("client still registered") } }) } func TestLeader_ReapMember(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() // Try to join joinLAN(t, c1, s1) state := s1.fsm.State() // Should be registered retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } }) // Simulate a node reaping mems := s1.LANMembers() var c1mem serf.Member for _, m := range mems { if m.Name == c1.config.NodeName { c1mem = m c1mem.Status = StatusReap break } } s1.reconcileCh <- c1mem // Should be deregistered; we have to poll quickly here because // anti-entropy will put it back. reaped := false for start := time.Now(); time.Since(start) < 5*time.Second; { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if node == nil { reaped = true break } } if !reaped { t.Fatalf("client should not be registered") } } func TestLeader_Reconcile_ReapMember(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() testrpc.WaitForLeader(t, s1.RPC, "dc1") // Register a non-existing member dead := structs.RegisterRequest{ Datacenter: s1.config.Datacenter, Node: "no-longer-around", Address: "127.1.1.1", Check: &structs.HealthCheck{ Node: "no-longer-around", CheckID: structs.SerfCheckID, Name: structs.SerfCheckName, Status: api.HealthCritical, }, WriteRequest: structs.WriteRequest{ Token: "root", }, } var out struct{} if err := s1.RPC("Catalog.Register", &dead, &out); err != nil { t.Fatalf("err: %v", err) } // Force a reconciliation if err := s1.reconcile(); err != nil { t.Fatalf("err: %v", err) } // Node should be gone state := s1.fsm.State() _, node, err := state.GetNode("no-longer-around") if err != nil { t.Fatalf("err: %v", err) } if node != nil { t.Fatalf("client registered") } } func TestLeader_Reconcile(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.ACLEnforceVersion8 = true }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() // Join before we have a leader, this should cause a reconcile! joinLAN(t, c1, s1) // Should not be registered state := s1.fsm.State() _, node, err := state.GetNode(c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if node != nil { t.Fatalf("client registered") } // Should be registered retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } }) } func TestLeader_Reconcile_Races(t *testing.T) { t.Parallel() dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() testrpc.WaitForLeader(t, s1.RPC, "dc1") dir2, c1 := testClient(t) defer os.RemoveAll(dir2) defer c1.Shutdown() joinLAN(t, c1, s1) // Wait for the server to reconcile the client and register it. state := s1.fsm.State() var nodeAddr string retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node == nil { r.Fatal("client not registered") } nodeAddr = node.Address }) // Add in some metadata via the catalog (as if the agent synced it // there). We also set the serfHealth check to failing so the reconile // will attempt to flip it back req := structs.RegisterRequest{ Datacenter: s1.config.Datacenter, Node: c1.config.NodeName, ID: c1.config.NodeID, Address: nodeAddr, NodeMeta: map[string]string{"hello": "world"}, Check: &structs.HealthCheck{ Node: c1.config.NodeName, CheckID: structs.SerfCheckID, Name: structs.SerfCheckName, Status: api.HealthCritical, Output: "", }, } var out struct{} if err := s1.RPC("Catalog.Register", &req, &out); err != nil { t.Fatalf("err: %v", err) } // Force a reconcile and make sure the metadata stuck around. if err := s1.reconcile(); err != nil { t.Fatalf("err: %v", err) } _, node, err := state.GetNode(c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if node == nil { t.Fatalf("bad") } if hello, ok := node.Meta["hello"]; !ok || hello != "world" { t.Fatalf("bad") } // Fail the member and wait for the health to go critical. c1.Shutdown() retry.Run(t, func(r *retry.R) { _, checks, err := state.NodeChecks(nil, c1.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if got, want := checks[0].Status, api.HealthCritical; got != want { r.Fatalf("got state %q want %q", got, want) } }) // Make sure the metadata didn't get clobbered. _, node, err = state.GetNode(c1.config.NodeName) if err != nil { t.Fatalf("err: %v", err) } if node == nil { t.Fatalf("bad") } if hello, ok := node.Meta["hello"]; !ok || hello != "world" { t.Fatalf("bad") } } func TestLeader_LeftServer(t *testing.T) { t.Parallel() dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir2) defer s2.Shutdown() dir3, s3 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir3) defer s3.Shutdown() // Put s1 last so we don't trigger a leader election. servers := []*Server{s2, s3, s1} // Try to join joinLAN(t, s2, s1) joinLAN(t, s3, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } // Kill any server servers[0].Shutdown() // Force remove the non-leader (transition to left state) if err := servers[1].RemoveFailedNode(servers[0].config.NodeName); err != nil { t.Fatalf("err: %v", err) } // Wait until the remaining servers show only 2 peers. for _, s := range servers[1:] { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 2)) }) } s1.Shutdown() } func TestLeader_LeftLeader(t *testing.T) { t.Parallel() dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir2) defer s2.Shutdown() dir3, s3 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir3) defer s3.Shutdown() servers := []*Server{s1, s2, s3} // Try to join joinLAN(t, s2, s1) joinLAN(t, s3, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } // Kill the leader! var leader *Server for _, s := range servers { if s.IsLeader() { leader = s break } } if leader == nil { t.Fatalf("Should have a leader") } if !leader.isReadyForConsistentReads() { t.Fatalf("Expected leader to be ready for consistent reads ") } leader.Leave() if leader.isReadyForConsistentReads() { t.Fatalf("Expected consistent read state to be false ") } leader.Shutdown() time.Sleep(100 * time.Millisecond) var remain *Server for _, s := range servers { if s == leader { continue } remain = s retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 2)) }) } // Verify the old leader is deregistered state := remain.fsm.State() retry.Run(t, func(r *retry.R) { _, node, err := state.GetNode(leader.config.NodeName) if err != nil { r.Fatalf("err: %v", err) } if node != nil { r.Fatal("leader should be deregistered") } }) } func TestLeader_MultiBootstrap(t *testing.T) { t.Parallel() dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServer(t) defer os.RemoveAll(dir2) defer s2.Shutdown() servers := []*Server{s1, s2} // Try to join joinLAN(t, s2, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { if got, want := len(s.serfLAN.Members()), 2; got != want { r.Fatalf("got %d peers want %d", got, want) } }) } // Ensure we don't have multiple raft peers for _, s := range servers { peers, _ := s.numPeers() if peers != 1 { t.Fatalf("should only have 1 raft peer!") } } } func TestLeader_TombstoneGC_Reset(t *testing.T) { t.Parallel() dir1, s1 := testServer(t) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir2) defer s2.Shutdown() dir3, s3 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir3) defer s3.Shutdown() servers := []*Server{s1, s2, s3} // Try to join joinLAN(t, s2, s1) joinLAN(t, s3, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } var leader *Server for _, s := range servers { if s.IsLeader() { leader = s break } } if leader == nil { t.Fatalf("Should have a leader") } // Check that the leader has a pending GC expiration if !leader.tombstoneGC.PendingExpiration() { t.Fatalf("should have pending expiration") } // Kill the leader leader.Shutdown() time.Sleep(100 * time.Millisecond) // Wait for a new leader leader = nil retry.Run(t, func(r *retry.R) { for _, s := range servers { if s.IsLeader() { leader = s return } } r.Fatal("no leader") }) retry.Run(t, func(r *retry.R) { if !leader.tombstoneGC.PendingExpiration() { r.Fatal("leader has no pending GC expiration") } }) } func TestLeader_ReapTombstones(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.ACLDatacenter = "dc1" c.ACLMasterToken = "root" c.ACLDefaultPolicy = "deny" c.TombstoneTTL = 50 * time.Millisecond c.TombstoneTTLGranularity = 10 * time.Millisecond }) defer os.RemoveAll(dir1) defer s1.Shutdown() codec := rpcClient(t, s1) testrpc.WaitForLeader(t, s1.RPC, "dc1") // Create a KV entry arg := structs.KVSRequest{ Datacenter: "dc1", Op: api.KVSet, DirEnt: structs.DirEntry{ Key: "test", Value: []byte("test"), }, WriteRequest: structs.WriteRequest{ Token: "root", }, } var out bool if err := msgpackrpc.CallWithCodec(codec, "KVS.Apply", &arg, &out); err != nil { t.Fatalf("err: %v", err) } // Delete the KV entry (tombstoned). arg.Op = api.KVDelete if err := msgpackrpc.CallWithCodec(codec, "KVS.Apply", &arg, &out); err != nil { t.Fatalf("err: %v", err) } // Make sure there's a tombstone. state := s1.fsm.State() func() { snap := state.Snapshot() defer snap.Close() stones, err := snap.Tombstones() if err != nil { t.Fatalf("err: %s", err) } if stones.Next() == nil { t.Fatalf("missing tombstones") } if stones.Next() != nil { t.Fatalf("unexpected extra tombstones") } }() // Check that the new leader has a pending GC expiration by // watching for the tombstone to get removed. retry.Run(t, func(r *retry.R) { snap := state.Snapshot() defer snap.Close() stones, err := snap.Tombstones() if err != nil { r.Fatal(err) } if stones.Next() != nil { r.Fatal("should have no tombstones") } }) } func TestLeader_RollRaftServer(t *testing.T) { t.Parallel() dir1, s1 := testServerWithConfig(t, func(c *Config) { c.Bootstrap = true c.Datacenter = "dc1" }) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServerWithConfig(t, func(c *Config) { c.Bootstrap = false c.Datacenter = "dc1" c.RaftConfig.ProtocolVersion = 1 }) defer os.RemoveAll(dir2) defer s2.Shutdown() dir3, s3 := testServerDCBootstrap(t, "dc1", false) defer os.RemoveAll(dir3) defer s3.Shutdown() servers := []*Server{s1, s2, s3} // Try to join joinLAN(t, s2, s1) joinLAN(t, s3, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } // Kill the v1 server s2.Shutdown() for _, s := range []*Server{s1, s3} { retry.Run(t, func(r *retry.R) { minVer, err := ServerMinRaftProtocol(s.LANMembers()) if err != nil { r.Fatal(err) } if got, want := minVer, 2; got != want { r.Fatalf("got min raft version %d want %d", got, want) } }) } // Replace the dead server with one running raft protocol v3 dir4, s4 := testServerWithConfig(t, func(c *Config) { c.Bootstrap = false c.Datacenter = "dc1" c.RaftConfig.ProtocolVersion = 3 }) defer os.RemoveAll(dir4) defer s4.Shutdown() joinLAN(t, s4, s1) servers[1] = s4 // Make sure the dead server is removed and we're back to 3 total peers for _, s := range servers { retry.Run(t, func(r *retry.R) { addrs := 0 ids := 0 future := s.raft.GetConfiguration() if err := future.Error(); err != nil { r.Fatal(err) } for _, server := range future.Configuration().Servers { if string(server.ID) == string(server.Address) { addrs++ } else { ids++ } } if got, want := addrs, 2; got != want { r.Fatalf("got %d server addresses want %d", got, want) } if got, want := ids, 1; got != want { r.Fatalf("got %d server ids want %d", got, want) } }) } } func TestLeader_ChangeServerID(t *testing.T) { t.Parallel() conf := func(c *Config) { c.Bootstrap = false c.BootstrapExpect = 3 c.Datacenter = "dc1" c.RaftConfig.ProtocolVersion = 3 } dir1, s1 := testServerWithConfig(t, conf) defer os.RemoveAll(dir1) defer s1.Shutdown() dir2, s2 := testServerWithConfig(t, conf) defer os.RemoveAll(dir2) defer s2.Shutdown() dir3, s3 := testServerWithConfig(t, conf) defer os.RemoveAll(dir3) defer s3.Shutdown() servers := []*Server{s1, s2, s3} // Try to join joinLAN(t, s2, s1) joinLAN(t, s3, s1) for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } // Shut down a server, freeing up its address/port s3.Shutdown() retry.Run(t, func(r *retry.R) { alive := 0 for _, m := range s1.LANMembers() { if m.Status == serf.StatusAlive { alive++ } } if got, want := alive, 2; got != want { r.Fatalf("got %d alive members want %d", got, want) } }) // Bring up a new server with s3's address that will get a different ID dir4, s4 := testServerWithConfig(t, func(c *Config) { c.Bootstrap = false c.BootstrapExpect = 3 c.Datacenter = "dc1" c.RaftConfig.ProtocolVersion = 3 c.SerfLANConfig.MemberlistConfig = s3.config.SerfLANConfig.MemberlistConfig c.RPCAddr = s3.config.RPCAddr c.RPCAdvertise = s3.config.RPCAdvertise }) defer os.RemoveAll(dir4) defer s4.Shutdown() joinLAN(t, s4, s1) servers[2] = s4 // Make sure the dead server is removed and we're back to 3 total peers for _, s := range servers { retry.Run(t, func(r *retry.R) { r.Check(wantPeers(s, 3)) }) } } func TestLeader_ACL_Initialization(t *testing.T) { t.Parallel() tests := []struct { name string build string master string init bool bootstrap bool }{ {"old version, no master", "0.8.0", "", false, false}, {"old version, master", "0.8.0", "root", false, false}, {"new version, no master", "0.9.1", "", true, true}, {"new version, master", "0.9.1", "root", true, false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { conf := func(c *Config) { c.Build = tt.build c.Bootstrap = true c.Datacenter = "dc1" c.ACLDatacenter = "dc1" c.ACLMasterToken = tt.master } dir1, s1 := testServerWithConfig(t, conf) defer os.RemoveAll(dir1) defer s1.Shutdown() testrpc.WaitForLeader(t, s1.RPC, "dc1") if tt.master != "" { _, master, err := s1.fsm.State().ACLGet(nil, tt.master) if err != nil { t.Fatalf("err: %v", err) } if master == nil { t.Fatalf("master token wasn't created") } } _, anon, err := s1.fsm.State().ACLGet(nil, anonymousToken) if err != nil { t.Fatalf("err: %v", err) } if anon == nil { t.Fatalf("anonymous token wasn't created") } bs, err := s1.fsm.State().ACLGetBootstrap() if err != nil { t.Fatalf("err: %v", err) } if !tt.init { if bs != nil { t.Fatalf("bootstrap should not be initialized") } } else { if bs == nil { t.Fatalf("bootstrap should be initialized") } if got, want := bs.AllowBootstrap, tt.bootstrap; got != want { t.Fatalf("got %v want %v", got, want) } } }) } }
mpl-2.0
danlrobertson/servo
tests/wpt/web-platform-tests/tools/wptrunner/wptrunner/browsers/firefox.py
18734
import json import os import platform import signal import subprocess import sys import mozinfo import mozleak from mozprocess import ProcessHandler from mozprofile import FirefoxProfile, Preferences from mozrunner import FirefoxRunner from mozrunner.utils import test_environment, get_stack_fixer_function from mozcrash import mozcrash from .base import (get_free_port, Browser, ExecutorBrowser, require_arg, cmd_arg, browser_command) from ..executors import executor_kwargs as base_executor_kwargs from ..executors.executormarionette import (MarionetteTestharnessExecutor, # noqa: F401 MarionetteRefTestExecutor, # noqa: F401 MarionetteWdspecExecutor) # noqa: F401 here = os.path.join(os.path.split(__file__)[0]) __wptrunner__ = {"product": "firefox", "check_args": "check_args", "browser": "FirefoxBrowser", "executor": {"testharness": "MarionetteTestharnessExecutor", "reftest": "MarionetteRefTestExecutor", "wdspec": "MarionetteWdspecExecutor"}, "browser_kwargs": "browser_kwargs", "executor_kwargs": "executor_kwargs", "env_extras": "env_extras", "env_options": "env_options", "run_info_extras": "run_info_extras", "update_properties": "update_properties"} def get_timeout_multiplier(test_type, run_info_data, **kwargs): if kwargs["timeout_multiplier"] is not None: return kwargs["timeout_multiplier"] if test_type == "reftest": if run_info_data["debug"] or run_info_data.get("asan"): return 4 else: return 2 elif run_info_data["debug"] or run_info_data.get("asan"): if run_info_data.get("ccov"): return 4 else: return 3 elif run_info_data["os"] == "android": return 4 return 1 def check_args(**kwargs): require_arg(kwargs, "binary") def browser_kwargs(test_type, run_info_data, config, **kwargs): return {"binary": kwargs["binary"], "prefs_root": kwargs["prefs_root"], "extra_prefs": kwargs["extra_prefs"], "test_type": test_type, "debug_info": kwargs["debug_info"], "symbols_path": kwargs["symbols_path"], "stackwalk_binary": kwargs["stackwalk_binary"], "certutil_binary": kwargs["certutil_binary"], "ca_certificate_path": config.ssl_config["ca_cert_path"], "e10s": kwargs["gecko_e10s"], "stackfix_dir": kwargs["stackfix_dir"], "binary_args": kwargs["binary_args"], "timeout_multiplier": get_timeout_multiplier(test_type, run_info_data, **kwargs), "leak_check": kwargs["leak_check"], "asan": run_info_data.get("asan"), "stylo_threads": kwargs["stylo_threads"], "chaos_mode_flags": kwargs["chaos_mode_flags"], "config": config, "headless": kwargs["headless"]} def executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs): executor_kwargs = base_executor_kwargs(test_type, server_config, cache_manager, run_info_data, **kwargs) executor_kwargs["close_after_done"] = test_type != "reftest" executor_kwargs["timeout_multiplier"] = get_timeout_multiplier(test_type, run_info_data, **kwargs) executor_kwargs["e10s"] = run_info_data["e10s"] capabilities = {} if test_type == "reftest": executor_kwargs["reftest_internal"] = kwargs["reftest_internal"] executor_kwargs["reftest_screenshot"] = kwargs["reftest_screenshot"] if test_type == "wdspec": options = {} if kwargs["binary"]: options["binary"] = kwargs["binary"] if kwargs["binary_args"]: options["args"] = kwargs["binary_args"] if kwargs["headless"]: if "args" not in options: options["args"] = [] if "--headless" not in options["args"]: options["args"].append("--headless") options["prefs"] = { "network.dns.localDomains": ",".join(server_config.domains_set) } capabilities["moz:firefoxOptions"] = options if kwargs["certutil_binary"] is None: capabilities["acceptInsecureCerts"] = True if capabilities: executor_kwargs["capabilities"] = capabilities executor_kwargs["debug"] = run_info_data["debug"] executor_kwargs["ccov"] = run_info_data.get("ccov", False) return executor_kwargs def env_extras(**kwargs): return [] def env_options(): # The server host is set to 127.0.0.1 as Firefox is configured (through the # network.dns.localDomains preference set below) to resolve the test # domains to localhost without relying on the network stack. # # https://github.com/web-platform-tests/wpt/pull/9480 return {"server_host": "127.0.0.1", "bind_address": False, "supports_debugger": True} def run_info_extras(**kwargs): def get_bool_pref(pref): for key, value in kwargs.get('extra_prefs', []): if pref == key: return value.lower() in ('true', '1') return False return {"e10s": kwargs["gecko_e10s"], "wasm": kwargs.get("wasm", True), "verify": kwargs["verify"], "headless": "MOZ_HEADLESS" in os.environ, "sw-e10s": get_bool_pref("dom.serviceWorkers.parent_intercept"),} def update_properties(): return (["debug", "webrender", "e10s", "os", "version", "processor", "bits"], {"debug", "e10s", "webrender"}) class FirefoxBrowser(Browser): used_ports = set() init_timeout = 70 shutdown_timeout = 70 def __init__(self, logger, binary, prefs_root, test_type, extra_prefs=None, debug_info=None, symbols_path=None, stackwalk_binary=None, certutil_binary=None, ca_certificate_path=None, e10s=False, stackfix_dir=None, binary_args=None, timeout_multiplier=None, leak_check=False, asan=False, stylo_threads=1, chaos_mode_flags=None, config=None, headless=None, **kwargs): Browser.__init__(self, logger) self.binary = binary self.prefs_root = prefs_root self.test_type = test_type self.extra_prefs = extra_prefs self.marionette_port = None self.runner = None self.debug_info = debug_info self.profile = None self.symbols_path = symbols_path self.stackwalk_binary = stackwalk_binary self.ca_certificate_path = ca_certificate_path self.certutil_binary = certutil_binary self.e10s = e10s self.binary_args = binary_args self.config = config if stackfix_dir: self.stack_fixer = get_stack_fixer_function(stackfix_dir, self.symbols_path) else: self.stack_fixer = None if timeout_multiplier: self.init_timeout = self.init_timeout * timeout_multiplier self.asan = asan self.lsan_allowed = None self.lsan_max_stack_depth = None self.leak_check = leak_check self.leak_report_file = None self.lsan_handler = None self.stylo_threads = stylo_threads self.chaos_mode_flags = chaos_mode_flags self.headless = headless def settings(self, test): self.lsan_allowed = test.lsan_allowed self.lsan_max_stack_depth = test.lsan_max_stack_depth return {"check_leaks": self.leak_check and not test.leaks, "lsan_allowed": test.lsan_allowed} def start(self, group_metadata=None, **kwargs): if group_metadata is None: group_metadata = {} if self.marionette_port is None: self.marionette_port = get_free_port(2828, exclude=self.used_ports) self.used_ports.add(self.marionette_port) if self.asan: print "Setting up LSAN" self.lsan_handler = mozleak.LSANLeaks(self.logger, scope=group_metadata.get("scope", "/"), allowed=self.lsan_allowed, maxNumRecordedFrames=self.lsan_max_stack_depth) env = test_environment(xrePath=os.path.dirname(self.binary), debugger=self.debug_info is not None, log=self.logger, lsanPath=self.prefs_root) env["STYLO_THREADS"] = str(self.stylo_threads) if self.chaos_mode_flags is not None: env["MOZ_CHAOSMODE"] = str(self.chaos_mode_flags) if self.headless: env["MOZ_HEADLESS"] = "1" preferences = self.load_prefs() self.profile = FirefoxProfile(preferences=preferences) self.profile.set_preferences({ "marionette.port": self.marionette_port, "network.dns.localDomains": ",".join(self.config.domains_set), # TODO: Remove preferences once Firefox 64 is stable (Bug 905404) "network.proxy.type": 0, "places.history.enabled": False, "network.preload": True, }) if self.e10s: self.profile.set_preferences({"browser.tabs.remote.autostart": True}) if self.test_type == "reftest": self.profile.set_preferences({"layout.interruptible-reflow.enabled": False}) if self.leak_check: self.leak_report_file = os.path.join(self.profile.profile, "runtests_leaks_%s.log" % os.getpid()) if os.path.exists(self.leak_report_file): os.remove(self.leak_report_file) env["XPCOM_MEM_BLOAT_LOG"] = self.leak_report_file else: self.leak_report_file = None # Bug 1262954: winxp + e10s, disable hwaccel if (self.e10s and platform.system() in ("Windows", "Microsoft") and '5.1' in platform.version()): self.profile.set_preferences({"layers.acceleration.disabled": True}) if self.ca_certificate_path is not None: self.setup_ssl() args = self.binary_args[:] if self.binary_args else [] args += [cmd_arg("marionette"), "about:blank"] debug_args, cmd = browser_command(self.binary, args, self.debug_info) self.runner = FirefoxRunner(profile=self.profile, binary=cmd[0], cmdargs=cmd[1:], env=env, process_class=ProcessHandler, process_args={"processOutputLine": [self.on_output]}) self.logger.debug("Starting Firefox") self.runner.start(debug_args=debug_args, interactive=self.debug_info and self.debug_info.interactive) self.logger.debug("Firefox Started") def load_prefs(self): prefs = Preferences() pref_paths = [] profiles = os.path.join(self.prefs_root, 'profiles.json') if os.path.isfile(profiles): with open(profiles, 'r') as fh: for name in json.load(fh)['web-platform-tests']: pref_paths.append(os.path.join(self.prefs_root, name, 'user.js')) else: # Old preference files used before the creation of profiles.json (remove when no longer supported) legacy_pref_paths = ( os.path.join(self.prefs_root, 'prefs_general.js'), # Used in Firefox 60 and below os.path.join(self.prefs_root, 'common', 'user.js'), # Used in Firefox 61 ) for path in legacy_pref_paths: if os.path.isfile(path): pref_paths.append(path) for path in pref_paths: if os.path.exists(path): prefs.add(Preferences.read_prefs(path)) else: self.logger.warning("Failed to find base prefs file in %s" % path) # Add any custom preferences prefs.add(self.extra_prefs, cast=True) return prefs() def stop(self, force=False): if self.runner is not None and self.runner.is_running(): try: # For Firefox we assume that stopping the runner prompts the # browser to shut down. This allows the leak log to be written for clean, stop_f in [(True, lambda: self.runner.wait(self.shutdown_timeout)), (False, lambda: self.runner.stop(signal.SIGTERM)), (False, lambda: self.runner.stop(signal.SIGKILL))]: if not force or not clean: retcode = stop_f() if retcode is not None: self.logger.info("Browser exited with return code %s" % retcode) break except OSError: # This can happen on Windows if the process is already dead pass self.process_leaks() self.logger.debug("stopped") def process_leaks(self): self.logger.debug("PROCESS LEAKS %s" % self.leak_report_file) if self.lsan_handler: self.lsan_handler.process() if self.leak_report_file is not None: mozleak.process_leak_log( self.leak_report_file, leak_thresholds={ "default": 0, "tab": 10000, # See dependencies of bug 1051230. # GMP rarely gets a log, but when it does, it leaks a little. "geckomediaplugin": 20000, }, ignore_missing_leaks=["geckomediaplugin"], log=self.logger, stack_fixer=self.stack_fixer ) def pid(self): if self.runner.process_handler is None: return None try: return self.runner.process_handler.pid except AttributeError: return None def on_output(self, line): """Write a line of output from the firefox process to the log""" if "GLib-GObject-CRITICAL" in line: return if line: data = line.decode("utf8", "replace") if self.stack_fixer: data = self.stack_fixer(data) if self.lsan_handler: data = self.lsan_handler.log(data) if data is not None: self.logger.process_output(self.pid(), data, command=" ".join(self.runner.command)) def is_alive(self): if self.runner: return self.runner.is_running() return False def cleanup(self, force=False): self.stop(force) def executor_browser(self): assert self.marionette_port is not None return ExecutorBrowser, {"marionette_port": self.marionette_port} def check_for_crashes(self): dump_dir = os.path.join(self.profile.profile, "minidumps") return bool(mozcrash.check_for_crashes(dump_dir, symbols_path=self.symbols_path, stackwalk_binary=self.stackwalk_binary, quiet=True)) def log_crash(self, process, test): dump_dir = os.path.join(self.profile.profile, "minidumps") mozcrash.log_crashes(self.logger, dump_dir, symbols_path=self.symbols_path, stackwalk_binary=self.stackwalk_binary, process=process, test=test) def setup_ssl(self): """Create a certificate database to use in the test profile. This is configured to trust the CA Certificate that has signed the web-platform.test server certificate.""" if self.certutil_binary is None: self.logger.info("--certutil-binary not supplied; Firefox will not check certificates") return self.logger.info("Setting up ssl") # Make sure the certutil libraries from the source tree are loaded when using a # local copy of certutil # TODO: Maybe only set this if certutil won't launch? env = os.environ.copy() certutil_dir = os.path.dirname(self.binary or self.certutil_binary) if mozinfo.isMac: env_var = "DYLD_LIBRARY_PATH" elif mozinfo.isUnix: env_var = "LD_LIBRARY_PATH" else: env_var = "PATH" env[env_var] = (os.path.pathsep.join([certutil_dir, env[env_var]]) if env_var in env else certutil_dir).encode( sys.getfilesystemencoding() or 'utf-8', 'replace') def certutil(*args): cmd = [self.certutil_binary] + list(args) self.logger.process_output("certutil", subprocess.check_output(cmd, env=env, stderr=subprocess.STDOUT), " ".join(cmd)) pw_path = os.path.join(self.profile.profile, ".crtdbpw") with open(pw_path, "w") as f: # Use empty password for certificate db f.write("\n") cert_db_path = self.profile.profile # Create a new certificate db certutil("-N", "-d", cert_db_path, "-f", pw_path) # Add the CA certificate to the database and mark as trusted to issue server certs certutil("-A", "-d", cert_db_path, "-f", pw_path, "-t", "CT,,", "-n", "web-platform-tests", "-i", self.ca_certificate_path) # List all certs in the database certutil("-L", "-d", cert_db_path)
mpl-2.0
emlai/wge3
desktop/src/wge3/game/desktop/DesktopLauncher.java
819
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package wge3.game.desktop; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import wge3.engine.WGE3; public class DesktopLauncher { public static void main (String[] arg) { LwjglApplicationConfiguration cfg = new LwjglApplicationConfiguration(); cfg.width = 1280; cfg.height = 720; //cfg.fullscreen = true; cfg.resizable = false; cfg.title = "WGE3"; cfg.useGL30 = false; LwjglApplication game = new LwjglApplication(new WGE3(), cfg); } }
mpl-2.0
itesla/ipst
modelica-export/src/main/java/eu/itesla_project/modelica_export/util/eurostag/EurostagFixedData.java
9893
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.modelica_export.util.eurostag; import java.util.Arrays; import java.util.List; /** * @author Silvia Machado <[email protected]> */ public final class EurostagFixedData { ///Según la API de IIDM dan por supuesto que la potencia nominal es 100 public static final String PARAMETER = "parameter"; public static final String OMEGAREF_NAME = "omegaRef"; public static final String ANNOT = ") annotation (Placement(transformation()));"; public static final String ANNOT_CONNECT = ") annotation (Line());"; public static final String CONNECT = "connect("; public static final String HIN_PIN = "SN"; public static final String SN_PIN = "HIn"; public static final String OMEGA_PIN = "omega"; public static final String GEN_SORTIE_PIN = "sortie"; public static final String GEN_OMEGAREF_PIN = "omegaRef"; /** * Data about generators with transformer included */ public static final String TRAFO_INCLUDED = "T"; public static final String TRAFO_NOT_INCLUDED = "N"; public static final String IS_SATURATED = "S"; public static final String IS_UNSATURATED = "U"; public static final List<String> TRAFO_GEN_PARAMS = Arrays.asList(new String[]{"V1", "V2", "U1N", "U2N", "SNtfo", "RTfoPu", "XTfoPu"}); public static final List<String> MACHINE_INIT_PAR = Arrays.asList(new String[]{"lambdaF0", "lambdaD0", "lambdaAD0", "lambdaAQ0", "lambdaQ10", "lambdaQ20", "iD0", "iQ0", "teta0", "omega_0", "cm0", "efd0", "mDVPu"}); public static final List<String> MACHINE_PAR = Arrays.asList(new String[]{"init_lambdaf", "init_lambdad", "init_lambdaad", "init_lambdaaq", "init_lambdaq1", "init_lambdaq2", "init_id", "init_iq", "init_theta", "init_omega", "init_cm", "init_efd", "WLMDVPu"}); public static final List<String> SATURATED_MACHINE = Arrays.asList(new String[]{"snq", "snd", "mq", "md"}); /** * MODELICA PARAMETER NAMES */ public static final String UR0 = "ur0"; public static final String UI0 = "ui0"; public static final String V_0 = "V_0"; public static final String ANGLE_0 = "angle_0"; public static final String VO_REAL = "Vo_real"; public static final String VO_IMG = "Vo_img"; public static final String P = "P"; public static final String Q = "Q"; public static final String SNOM = "Snom"; public static final String PCU = "Pcu"; public static final String PFE = "Pfe"; public static final String IM = "IM"; public static final String B0 = "B0"; public static final String G0 = "G0"; public static final String V1 = "V1"; public static final String V2 = "V2"; public static final String U1N = "U1N"; public static final String U2N = "U2N"; public static final String U1_NOM = "U1nom"; @SuppressWarnings("checkstyle:constantname") @Deprecated public static final String U1nom = U1_NOM; public static final String U2_NOM = "U2nom"; @SuppressWarnings("checkstyle:constantname") @Deprecated public static final String U2nom = U2_NOM; public static final String UCC = "Ucc"; public static final String THETA = "theta"; public static final String ESAT = "ESAT"; public static final String R = "R"; public static final String X = "X"; public static final String G = "G"; public static final String B = "B"; @SuppressWarnings("checkstyle:constantname") public static final String r = "r"; public static final String ALPHA = "alpha"; public static final String BETA = "beta"; public static final String TRAFOINCLUDED = "transformerIncluded"; public static final String SATURATED = "Saturated"; public static final String INLMDV = "IWLMDV"; public static final String TX = "TX"; public static final String XD = "XD"; public static final String XPD = "XPD"; public static final String XSD = "XSD"; public static final String TPD0 = "TPD0"; public static final String TSD0 = "TSD0"; public static final String XQ = "XQ"; public static final String XPQ = "XPQ"; public static final String XSQ = "XSQ"; public static final String TPQ0 = "TPQ0"; public static final String TSQ0 = "TSQ0"; public static final String IENR = "IENR"; public static final String SNTFO = "SNtfo"; public static final String SN = "SN"; public static final String RTFOPU = "RTfoPu"; public static final String XTFOPU = "XTfoPu"; public static final String SND = "snd"; public static final String SNQ = "snq"; public static final String MD = "md"; public static final String MQ = "mq"; public static final String RSTATIN = "rStatIn"; public static final String LSTATIN = "lStatIn"; public static final String MQ0PU = "mQ0Pu"; public static final String MD0PU = "mD0Pu"; public static final String PN = "PN"; public static final String LDPU = "lDPu"; public static final String RROTIN = "rRotIn"; public static final String LROTIN = "lRotIn"; public static final String RQ1PU = "rQ1Pu"; public static final String LQ1PU = "lQ1Pu"; public static final String RQ2PU = "rQ2Pu"; public static final String LQ2PU = "lQ2Pu"; public static final String MCANPU = "mCanPu"; public static final String PNALT = "PNALT"; //M1S & M2S INIT public static final String INIT_SNREF = "SNREF"; public static final String INIT_SN = "SN"; public static final String INIT_PN = "PN"; public static final String INIT_PNALT = "PNALT"; public static final String INIT_SNTFO = "sNTfo"; public static final String INIT_UR0 = "ur0"; public static final String INIT_UI0 = "ui0"; public static final String INIT_P0 = "p0"; public static final String INIT_Q0 = "q0"; public static final String INIT_UNRESTFO = "uNResTfo"; public static final String INIT_UNOMNW = "uNomNw"; public static final String INIT_UNMACTFO = "uNMacTfo"; public static final String INIT_UBMAC = "uBMac"; public static final String INIT_RTFOIN = "rTfoIn"; public static final String INIT_XTFOIN = "xTfoIn"; public static final String INIT_NDSAT = "nDSat"; public static final String INIT_NQSAT = "nQSat"; public static final String INIT_MDSATIN = "mDSatIn"; public static final String INIT_MQSATIN = "mQSatIn"; public static final String INIT_RSTATIN = "rStatIn"; public static final String INIT_LSTATIN = "lStatIn"; public static final String INIT_MD0PU = "mD0Pu"; public static final String INIT_PNOM = "pNom"; public static final String INIT_OMEGA0 = "omega_0"; public static final String INIT_PPUWLMDV = "pPuWLMDV"; public static final String INIT_IENR = "IENR"; //M1S INIT public static final String INIT_MQ0PU = "mQ0Pu"; public static final String INIT_LDPU = "lDPu"; public static final String INIT_RROTIN = "rRotIn"; public static final String INIT_LROTIN = "lRotIn"; public static final String INIT_RQ1PU = "rQ1Pu"; public static final String INIT_LQ1PU = "lQ1Pu"; public static final String INIT_RQ2PU = "rQ2Pu"; public static final String INIT_LQ2PU = "lQ2Pu"; public static final String INIT_MCANPU = "mCanPu"; //M2S INIT public static final String INIT_XD = "XD"; public static final String INIT_XSD = "XSD"; public static final String INIT_XPD = "XPD"; public static final String INIT_TPDO = "TPD0"; public static final String INIT_TSDO = "TSD0"; public static final String INIT_XQ = "XQ"; public static final String INIT_XPQ = "XPQ"; public static final String INIT_XSQ = "XSQ"; public static final String INIT_TPQO = "TPQ0"; public static final String INIT_TSQO = "TSQ0"; public static final String INIT_TX = "TX"; public static final String NSTEPS = "nsteps"; public static final String BO = "Bo"; public static final String OPENR = "OpenR_end"; private EurostagFixedData() { } }
mpl-2.0
brave/publishers
app/services/promo/unattached_registrar.rb
1393
# Registers infinity codes for a Brave admin class Promo::UnattachedRegistrar < BaseApiClient include PromosHelper def initialize(number:, promo_id: active_promo_id, campaign: nil) @number = number @promo_id = promo_id @campaign = campaign end def perform return if @number <= 0 return perform_offline if perform_promo_offline? response = connection.put do |request| request.headers["Authorization"] = api_authorization_header request.headers["Content-Type"] = "application/json" request.url("/api/2/promo/referral_code/unattached?number=#{@number}") end promo_registrations = JSON.parse(response.body) promo_registrations.each do |promo_registration| PromoRegistration.create!( referral_code: promo_registration["referral_code"], promo_id: active_promo_id, kind: PromoRegistration::UNATTACHED, promo_campaign: @campaign ) end end def perform_offline @number.times do PromoRegistration.create!( referral_code: offline_referral_code, promo_id: active_promo_id, kind: PromoRegistration::UNATTACHED, promo_campaign: @campaign ) end end private def api_base_uri Rails.application.secrets[:api_promo_base_uri] end def api_authorization_header "Bearer #{Rails.application.secrets[:api_promo_key]}" end end
mpl-2.0
caterinaurban/Lyra
src/lyra/unittests/numerical/interval/forward/outside.py
124
def f(x: int) -> int: return x + b a: int = 3 b: int = 4 c: int = f(a) # FINAL: a -> [3, 3]; b -> [4, 4]; c -> [7, 7]
mpl-2.0
wl1244hotmai/BLE-Mesh
sdk/src/main/java/sword/blemesh/sdk/transport/ble/BLETransportCallback.java
906
package sword.blemesh.sdk.transport.ble; import java.util.Map; import sword.blemesh.sdk.transport.Transport; /** * Created by davidbrodsky on 2/23/15. */ public interface BLETransportCallback { public static enum DeviceType {GATT, GATT_SERVER} public void dataReceivedFromIdentifier(DeviceType deviceType, byte[] data, String identifier); public void dataSentToIdentifier(DeviceType deviceType, byte[] data, String identifier, Exception e); public void identifierUpdated(DeviceType deviceType, String identifier, Transport.ConnectionStatus status, Map<String, Object> extraInfo); }
mpl-2.0
etomica/etomica
etomica-core/src/main/java/etomica/units/dimensions/Energy.java
1287
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.units.dimensions; import java.io.ObjectStreamException; import etomica.units.Prefix; import etomica.units.SimpleUnit; import etomica.units.Unit; import etomica.units.systems.UnitSystem; /** * Dimension for all energy units. Simulation unit of energy is D-A^2/ps^2 */ public final class Energy extends Dimension { /** * Singleton instance of this class. */ public static final Dimension DIMENSION = new Energy(); /** * The simulation unit of energy is D-A^2/ps^2. */ public static final Unit SIM_UNIT = new SimpleUnit(DIMENSION, 1.0, "sim energy units", "D-A^2/ps^2", Prefix.NOT_ALLOWED); private Energy() { super("Energy", 2, 1, -2); } public Unit getUnit(UnitSystem unitSystem) { return unitSystem.energy(); } /** * Required to guarantee singleton when deserializing. * * @return the singleton DIMENSION */ private Object readResolve() throws ObjectStreamException { return DIMENSION; } private static final long serialVersionUID = 1; }
mpl-2.0
mssavai/muzima-api
src/main/java/com/muzima/api/service/PatientService.java
9687
/* * Copyright (c) 2014. The Trustees of Indiana University. * * This version of the code is licensed under the MPL 2.0 Open Source license with additional * healthcare disclaimer. If the user is an entity intending to commercialize any application * that uses this code in a for-profit venture, please contact the copyright holder. */ package com.muzima.api.service; import com.google.inject.ImplementedBy; import com.muzima.api.model.CohortMember; import com.muzima.api.model.Patient; import com.muzima.api.service.impl.PatientServiceImpl; import org.apache.lucene.queryParser.ParseException; import java.io.IOException; import java.util.List; /** * Service handling all operation to the @{Patient} actor/model * <p/> * TODO: add ability to search based on lucene like query syntax (merging name and identifier). */ @ImplementedBy(PatientServiceImpl.class) public interface PatientService extends MuzimaInterface { /** * Download a single patient record from the patient rest resource into the local lucene repository. * * @param uuid the uuid of the patient. * @throws IOException when search api unable to process the resource. * @should download patient with matching uuid. */ Patient downloadPatientByUuid(final String uuid) throws IOException; /** * Download all patients with name similar to the partial name passed in the parameter. * * @param name the partial name of the patient to be downloaded. When empty, will return all patients available. * @throws IOException when search api unable to process the resource. * @should download all patient with partially matched name. */ List<Patient> downloadPatientsByName(final String name) throws IOException; Patient consolidateTemporaryPatient(final String temporaryUuid) throws IOException; Patient consolidateTemporaryPatient(final Patient temporaryPatient) throws IOException; /** * Save patient to the local lucene repository. * * @param patient the patient to be saved. * @throws IOException when search api unable to process the resource. * @should save patient to local data repository. */ Patient savePatient(final Patient patient) throws IOException; /** * Save patients to the local lucene repository. * * @param patients the patients to be saved. * @throws IOException when search api unable to process the resource. * @should save patients to local data repository. */ void savePatients(final List<Patient> patients) throws IOException; /** * Update patient in the local lucene repository. * * @param patient the patient to be updated. * @throws IOException when search api unable to process the resource. * @should replace existing patient in local data repository. */ void updatePatient(final Patient patient) throws IOException; /** * Update patients in the local lucene repository. * * @param patients the patients to be updated. * @throws IOException when search api unable to process the resource. * @should replace existing patients in local data repository. */ void updatePatients(final List<Patient> patients) throws IOException; /** * Get a single patient record from the local repository with matching uuid. * * @param uuid the patient uuid * @return patient with matching uuid or null when no patient match the uuid * @throws IOException when search api unable to process the resource. * @should return patient with matching uuid * @should return null when no patient match the uuid */ Patient getPatientByUuid(final String uuid) throws IOException; /** * Get patient by the identifier of the patient. * * @param identifier the patient identifier. * @return patient with matching identifier or null when no patient match the identifier. * @throws IOException when search api unable to process the resource. * @should return patient with matching identifier. * @should return null when no patient match the identifier. */ Patient getPatientByIdentifier(final String identifier) throws IOException; /** * Count all patient objects. * * @return the total number of patient objects. * @throws IOException when search api unable to process the resource. */ Integer countAllPatients() throws IOException; /** * Count all patient objects in cohort. * * @return the total number of patient objects. * @throws IOException when search api unable to process the resource. */ Integer countPatients(final String cohortUuid) throws IOException; /** * Get all saved patients in the local repository. * * @return all registered patients or empty list when no patient is registered. * @throws IOException when search api unable to process the resource. * @should return all registered patients. * @should return empty list when no patient is registered. */ List<Patient> getAllPatients() throws IOException; /** * Get all saved patients in the local repository, of the specified page and page size * * @param page the page number * @param pageSize the number of patients per page. * * @return all registered patients or empty list when no patient is registered. * @throws IOException when search api unable to process the resource. * @should return all registered patients. * @should return empty list when no patient is registered. */ List<Patient> getPatients(final Integer page, final Integer pageSize) throws IOException; /** * Get all saved patients in cohort in the local repository, of the specified page and page size * * @param cohortUuid the cohort ID * @param page the page number * @param pageSize the number of patients per page. * * @return all registered patients or empty list when no patient is registered. * @throws IOException when search api unable to process the resource. * @should return all registered patients. * @should return empty list when no patient is registered. */ List<Patient> getPatients(final String cohortUuid, final Integer page, final Integer pageSize) throws IOException; /** * Get list of patients with name similar to the search term. * * @param name the patient name. * @return list of all patients with matching name or empty list when no patient match the name. * @throws ParseException when query parser from lucene unable to parse the query string. * @throws IOException when search api unable to process the resource. * @should return list of all patients with matching name partially. * @should return empty list when no patient match the name. */ List<Patient> getPatientsByName(final String name) throws IOException, ParseException; /** * Search for patients with matching characteristic on the name or identifier with the search term. * * @param term the search term. * @return list of all patients with matching search term on the searchable fields or empty list. * @throws ParseException when query parser from lucene unable to parse the query string. * @throws IOException when search api unable to process the resource. * @should return list of all patients with matching search term. * @should return empty list when no patient match the search term. */ List<Patient> searchPatients(final String term) throws IOException, ParseException; List<Patient> searchPatients(final String term, final Integer page, final Integer pageSize) throws IOException, ParseException; /** * Search for patients with matching characteristic on the name or identifier with the search term, within the give cohort. * * @param term the search term * @param cohortUuid the Uuid of the cohort, only patients within the cohort will be searched * @return list of all patients in the cohort with matching search term on the searchable fields or empty list. * @throws ParseException when query parser from lucene unable to parse the query string. * @throws IOException when search api unable to process the resource. * @should return list of all patients in cohort with matching search term. * @should return empty list when no patient match the search term. */ List<Patient> searchPatients(final String term, final String cohortUuid) throws IOException, ParseException; /** * Delete a single patient object from the local repository. * * @param patient the patient object. * @throws IOException when search api unable to process the resource. * @should delete the patient object from the local repository. */ void deletePatient(final Patient patient) throws IOException; /** * Delete patient objects from the local repository. * * @param patients the patient objects. * @throws IOException when search api unable to process the resource. * @should delete the patient object from the local repository. */ void deletePatients(final List<Patient> patients) throws IOException; /** * @return List of patients that are not a part of any cohort. */ List<Patient> getPatientsNotInCohorts() throws IOException; List<Patient> getPatientsFromCohortMembers(List<CohortMember> cohortMembers); }
mpl-2.0
andreadanzi/rotho_dev
modules/Rumors/ProductToRumors.js
1032
function return_product_to_rumors(recordid,value,target_fieldname,product_cat,link_to_description,link_to_category_descr) { var formName = getReturnFormName(); var form = getReturnForm(formName); if (form) { var domnode_id = form.elements[target_fieldname]; var domnode_display = form.elements[target_fieldname+'_display']; if(domnode_id) domnode_id.value = recordid; if(domnode_display) domnode_display.value = value; disableReferenceField(domnode_display,domnode_id,form.elements[target_fieldname+'_mass_edit_check']); //crmv@29190 if (enableAdvancedFunction(form)) { if (form.elements['product_cat']) { form.elements['product_cat'].value = product_cat; } if (form.elements['product_desc']) { form.elements['product_desc'].value = link_to_description; } // danzi.tn@20140225 aggiunto descrizione categoria category_descr if (form.elements['product_cat_descr']) { form.elements['product_cat_descr'].value = link_to_category_descr; } } return true; } else { return false; } }
mpl-2.0
susaing/doc.servo.org
servo/script/dom/xmlhttprequest/sidebar-items.js
152
initSidebarItems({"enum":[["XHRProgress",""]],"struct":[["GenerationId",""],["XMLHttpRequest",""]],"type":[["SendParam",""],["TrustedXHRAddress",""]]});
mpl-2.0
n0max/servo
components/script/dom/htmlstyleelement.rs
9428
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use cssparser::{Parser as CssParser, ParserInput}; use dom::bindings::cell::DomRefCell; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding; use dom::bindings::codegen::Bindings::HTMLStyleElementBinding::HTMLStyleElementMethods; use dom::bindings::codegen::Bindings::NodeBinding::NodeMethods; use dom::bindings::inheritance::Castable; use dom::bindings::root::{DomRoot, MutNullableDom}; use dom::cssstylesheet::CSSStyleSheet; use dom::document::Document; use dom::element::{Element, ElementCreator}; use dom::eventtarget::EventTarget; use dom::htmlelement::HTMLElement; use dom::node::{ChildrenMutation, Node, UnbindContext, document_from_node, window_from_node}; use dom::stylesheet::StyleSheet as DOMStyleSheet; use dom::virtualmethods::VirtualMethods; use dom_struct::dom_struct; use html5ever::{LocalName, Prefix}; use net_traits::ReferrerPolicy; use servo_arc::Arc; use std::cell::Cell; use style::media_queries::parse_media_query_list; use style::parser::ParserContext as CssParserContext; use style::stylesheets::{CssRuleType, Stylesheet, Origin}; use style_traits::PARSING_MODE_DEFAULT; use stylesheet_loader::{StylesheetLoader, StylesheetOwner}; #[dom_struct] pub struct HTMLStyleElement { htmlelement: HTMLElement, #[ignore_malloc_size_of = "Arc"] stylesheet: DomRefCell<Option<Arc<Stylesheet>>>, cssom_stylesheet: MutNullableDom<CSSStyleSheet>, /// <https://html.spec.whatwg.org/multipage/#a-style-sheet-that-is-blocking-scripts> parser_inserted: Cell<bool>, in_stack_of_open_elements: Cell<bool>, pending_loads: Cell<u32>, any_failed_load: Cell<bool>, line_number: u64, } impl HTMLStyleElement { fn new_inherited(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> HTMLStyleElement { HTMLStyleElement { htmlelement: HTMLElement::new_inherited(local_name, prefix, document), stylesheet: DomRefCell::new(None), cssom_stylesheet: MutNullableDom::new(None), parser_inserted: Cell::new(creator.is_parser_created()), in_stack_of_open_elements: Cell::new(creator.is_parser_created()), pending_loads: Cell::new(0), any_failed_load: Cell::new(false), line_number: creator.return_line_number(), } } #[allow(unrooted_must_root)] pub fn new(local_name: LocalName, prefix: Option<Prefix>, document: &Document, creator: ElementCreator) -> DomRoot<HTMLStyleElement> { Node::reflect_node(Box::new(HTMLStyleElement::new_inherited(local_name, prefix, document, creator)), document, HTMLStyleElementBinding::Wrap) } pub fn parse_own_css(&self) { let node = self.upcast::<Node>(); let element = self.upcast::<Element>(); assert!(node.is_in_doc()); let window = window_from_node(node); let doc = document_from_node(self); let mq_attribute = element.get_attribute(&ns!(), &local_name!("media")); let mq_str = match mq_attribute { Some(a) => String::from(&**a.value()), None => String::new(), }; let data = node.GetTextContent().expect("Element.textContent must be a string"); let url = window.get_url(); let context = CssParserContext::new_for_cssom(&url, Some(CssRuleType::Media), PARSING_MODE_DEFAULT, doc.quirks_mode()); let shared_lock = node.owner_doc().style_shared_lock().clone(); let mut input = ParserInput::new(&mq_str); let css_error_reporter = window.css_error_reporter(); let mq = Arc::new(shared_lock.wrap(parse_media_query_list(&context, &mut CssParser::new(&mut input), css_error_reporter))); let loader = StylesheetLoader::for_element(self.upcast()); let sheet = Stylesheet::from_str(&data, window.get_url(), Origin::Author, mq, shared_lock, Some(&loader), css_error_reporter, doc.quirks_mode(), self.line_number as u32); let sheet = Arc::new(sheet); // No subresource loads were triggered, just fire the load event now. if self.pending_loads.get() == 0 { self.upcast::<EventTarget>().fire_event(atom!("load")); } self.set_stylesheet(sheet); } // FIXME(emilio): This is duplicated with HTMLLinkElement::set_stylesheet. pub fn set_stylesheet(&self, s: Arc<Stylesheet>) { let doc = document_from_node(self); if let Some(ref s) = *self.stylesheet.borrow() { doc.remove_stylesheet(self.upcast(), s) } *self.stylesheet.borrow_mut() = Some(s.clone()); self.cssom_stylesheet.set(None); doc.add_stylesheet(self.upcast(), s); } pub fn get_stylesheet(&self) -> Option<Arc<Stylesheet>> { self.stylesheet.borrow().clone() } pub fn get_cssom_stylesheet(&self) -> Option<DomRoot<CSSStyleSheet>> { self.get_stylesheet().map(|sheet| { self.cssom_stylesheet.or_init(|| { CSSStyleSheet::new(&window_from_node(self), self.upcast::<Element>(), "text/css".into(), None, // todo handle location None, // todo handle title sheet) }) }) } } impl VirtualMethods for HTMLStyleElement { fn super_type(&self) -> Option<&VirtualMethods> { Some(self.upcast::<HTMLElement>() as &VirtualMethods) } fn children_changed(&self, mutation: &ChildrenMutation) { self.super_type().unwrap().children_changed(mutation); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and one of its child nodes is modified by a script." // TODO: Handle Text child contents being mutated. if self.upcast::<Node>().is_in_doc() && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn bind_to_tree(&self, tree_in_doc: bool) { self.super_type().unwrap().bind_to_tree(tree_in_doc); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is not on the stack of open elements of an HTML parser or XML parser, // and it becomes connected or disconnected." if tree_in_doc && !self.in_stack_of_open_elements.get() { self.parse_own_css(); } } fn pop(&self) { self.super_type().unwrap().pop(); // https://html.spec.whatwg.org/multipage/#update-a-style-block // Handles the case when: // "The element is popped off the stack of open elements of an HTML parser or XML parser." self.in_stack_of_open_elements.set(false); if self.upcast::<Node>().is_in_doc() { self.parse_own_css(); } } fn unbind_from_tree(&self, context: &UnbindContext) { if let Some(ref s) = self.super_type() { s.unbind_from_tree(context); } if context.tree_in_doc { if let Some(s) = self.stylesheet.borrow_mut().take() { document_from_node(self).remove_stylesheet(self.upcast(), &s) } } } } impl StylesheetOwner for HTMLStyleElement { fn increment_pending_loads_count(&self) { self.pending_loads.set(self.pending_loads.get() + 1) } fn load_finished(&self, succeeded: bool) -> Option<bool> { assert!(self.pending_loads.get() > 0, "What finished?"); if !succeeded { self.any_failed_load.set(true); } self.pending_loads.set(self.pending_loads.get() - 1); if self.pending_loads.get() != 0 { return None; } let any_failed = self.any_failed_load.get(); self.any_failed_load.set(false); Some(any_failed) } fn parser_inserted(&self) -> bool { self.parser_inserted.get() } fn referrer_policy(&self) -> Option<ReferrerPolicy> { None } fn set_origin_clean(&self, origin_clean: bool) { if let Some(stylesheet) = self.get_cssom_stylesheet() { stylesheet.set_origin_clean(origin_clean); } } } impl HTMLStyleElementMethods for HTMLStyleElement { // https://drafts.csswg.org/cssom/#dom-linkstyle-sheet fn GetSheet(&self) -> Option<DomRoot<DOMStyleSheet>> { self.get_cssom_stylesheet().map(DomRoot::upcast) } }
mpl-2.0
klahnakoski/jx-sqlite
vendor/jx_python/expressions/in_op.py
613
# encoding: utf-8 # # # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http:# mozilla.org/MPL/2.0/. # # Contact: Kyle Lahnakoski ([email protected]) # from __future__ import absolute_import, division, unicode_literals from jx_base.expressions import InOp as InOp_ from jx_python.expressions._utils import Python class InOp(InOp_): def to_python(self, not_null=False, boolean=False, many=False): return (self.value).to_python() + " in " + (self.superset).to_python(many=True)
mpl-2.0
ajschult/etomica
etomica-core/src/main/java/etomica/data/types/CastGroupOfTablesToDataTable.java
5215
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.data.types; import etomica.data.DataPipe; import etomica.data.DataProcessor; import etomica.data.IData; import etomica.data.IEtomicaDataInfo; import etomica.data.types.DataDoubleArray.DataInfoDoubleArray; import etomica.data.types.DataGroup.DataInfoGroup; import etomica.data.types.DataTable.DataInfoTable; import etomica.util.Arrays; /** * A DataProcessor that converts a homogeneous DataGroup into a multidimensional DataDoubleArray. * All elements in group must be of the same data type. If the group contains only one element, * the effect is the same as applying CastToDoubleArray to the element. Otherwise, if <tt>d</tt> * is the dimension of each grouped element, the resulting DataDoubleArray will be of * dimension <tt>d+1</tt>. The added dimension corresponds to the different elements of the group. * <p> * For example: * <ul> * <li>if the DataGroup contains 8 DataDouble instances (thus d = 0), the cast gives a * one-dimensional DataDoubleArray of length 8. * <li>if the DataGroup contains 4 Vector3D instances (thus d = 1), the cast gives a two-dimensional DataDoubleArray * of dimensions (4, 3). * <li>if the DataGroup contains 5 two-dimensional (d = 2) DataDoubleArray of shape (7,80), the cast gives a * three-dimensional DataDoubleArray of shape (5, 7, 80). * </ul> * etc. * * @author David Kofke * */ public class CastGroupOfTablesToDataTable extends DataProcessor { /** * Sole constructor. */ public CastGroupOfTablesToDataTable() { } /** * Prepares processor to handle Data. Uses given DataInfo to determine the * type of Data to expect in subsequent calls to processData. * * @throws ClassCastException * if DataInfo does not indicate a DataGroup or its sub-groups * are not DataTables * * @throws IllegalArgumentException * if DataInfo indicates that the DataTables have different * numbers of rows */ protected IEtomicaDataInfo processDataInfo(IEtomicaDataInfo inputDataInfo) { if (!(inputDataInfo instanceof DataInfoGroup)) { throw new IllegalArgumentException("can only cast from DataGroup"); } DataInfoDoubleArray[] columnDataInfo = new DataInfoDoubleArray[0]; int nColumns = 0; int nRows = -1; String[] rowHeaders = null; for (int i = 0; i<((DataInfoGroup)inputDataInfo).getNDataInfo(); i++) { DataInfoTable elementDataInfo = (DataInfoTable)((DataInfoGroup)inputDataInfo).getSubDataInfo(i); columnDataInfo = (DataInfoDoubleArray[])Arrays.resizeArray(columnDataInfo, nColumns+elementDataInfo.getNDataInfo()); for (int j=nColumns; j<columnDataInfo.length; j++) { columnDataInfo[j] = (DataInfoDoubleArray)elementDataInfo.getSubDataInfo(j-nColumns); } nColumns = columnDataInfo.length; if (nRows > -1 && elementDataInfo.getNRows() != nRows) { throw new IllegalArgumentException("all columns must have an equal number of rows"); } nRows = elementDataInfo.getNRows(); if (rowHeaders == null && elementDataInfo.hasRowHeaders()) { rowHeaders = new String[nRows]; for (int j=0; j<nRows; j++) { rowHeaders[j] = elementDataInfo.getRowHeader(j); } } } outputData = null; outputDataInfo = new DataInfoTable(inputDataInfo.getLabel(), columnDataInfo, nRows, rowHeaders); return outputDataInfo; } /** * Converts data in given group to a DataDoubleArray as described in the * general comments for this class. * * @throws ClassCastException * if the given Data is not a DataGroup with Data elements of * the type indicated by the most recent call to * processDataInfo. */ protected IData processData(IData data) { if (outputData == null) { DataDoubleArray[] columns = new DataDoubleArray[outputDataInfo.getNDataInfo()]; int i=0; for (int j=0; j<((DataGroup)data).getNData(); j++) { for (int k=0; k<((DataTable)((DataGroup)data).getData(j)).getNData(); k++) { columns[i] = (DataDoubleArray)((DataTable)((DataGroup)data).getData(j)).getData(k); i++; } } outputData = new DataTable(columns); } return outputData; } /** * Returns null. */ public DataPipe getDataCaster(IEtomicaDataInfo info) { if (!(info instanceof DataInfoGroup)) { throw new IllegalArgumentException("can only cast from DataGroup"); } return null; } private static final long serialVersionUID = 1L; private DataTable outputData; private DataInfoTable outputDataInfo; }
mpl-2.0
ansp-2015/arquea
evento/migrations/0001_initial.py
4843
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('membro', '__first__'), ('outorga', '0002_auto_20150517_1724'), ] operations = [ migrations.CreateModel( name='AreaOperacional', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nome', models.CharField(max_length=50)), ], options={ 'verbose_name': '\xc1rea operacional', 'verbose_name_plural': '\xc1reas operacionais', }, bases=(models.Model,), ), migrations.CreateModel( name='AreaPrograma', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nome', models.CharField(max_length=50)), ], options={ 'verbose_name': '\xc1rea do programa', 'verbose_name_plural': '\xc1reas dos programas', }, bases=(models.Model,), ), migrations.CreateModel( name='Atribuicao', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('relatorio', models.FileField(upload_to=b'evento', null=True, verbose_name='Relat\xf3rio', blank=True)), ('area', models.ForeignKey(verbose_name='\xc1rea operacional', to='evento.AreaOperacional')), ('membro', models.ForeignKey(to='membro.Membro')), ], options={ 'verbose_name': 'Atribui\xe7\xe3o', 'verbose_name_plural': 'Atribui\xe7\xf5es', }, bases=(models.Model,), ), migrations.CreateModel( name='Evento', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('local', models.CharField(max_length=100)), ('descricao', models.CharField(max_length=200, verbose_name='Descri\xe7\xe3o')), ('inicio', models.DateTimeField(verbose_name='In\xedcio')), ('termino', models.DateTimeField(verbose_name='T\xe9rmino')), ('url', models.URLField(null=True, verbose_name='URL', blank=True)), ('obs', models.TextField(null=True, verbose_name='Observa\xe7\xe3o', blank=True)), ('acordo', models.ForeignKey(blank=True, to='outorga.Acordo', null=True)), ], options={ }, bases=(models.Model,), ), migrations.CreateModel( name='Sessao', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('descricao', models.CharField(max_length=100, verbose_name='Descri\xe7\xe3o')), ('local', models.CharField(max_length=100)), ('inicio', models.DateTimeField(verbose_name='In\xedcio')), ('termino', models.DateTimeField(verbose_name='T\xe9rmino')), ('arquivo', models.FileField(null=True, upload_to=b'sessao', blank=True)), ('obs', models.TextField(null=True, verbose_name='Observa\xe7\xe3o', blank=True)), ('area', models.ForeignKey(verbose_name='\xc1rea', to='evento.AreaPrograma')), ('evento', models.ForeignKey(to='evento.Evento')), ], options={ 'verbose_name': 'Sess\xe3o', 'verbose_name_plural': 'Sess\xf5es', }, bases=(models.Model,), ), migrations.CreateModel( name='Tipo', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('nome', models.CharField(max_length=50)), ], options={ }, bases=(models.Model,), ), migrations.AddField( model_name='evento', name='tipo', field=models.ForeignKey(to='evento.Tipo'), preserve_default=True, ), migrations.AddField( model_name='atribuicao', name='sessao', field=models.ForeignKey(verbose_name='Sess\xe3o', to='evento.Sessao'), preserve_default=True, ), ]
mpl-2.0
renatocoelho/vencimetro
src/main/java/app/models/List.java
366
package app.models; @javax.persistence.Entity public class List extends Entity { private Integer idLista; private String nome; public void setIdLista(Integer idLista) { this.idLista = idLista; } public Integer getIdLista() { return idLista; } public void setNome(String nome) { this.nome = nome; } public String getNome() { return nome; } }
mpl-2.0
RowEchelonForm/HinduCyborg
Assets/Scripts/SaveLoad/SaveLoadHandler.cs
837
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class SaveLoadHandler : MonoBehaviour { // Use this for initialization void Start () { //SaveLoad.Save(LevelManager.currentLevelName); } // Update is called once per frame void Update () { /*if (Input.GetKeyDown(KeyCode.R)) { SaveLoad.Load(); } if (Input.GetKeyDown(KeyCode.T)) { SaveLoad.Save(LevelManager.currentLevelName); SaveLoad.SaveToFile("test"); } if (Input.GetKeyDown(KeyCode.Y)) { SaveLoad.LoadFromFile("test"); SaveLoad.Load(); }*/ /*if ( Input.GetKeyDown(KeyCode.Escape) ) { LevelManager.loadStart(); }*/ } }
mpl-2.0
encapturemd/MirthConnect
server/src/com/mirth/connect/server/util/MessageAttachmentUtil.java
11578
/* * Copyright (c) Mirth Corporation. All rights reserved. * * http://www.mirthcorp.com * * The software in this package is published under the terms of the MPL license a copy of which has * been included with this distribution in the LICENSE.txt file. */ package com.mirth.connect.server.util; import java.io.ByteArrayOutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; import org.apache.commons.codec.binary.StringUtils; import org.apache.log4j.Logger; import com.mirth.connect.donkey.model.message.ConnectorMessage; import com.mirth.connect.donkey.model.message.XmlSerializerException; import com.mirth.connect.donkey.model.message.attachment.Attachment; import com.mirth.connect.donkey.server.Constants; import com.mirth.connect.donkey.util.Base64Util; import com.mirth.connect.donkey.util.StringUtil; import com.mirth.connect.server.controllers.MessageController; import com.mirth.connect.userutil.ImmutableConnectorMessage; public class MessageAttachmentUtil { private static Logger logger = Logger.getLogger(MessageAttachmentUtil.class); private static String PREFIX = "${"; private static String SUFFIX = "}"; private static int ATTACHMENT_ID_LENGTH = 36; private static String ATTACHMENT_KEY = "ATTACH:"; private static String DICOM_KEY = "DICOMMESSAGE"; private static int KEY_DATA = 0; private static int KEY_END_INDEX = 1; public static byte[] reAttachMessage(String raw, ImmutableConnectorMessage connectorMessage, String charsetEncoding, boolean binary) { try { Map<Integer, Map<Integer, Object>> replacementObjects = new TreeMap<Integer, Map<Integer, Object>>(); // Determine the buffersize during the first pass for better memory performance int bufferSize = raw.length(); int index = 0; int endIndex; // Initialize the objects here so only one retrieval of the attachment content is ever needed. byte[] dicomObject = null; Map<String, Attachment> attachmentMap = null; // Handle the special case if only a dicom message is requested. // In this case we can skip any byte appending and thus do not need to base64 encode the dicom object // if the type is binary. if (raw.trim().equals(PREFIX + DICOM_KEY + SUFFIX)) { dicomObject = DICOMMessageUtil.getDICOMRawBytes(connectorMessage); if (!binary) { dicomObject = Base64Util.encodeBase64(dicomObject); } return dicomObject; } // Check the raw string in one pass for any attachments. // Stores the start and end indices to replace, along with the attachment content. while ((index = raw.indexOf(PREFIX, index)) != -1) { if (raw.startsWith(DICOM_KEY + SUFFIX, index + PREFIX.length())) { if (dicomObject == null) { // Unfortunately, if the dicom data needs to appended to other base64 data, it must be done so in base64. dicomObject = Base64Util.encodeBase64(DICOMMessageUtil.getDICOMRawBytes(connectorMessage)); } endIndex = index + PREFIX.length() + DICOM_KEY.length() + SUFFIX.length(); Map<Integer, Object> replacementMap = new HashMap<Integer, Object>(); replacementMap.put(KEY_END_INDEX, endIndex); replacementMap.put(KEY_DATA, dicomObject); replacementObjects.put(index, replacementMap); bufferSize += dicomObject.length; index += endIndex - index; } else if (raw.startsWith(ATTACHMENT_KEY, index + PREFIX.length())) { if (attachmentMap == null) { List<Attachment> list = getMessageAttachments(connectorMessage); // Store the attachments in a map with the attachment's Id as the key attachmentMap = new HashMap<String, Attachment>(); for (Attachment attachment : list) { attachmentMap.put(attachment.getId(), attachment); } } int attachmentIdStartIndex = index + PREFIX.length() + ATTACHMENT_KEY.length(); int attachmentIdEndIndex = attachmentIdStartIndex + ATTACHMENT_ID_LENGTH; endIndex = attachmentIdEndIndex + SUFFIX.length(); String attachmentId = raw.substring(attachmentIdStartIndex, attachmentIdStartIndex + ATTACHMENT_ID_LENGTH); if (raw.substring(attachmentIdEndIndex, endIndex).equals(SUFFIX)) { Map<Integer, Object> replacementMap = new HashMap<Integer, Object>(); replacementMap.put(KEY_END_INDEX, endIndex); if (attachmentMap.containsKey(attachmentId)) { Attachment attachment = attachmentMap.get(attachmentId); replacementMap.put(KEY_DATA, attachment.getContent()); bufferSize += attachment.getContent().length; } else { replacementMap.put(KEY_DATA, new byte[0]); } replacementObjects.put(index, replacementMap); } } else { endIndex = index + PREFIX.length(); } index += endIndex - index; } // Release the object pointers of the attachment content so they aren't held in memory for the entire method dicomObject = null; attachmentMap = null; // Initialize the stream's buffer size. The buffer size will always be slightly large than needed, // because the template keys are never removed from the buffer size. // It is not worth doing any extra calculations for the amount of memory saved. ByteArrayOutputStream baos = new ByteArrayOutputStream(bufferSize); int segmentStartIndex = 0; for (Map.Entry<Integer, Map<Integer, Object>> entry : replacementObjects.entrySet()) { int startReplacementIndex = entry.getKey(); int endReplacementIndex = (Integer) entry.getValue().get(KEY_END_INDEX); byte[] data = (byte[]) entry.getValue().get(KEY_DATA); // Allows the memory used by the attachments to be released at the end of the loop entry.getValue().clear(); byte[] templateSegment; // If the data is binary, the content should be in base64, so using US-ASCII as the charset encoding should be sufficient. if (binary) { templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex, startReplacementIndex)); } else { templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex, startReplacementIndex), Constants.ATTACHMENT_CHARSET); } baos.write(templateSegment); baos.write(data); segmentStartIndex = endReplacementIndex; } byte[] templateSegment; if (binary) { templateSegment = StringUtils.getBytesUsAscii(raw.substring(segmentStartIndex)); } else { templateSegment = StringUtil.getBytesUncheckedChunked(raw.substring(segmentStartIndex), Constants.ATTACHMENT_CHARSET); } byte[] combined; // If there are no attachments, don't bother writing to the output stream. if (segmentStartIndex == 0) { combined = templateSegment; } else { // Write the segment after the last replacement. baos.write(templateSegment); combined = baos.toByteArray(); // Release the memory used by the byte array stream. ByteArrayOutputStreams do not need to be closed. baos = null; } templateSegment = null; // If binary, the content should be in base64 so it is necessary to decode the data. if (binary) { combined = Base64Util.decodeBase64(combined); } else if (charsetEncoding != null && !charsetEncoding.toUpperCase().equals(Constants.ATTACHMENT_CHARSET.toUpperCase())) { // Convert the byte array to a string using the internal encoding. String combinedString = StringUtils.newString(combined, Constants.ATTACHMENT_CHARSET); // First release the reference to the old byte data so it can be reallocated if necessary. combined = null; // Convert the string to a byte array using the requested encoding combined = StringUtil.getBytesUncheckedChunked(combinedString, charsetEncoding); } return combined; } catch (Exception e) { logger.error("Error reattaching attachments", e); return null; } } public static byte[] reAttachMessage(String raw, ConnectorMessage connectorMessage, String charsetEncoding, boolean binary) { return reAttachMessage(raw, new ImmutableConnectorMessage(connectorMessage), charsetEncoding, binary); } public static String reAttachMessage(ConnectorMessage message) { return reAttachMessage(new ImmutableConnectorMessage(message)); } public static String reAttachMessage(ImmutableConnectorMessage message) { String messageData = null; if (message.getEncoded() != null && message.getEncoded().getContent() != null) { messageData = message.getEncoded().getContent(); } else if (message.getRaw() != null) { messageData = message.getRaw().getContent(); } return StringUtils.newString(reAttachMessage(messageData, message, Constants.ATTACHMENT_CHARSET, false), Constants.ATTACHMENT_CHARSET); } public static String reAttachMessage(String raw, ConnectorMessage message) { return reAttachMessage(raw, new ImmutableConnectorMessage(message)); } public static String reAttachMessage(String raw, ImmutableConnectorMessage message) { return StringUtils.newString(reAttachMessage(raw, message, Constants.ATTACHMENT_CHARSET, false), Constants.ATTACHMENT_CHARSET); } public static boolean hasAttachmentKeys(String raw) { if (raw.contains(PREFIX + DICOM_KEY + SUFFIX) || raw.contains(PREFIX + ATTACHMENT_KEY)) { return true; } return false; } public static List<Attachment> getMessageAttachments(ImmutableConnectorMessage message) throws XmlSerializerException { List<Attachment> attachments; try { attachments = MessageController.getInstance().getMessageAttachment(message.getChannelId(), message.getMessageId()); } catch (Exception e) { throw new XmlSerializerException(e.getMessage()); } return attachments; } }
mpl-2.0
das-praktische-schreinerlein/yaio-commons
src/main/java/de/yaio/commons/config/ConfigurationOption.java
1649
/** * software for projectmanagement and documentation * * @FeatureDomain Collaboration * @author Michael Schreiner <[email protected]> * @category collaboration * @copyright Copyright (c) 2014, Michael Schreiner * @license http://mozilla.org/MPL/2.0/ Mozilla Public License 2.0 * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package de.yaio.commons.config; public class ConfigurationOption { protected String name; protected Object value; public ConfigurationOption(final String name, final Object value) { this.name = name; this.value = value; } public String getName() { return name; } public Object getValue() { return value; } public String getStringValue() { return value == null ? null : value.toString(); } public String toString() { return "ConfigurationOption " + getName() + "=" + getValue(); } public static Object valueOf(final ConfigurationOption option) { return option == null ? null : option.getValue(); } public static String stringValueOf(final ConfigurationOption option) { return option == null ? null : option.getValue().toString(); } public static Integer integerValueOf(final ConfigurationOption option) { return option == null ? null : new Integer(option.getValue().toString()); } }
mpl-2.0
cqrs-endeavour/cqrs-endeavour
cqrs-framework/src/test/scala/cqrs/query/EventDuplicatesFilterSpec.scala
3846
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package cqrs.query import java.util.UUID import cqrs.test.entities.TestAggregateRoot.TestAggregateRootCreated import org.scalatest.FlatSpec class InMemoryEventDuplicatesFilterPersistService extends EventDuplicatesFilterPersistService { private var _lastSequenceNumbers: Seq[(String, Long)] = List() override def fetchFilter: EventDuplicatesFilter = ??? override def updateFilter(updatedSequenceNumbers: Seq[(String, Long)]): Unit = { _lastSequenceNumbers = updatedSequenceNumbers } def lastSequenceNumbers: Seq[(String, Long)] = { _lastSequenceNumbers } } trait EventDuplicatesFilterSpecScope { val service = new InMemoryEventDuplicatesFilterPersistService val filter = new EventDuplicatesFilter val event = TestAggregateRootCreated(UUID.randomUUID(), 2, "some_event") } class EventDuplicatesFilterSpec extends FlatSpec { "EventDuplicatesFilter" should "allow consecutive events for one aggregate" in new EventDuplicatesFilterSpecScope { assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 4, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 5, event))) } it should "filter events with the same sequence number" in new EventDuplicatesFilterSpecScope { assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(!filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 3, event))) } it should "filter events with smaller sequence number" in new EventDuplicatesFilterSpecScope { assert(filter.markAsSeen(EventEnvelope("ar-1", 3, event))) assert(!filter.markAsSeen(EventEnvelope("ar-1", 1, event))) assert(!filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 4, event))) } it should "allow consecutive events within different aggregagtes" in new EventDuplicatesFilterSpecScope { assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-2", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 3, event))) assert(filter.markAsSeen(EventEnvelope("ar-2", 3, event))) } it should "filter events with the same sequence and aggregate id" in new EventDuplicatesFilterSpecScope { assert(filter.markAsSeen(EventEnvelope("ar-1", 1, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-2", 2, event))) assert(!filter.markAsSeen(EventEnvelope("ar-1", 2, event))) assert(!filter.markAsSeen(EventEnvelope("ar-2", 2, event))) assert(filter.markAsSeen(EventEnvelope("ar-2", 3, event))) } it should "rollback seen but not committed events" in new EventDuplicatesFilterSpecScope { // given assert(filter.markAsSeen(EventEnvelope("ar-1", 1, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) // when filter.rollbackSequenceNumbers() // then assert(filter.markAsSeen(EventEnvelope("ar-1", 1, event))) assert(filter.markAsSeen(EventEnvelope("ar-1", 2, event))) } it should "use service to persist not committed sequence numbers" in new EventDuplicatesFilterSpecScope { // given val firstEnvelope = EventEnvelope("ar-1", 1, event) val secondEnvelope = EventEnvelope("ar-2", 2, event) assert(filter.markAsSeen(firstEnvelope)) assert(filter.markAsSeen(secondEnvelope)) // when filter.updatePersistedSequenceNumbers(service) // then val expectedSequenceNumbers = Seq("ar-1" -> 1, "ar-2" -> 2) assert(service.lastSequenceNumbers == expectedSequenceNumbers) } }
mpl-2.0
Ricard/AppverseProject
app/bower_components/ag-grid/docs/angular-grid-grouping/example1.js
1495
var columnDefs = [ {headerName: "Athlete", field: "athlete", width: 150}, {headerName: "Age", field: "age", width: 90}, {headerName: "Country", field: "country", width: 120, rowGroupIndex: 0}, {headerName: "Year", field: "year", width: 90}, {headerName: "Date", field: "date", width: 110}, {headerName: "Sport", field: "sport", width: 110}, {headerName: "Gold", field: "gold", width: 100}, {headerName: "Silver", field: "silver", width: 100}, {headerName: "Bronze", field: "bronze", width: 100}, {headerName: "Total", field: "total", width: 100} ]; var gridOptions = { columnDefs: columnDefs, rowData: null, groupUseEntireRow: true }; // setup the grid after the page has finished loading document.addEventListener('DOMContentLoaded', function() { var gridDiv = document.querySelector('#myGrid'); new agGrid.Grid(gridDiv, gridOptions); // do http request to get our sample data - not using any framework to keep the example self contained. // you will probably use a framework like JQuery, Angular or something else to do your HTTP calls. var httpRequest = new XMLHttpRequest(); httpRequest.open('GET', '../olympicWinners.json'); httpRequest.send(); httpRequest.onreadystatechange = function() { if (httpRequest.readyState == 4 && httpRequest.status == 200) { var httpResult = JSON.parse(httpRequest.responseText); gridOptions.api.setRowData(httpResult); } }; });
mpl-2.0