file_name
stringlengths
3
137
prefix
stringlengths
0
918k
suffix
stringlengths
0
962k
middle
stringlengths
0
812k
day02.rs
use std::fs::File; use std::io::Read; use std::io::Result; pub fn solve() -> Result<()> { let mut file = File::open("input/02.txt")?; let mut lines = String::new(); file.read_to_string(&mut lines)?; let matrix = generate_matrix(&lines); println!("day 2 first: {}", solve_checksum_first(&matrix)); println!("day 2 second: {}", solve_checksum_second(&matrix)); Ok(()) }
fn generate_matrix(input: &str) -> Vec<Vec<u32>> { input .lines() .map(|line| { line.split_whitespace() .filter_map(|digits| digits.parse::<u32>().ok()) .collect() }).collect() } fn solve_checksum_first(matrix: &[Vec<u32>]) -> u32 { matrix .iter() .map(|line| line.iter().max().unwrap() - line.iter().min().unwrap()) .sum() } fn solve_checksum_second(matrix: &[Vec<u32>]) -> u32 { matrix .iter() .filter_map(|line| { for i in 0..(line.len() - 1) { for j in (i + 1)..line.len() { if line[i] % line[j] == 0 { return Some(line[i] / line[j]); } else if line[j] % line[i] == 0 { return Some(line[j] / line[i]); } } } None }).sum() } #[cfg(test)] mod tests { use super::{generate_matrix, solve_checksum_first, solve_checksum_second}; #[test] fn test_solve_checksum_first() { let input = "5 1 9 5\n7 5 3\n2 4 6 8"; let matrix = generate_matrix(input); assert_eq!(solve_checksum_first(&matrix), 18); } #[test] fn test_solve_checksum_second() { let input = "5 9 2 8\n9 4 7 3\n3 8 6 5"; let matrix = generate_matrix(input); assert_eq!(solve_checksum_second(&matrix), 9); } }
accountinfomap.py
from huobi.exception.huobiapiexception import HuobiApiException from huobi.impl.restapiinvoker import call_sync from huobi.model.user import User class AccountInfoMap: user_map = dict() account_id_type_map = dict() account_type_id_map = dict() def
(self, api_key, request_impl): accounts = call_sync(request_impl.get_accounts()) user = User() user.accounts = accounts self.user_map[api_key] = user if accounts and len(accounts): self.account_id_type_map[api_key] = {} self.account_type_id_map[api_key] = {} for account_item in accounts: self.account_id_type_map[api_key][account_item.id] = account_item.account_type self.account_type_id_map[api_key][account_item.account_type] = account_item.id def get_user(self, api_key): if api_key is None or api_key == "": raise HuobiApiException(HuobiApiException.KEY_MISSING, "[User] Key is empty or null") if api_key not in self.user_map: raise HuobiApiException(HuobiApiException.RUNTIME_ERROR, "[User] Cannot found user by key: " + api_key) return self.user_map[api_key] def get_account_by_id(self, api_key, account_id): user = self.get_user(api_key) account = user.get_account_by_id(account_id) if account is None: raise HuobiApiException(HuobiApiException.RUNTIME_ERROR, "[User] Cannot find the account, key: " + api_key + ", account id: " + str(account_id)) return account def get_all_accounts(self, api_key): user = self.get_user(api_key) return user.accounts def get_account_type_by_id(self, api_key, account_id): if api_key is None or api_key == "": raise HuobiApiException(HuobiApiException.KEY_MISSING, "[User] Key is empty or null") if api_key not in self.account_id_type_map: raise HuobiApiException(HuobiApiException.RUNTIME_ERROR, "[User] Cannot found account_id by key: " + api_key) return self.account_id_type_map.get(api_key, {}).get(account_id, None) def get_account_id_by_type(self, api_key, account_type): if api_key is None or api_key == "": raise HuobiApiException(HuobiApiException.KEY_MISSING, "[User] Key is empty or null") if api_key not in self.account_type_id_map: raise HuobiApiException(HuobiApiException.RUNTIME_ERROR, "[User] Cannot found account_type by key: " + api_key) return self.account_type_id_map.get(api_key, {}).get(account_type, None) def get_all_accounts_without_check(self, api_key): if api_key is None or api_key == "": raise HuobiApiException(HuobiApiException.KEY_MISSING, "[User] Key is empty or null") user = self.user_map.get(api_key, None) return None if (user is None) else user.accounts account_info_map = AccountInfoMap()
update_user_info
http.go
package http import ( "fmt" "io" "io/ioutil" "net/http" "strings" "sync" "time" "github.com/yevheniir/telegraf-fork" "github.com/yevheniir/telegraf-fork/internal" "github.com/yevheniir/telegraf-fork/internal/tls" "github.com/yevheniir/telegraf-fork/plugins/inputs" "github.com/yevheniir/telegraf-fork/plugins/parsers" ) type HTTP struct { URLs []string `toml:"urls"` Method string `toml:"method"` Body string `toml:"body"` ContentEncoding string `toml:"content_encoding"` Headers map[string]string `toml:"headers"` // HTTP Basic Auth Credentials Username string `toml:"username"` Password string `toml:"password"` tls.ClientConfig SuccessStatusCodes []int `toml:"success_status_codes"` Timeout internal.Duration `toml:"timeout"` client *http.Client // The parser will automatically be set by Telegraf core code because // this plugin implements the ParserInput interface (i.e. the SetParser method) parser parsers.Parser } var sampleConfig = ` ## One or more URLs from which to read formatted metrics urls = [ "http://localhost/metrics" ] ## HTTP method # method = "GET" ## Optional HTTP headers # headers = {"X-Special-Header" = "Special-Value"} ## Optional HTTP Basic Auth Credentials # username = "username" # password = "pa$$word" ## HTTP entity-body to send with POST/PUT requests. # body = "" ## HTTP Content-Encoding for write request body, can be set to "gzip" to ## compress body or "identity" to apply no encoding. # content_encoding = "identity" ## Optional TLS Config # tls_ca = "/etc/telegraf/ca.pem" # tls_cert = "/etc/telegraf/cert.pem" # tls_key = "/etc/telegraf/key.pem" ## Use TLS but skip chain & host verification # insecure_skip_verify = false ## Amount of time allowed to complete the HTTP request # timeout = "5s" ## List of success status codes # success_status_codes = [200] ## Data format to consume. ## Each data format has its own unique set of configuration options, read ## more about them here: ## https://github.com/yevheniir/telegraf-fork/blob/master/docs/DATA_FORMATS_INPUT.md # data_format = "influx" ` // SampleConfig returns the default configuration of the Input func (*HTTP) SampleConfig() string { return sampleConfig } // Description returns a one-sentence description on the Input func (*HTTP) Description() string { return "Read formatted metrics from one or more HTTP endpoints" } func (h *HTTP) Init() error { tlsCfg, err := h.ClientConfig.TLSConfig() if err != nil { return err } h.client = &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsCfg, Proxy: http.ProxyFromEnvironment, }, Timeout: h.Timeout.Duration, } // Set default as [200] if len(h.SuccessStatusCodes) == 0 { h.SuccessStatusCodes = []int{200} } return nil } // Gather takes in an accumulator and adds the metrics that the Input // gathers. This is called every "interval" func (h *HTTP) Gather(acc telegraf.Accumulator) error { var wg sync.WaitGroup for _, u := range h.URLs { wg.Add(1) go func(url string) { defer wg.Done() if err := h.gatherURL(acc, url); err != nil { acc.AddError(fmt.Errorf("[url=%s]: %s", url, err)) } }(u) } wg.Wait() return nil } // SetParser takes the data_format from the config and finds the right parser for that format func (h *HTTP) SetParser(parser parsers.Parser) { h.parser = parser } // Gathers data from a particular URL // Parameters: // acc : The telegraf Accumulator to use // url : endpoint to send request to // // Returns: // error: Any error that may have occurred func (h *HTTP) gatherURL( acc telegraf.Accumulator, url string, ) error { body, err := makeRequestBodyReader(h.ContentEncoding, h.Body) if err != nil { return err } request, err := http.NewRequest(h.Method, url, body) if err != nil { return err } if h.ContentEncoding == "gzip" { request.Header.Set("Content-Encoding", "gzip") } for k, v := range h.Headers { if strings.ToLower(k) == "host" { request.Host = v } else { request.Header.Add(k, v) } } if h.Username != "" || h.Password != "" { request.SetBasicAuth(h.Username, h.Password) } resp, err := h.client.Do(request) if err != nil { return err } defer resp.Body.Close() responseHasSuccessCode := false for _, statusCode := range h.SuccessStatusCodes { if resp.StatusCode == statusCode { responseHasSuccessCode = true break } } if !responseHasSuccessCode { return fmt.Errorf("received status code %d (%s), expected any value out of %v", resp.StatusCode, http.StatusText(resp.StatusCode), h.SuccessStatusCodes) } b, err := ioutil.ReadAll(resp.Body) if err != nil { return err } metrics, err := h.parser.Parse(b) if err != nil { return err } for _, metric := range metrics { if !metric.HasTag("url") { metric.AddTag("url", url) } acc.AddFields(metric.Name(), metric.Fields(), metric.Tags(), metric.Time()) } return nil } func makeRequestBodyReader(contentEncoding, body string) (io.Reader, error) { var err error var reader io.Reader = strings.NewReader(body) if contentEncoding == "gzip" { reader, err = internal.CompressWithGzip(reader) if err != nil { return nil, err } } return reader, nil } func init()
{ inputs.Add("http", func() telegraf.Input { return &HTTP{ Timeout: internal.Duration{Duration: time.Second * 5}, Method: "GET", } }) }
miner_fees.py
""" MinerFees """ from .miner_fees_item import MinerFeesItem class MinerFees: """ The total amount of fees that the purchaser will pay to cover BitPay's UTXO sweep cost for an invoice. The key is the currency and the value is an amount in satoshis. This is referenced as "Network Cost" on an invoice,see this support article for more information """ __btc = MinerFeesItem() __bch = MinerFeesItem() __eth = MinerFeesItem() __usdc = MinerFeesItem() __gusd = MinerFeesItem() __pax = MinerFeesItem() __doge = MinerFeesItem() __ltc = MinerFeesItem() __busd = MinerFeesItem() __xrp = MinerFeesItem() def __init__(self, **kwargs): for key, value in kwargs.items(): try: if key in ["BTC", "BCH", "ETH", "USDC", "GUSD", "PAX", "BUSD", "XRP"]: value = MinerFeesItem(**value) getattr(self, "set_%s" % key.lower())(value) except AttributeError: pass def get_btc(self): """ Get method for the btc :return: btc """ return self.__btc def set_btc(self, btc: MinerFeesItem): """ Set method for the btc :param btc: btc """ self.__btc = btc def get_bch(self): """ Get method for the bch :return: bch """ return self.__bch def set_bch(self, bch: MinerFeesItem): """ Set method for the bch :param bch: bch """ self.__bch = bch def get_eth(self): """ Get method for the eth :return: eth """ return self.__eth def set_eth(self, eth: MinerFeesItem): """ Set method for the eth :param eth: eth """ self.__eth = eth def get_usdc(self): """ Get method for the usdc :return: usdc """ return self.__usdc def set_usdc(self, usdc: MinerFeesItem): """ Set method for the usdc :param usdc: usdc """ self.__usdc = usdc def get_gusd(self): """ Get method for the gusd :return: gusd """ return self.__gusd def set_gusd(self, gusd: MinerFeesItem): """ Set method for the gusd :param gusd: gusd """ self.__gusd = gusd def get_doge(self): """ Get method for the doge :return: doge """ return self.__doge def set_doge(self, doge: MinerFeesItem): """ Set method for the doge :param doge: doge """ self.__doge = doge def get_ltc(self):
def set_ltc(self, ltc: MinerFeesItem): """ Set method for the ltc :param ltc: ltc """ self.__ltc = ltc def get_pax(self): """ Get method for the pax :return: pax """ return self.__pax def set_pax(self, pax: MinerFeesItem): """ Set method for the pax :param pax: pax """ self.__pax = pax def get_busd(self): """ Get method for the busd :return: busd """ return self.__busd def set_busd(self, busd: MinerFeesItem): """ Set method for the busd :param busd: busd """ self.__busd = busd def get_xrp(self): """ Get method for the xrp :return: xrp """ return self.__xrp def set_xrp(self, xrp: MinerFeesItem): """ Set method for the xrp :param xrp: xrp """ self.__xrp = xrp def to_json(self): """ :return: data in json """ data = { "btc": self.get_btc(), "bch": self.get_bch(), "eth": self.get_eth(), "usdc": self.get_usdc(), "gusd": self.get_gusd(), "pax": self.get_pax(), "doge": self.get_doge(), "ltc": self.get_ltc(), "xrp": self.get_xrp(), "busd": self.get_busd(), } data = {key: value for key, value in data.items() if value} return data
""" Get method for the ltc :return: ltc """ return self.__ltc
crossdomain.py
"""Cross Domain Decorators""" from datetime import timedelta from functools import update_wrapper from flask import current_app, make_response, request from past.builtins import basestring from ..models.client import validate_origin def
( origin=None, methods=None, headers=( 'Authorization', 'X-Requested-With', 'X-CSRFToken', 'Content-Type' ), max_age=21600, automatic_options=True): """Decorator to add specified crossdomain headers to response :param origin: '*' to allow all origins, otherwise a string with a single origin or a list of origins that might access the resource. If no origin is provided, use request.headers['Origin'], but ONLY if it validates. If no origin is provided and the request doesn't include an **Origin** header, no CORS headers will be added. :param methods: Optionally a list of methods that are allowed for this view. If not provided it will allow all methods that are implemented. :param headers: Optionally a list of headers that are allowed for this request. :param max_age: The number of seconds as integer or timedelta object for which the preflighted request is valid. :param automatic_options: If enabled the decorator will use the default Flask OPTIONS response and attach the headers there, otherwise the view function will be called to generate an appropriate response. :raises :py:exc:`werkzeug.exceptions.Unauthorized`: if no origin is provided and the one in request.headers['Origin'] doesn't validate as one we know. """ def get_headers(): if headers is not None and not isinstance(headers, basestring): return ', '.join(x.upper() for x in headers) return headers def get_methods(): if methods is not None: return ', '.join(sorted(x.upper() for x in methods)) options_resp = current_app.make_default_options_response() return options_resp.headers['allow'] def get_origin(): """Given origin used blind, request.origin requires validation""" if origin: if not isinstance(origin, basestring): return ', '.join(origin) return origin use_origin = None if 'Origin' in request.headers: use_origin = request.headers['Origin'] if use_origin: validate_origin(use_origin) return use_origin def get_max_age(): if isinstance(max_age, timedelta): return str(max_age.total_seconds()) return str(max_age) def decorator(f): def wrapped_function(*args, **kwargs): if automatic_options and request.method == 'OPTIONS': resp = current_app.make_default_options_response() else: resp = make_response(f(*args, **kwargs)) origin = get_origin() if origin: h = resp.headers h['Access-Control-Allow-Credentials'] = 'true' h['Access-Control-Allow-Origin'] = origin h['Access-Control-Allow-Methods'] = get_methods() h['Access-Control-Max-Age'] = get_max_age() h['Access-Control-Allow-Headers'] = get_headers() h['Access-Control-Expose-Headers'] = 'content-length' return resp f.provide_automatic_options = False f.required_methods = getattr(f, 'required_methods', set()) f.required_methods.add('OPTIONS') return update_wrapper(wrapped_function, f) return decorator
crossdomain
analysis.rs
use std::collections::{HashMap, HashSet}; use std::hash::Hash; use ast::*; #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] enum AccessType { Read, Write, } #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)] enum RootIdentifier { Mem(u32), Param(u32), } impl RootIdentifier { fn map_param(self, mapper: impl FnOnce(u32) -> RootIdentifier) -> RootIdentifier { match self { RootIdentifier::Mem(_) => self, RootIdentifier::Param(p) => mapper(p), } } } #[derive(Clone, Debug)] struct Scope<'a> { idents: HashMap<&'a str, RootIdentifier>, } #[derive(Debug)] struct FnContext<'a> { name: &'a str, accesses: HashSet<(AccessType, RootIdentifier)>, } #[derive(Debug)] struct FnCall<'a>(u32, &'a str, Vec<Option<RootIdentifier>>); impl<'a> Hash for FnCall<'a> { fn hash<H: std::hash::Hasher>(&self, state: &mut H)
} impl<'a> PartialEq for FnCall<'a> { fn eq(&self, other: &Self) -> bool { self.0 == other.0 } } impl<'a> Eq for FnCall<'a> {} #[derive(Debug, Default)] struct Analysis<'a> { next_id: u32, next_mem_loc: u32, accesses: HashMap<&'a str, HashSet<(AccessType, RootIdentifier)>>, points_to: HashMap<&'a str, HashMap<u32, HashSet<u32>>>, calls: HashMap<&'a str, HashSet<FnCall<'a>>>, } impl<'a> Analysis<'a> { fn next_id(&mut self) -> u32 { let id = self.next_id; self.next_id += 1; id } fn next_mem_loc(&mut self) -> u32 { let loc = self.next_mem_loc; self.next_mem_loc += 1; loc } } /// PRECONDITION: Functions must be defined in order, such that earlier functions do not contain /// calls to later functions. pub fn analyse(module: &Module) -> bool { let mut analysis = Analysis::default(); let mut global_scope = Scope { idents: Default::default(), }; for var in &module.vars { global_scope .idents .insert(&var.name, RootIdentifier::Mem(analysis.next_mem_loc())); } for func in module.functions.iter().rev() { let accesses = visit_function(&mut analysis, global_scope.clone(), func); analysis.accesses.insert(&func.name, accesses); } // println!("{analysis:#?}"); let Analysis { mut accesses, points_to, calls, .. } = analysis; for func in module.functions.iter() { // Expand the calls to determine the full set of possible memory accesses for call in calls.get(func.name.as_str()).into_iter().flatten() { if let Some(call_accesses) = accesses .get(call.1) .map(|it| it as *const HashSet<(AccessType, RootIdentifier)>) { // This should be safe as long as func.name != call.1 (which shouldn't be the // case since recursion is forbidden in WGSL) let call_accesses = unsafe { &*call_accesses }; for (access_type, root_id) in call_accesses { accesses.entry(func.name.as_str()).or_default().insert(( *access_type, root_id.map_param(|it| call.2[it as usize].unwrap()), )); } } } let mut expanded_accesses: HashMap<u32, HashSet<(AccessType, RootIdentifier)>> = HashMap::new(); for (access_type, root_id) in accesses.get(func.name.as_str()).unwrap() { match root_id { RootIdentifier::Mem(loc) => { expanded_accesses .entry(*loc) .or_default() .insert((*access_type, *root_id)); } RootIdentifier::Param(p) => { for loc in points_to.get(func.name.as_str()).unwrap().get(p).unwrap() { expanded_accesses .entry(*loc) .or_default() .insert((*access_type, *root_id)); } } } } // println!("{}: {:#?}", func.name, expanded_accesses); for (loc_id, accesses) in expanded_accesses { if let Some((_, root_id)) = accesses .iter() .find(|(access_type, _)| matches!(access_type, AccessType::Write)) { if accesses.iter().any(|it| it.1 != *root_id) { eprintln!( "possible aliased access to mem loc `{loc_id}` in `{}`", func.name ); return false; } } } } true } // TODO: Use visitor pattern to avoid duplicating code with analysis in harness? fn visit_function<'a>( analysis: &mut Analysis<'a>, mut scope: Scope<'a>, func: &'a FnDecl, ) -> HashSet<(AccessType, RootIdentifier)> { let mut cx = FnContext { name: &func.name, accesses: Default::default(), }; for (i, param) in func.inputs.iter().enumerate() { if let DataType::Ptr(_) = &param.data_type { scope .idents .insert(&param.name, RootIdentifier::Param(i as u32)); } } for stmt in &func.body { visit_stmt(analysis, &mut scope, &mut cx, stmt); } cx.accesses } fn visit_stmt<'a>( analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, stmt: &'a Statement, ) { match stmt { Statement::LetDecl(stmt) => visit_expr(analysis, scope, cx, &stmt.initializer), Statement::VarDecl(stmt) => { if let Some(initializer) = &stmt.initializer { visit_expr(analysis, scope, cx, initializer); } scope .idents .insert(&stmt.ident, RootIdentifier::Mem(analysis.next_mem_loc())); } Statement::Assignment(stmt) => { visit_lhs(analysis, scope, cx, &stmt.lhs); visit_expr(analysis, scope, cx, &stmt.rhs); } Statement::Compound(block) => visit_stmt_block(analysis, scope, cx, block), Statement::If(stmt) => visit_if_stmt(analysis, scope, cx, stmt), Statement::Return(stmt) => { if let Some(value) = &stmt.value { visit_expr(analysis, scope, cx, value); } } Statement::Loop(stmt) => visit_stmt_block(analysis, scope, cx, &stmt.body), Statement::Break => {} Statement::Switch(stmt) => { visit_expr(analysis, scope, cx, &stmt.selector); for case in &stmt.cases { visit_stmt_block(analysis, scope, cx, &case.body); } visit_stmt_block(analysis, scope, cx, &stmt.default); } Statement::ForLoop(stmt) => { let mut scope = scope.clone(); if let Some(init) = &stmt.header.init { match init { ForLoopInit::VarDecl(stmt) => { if let Some(init) = &stmt.initializer { visit_expr(analysis, &mut scope, cx, init); } scope .idents .insert(&stmt.ident, RootIdentifier::Mem(analysis.next_mem_loc())); } } } if let Some(condition) = &stmt.header.condition { visit_expr(analysis, &mut scope, cx, condition); } if let Some(update) = &stmt.header.update { match update { ForLoopUpdate::Assignment(stmt) => { visit_lhs(analysis, &mut scope, cx, &stmt.lhs); visit_expr(analysis, &mut scope, cx, &stmt.rhs); } } } visit_stmt_block(analysis, &mut scope, cx, &stmt.body); } Statement::FnCall(stmt) => { visit_function_call(analysis, scope, cx, &stmt.ident, &stmt.args); } Statement::Continue => {} Statement::Fallthrough => {} } } fn visit_stmt_block<'a>( analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, block: &'a [Statement], ) { let mut scope = scope.clone(); for stmt in block { visit_stmt(analysis, &mut scope, cx, stmt); } } fn visit_lhs<'a>( _analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, lhs: &'a AssignmentLhs, ) { if let AssignmentLhs::Expr(lhs) = &lhs { let ident = find_lhs_ident(lhs); let root_ident = scope.idents.get(ident); if let Some(root_ident) = root_ident { cx.accesses.insert((AccessType::Write, *root_ident)); } } } fn visit_if_stmt<'a>( analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, stmt: &'a IfStatement, ) { visit_expr(analysis, scope, cx, &stmt.condition); visit_stmt_block(analysis, scope, cx, &stmt.body); if let Some(else_) = &stmt.else_ { match else_.as_ref() { Else::If(stmt) => visit_if_stmt(analysis, scope, cx, stmt), Else::Else(body) => visit_stmt_block(analysis, scope, cx, body), } } } fn visit_expr<'a>( analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, node: &'a ExprNode, ) { match &node.expr { Expr::Lit(_) => {} Expr::TypeCons(expr) => { for arg in &expr.args { visit_expr(analysis, scope, cx, arg); } } Expr::Var(expr) => { let ident = scope.idents.get(expr.ident.as_str()); if let Some(root_ident) = ident { cx.accesses.insert((AccessType::Read, *root_ident)); } } Expr::Postfix(expr) => { visit_expr(analysis, scope, cx, &expr.inner); match &expr.postfix { Postfix::Index(index) => visit_expr(analysis, scope, cx, index), Postfix::Member(_) => {} } } Expr::UnOp(expr) => { visit_expr(analysis, scope, cx, &expr.inner); } Expr::BinOp(expr) => { visit_expr(analysis, scope, cx, &expr.left); visit_expr(analysis, scope, cx, &expr.right); } Expr::FnCall(expr) => { visit_function_call(analysis, scope, cx, &expr.ident, &expr.args); } } } fn find_lhs_ident(node: &LhsExprNode) -> &str { match &node.expr { LhsExpr::Ident(v) => v, LhsExpr::Postfix(node, _) => find_lhs_ident(node), LhsExpr::Deref(node) => find_lhs_ident(node), LhsExpr::AddressOf(node) => find_lhs_ident(node), } } fn visit_function_call<'a>( analysis: &mut Analysis<'a>, scope: &mut Scope<'a>, cx: &mut FnContext<'a>, ident: &'a str, args: &'a [ExprNode], ) { let mut has_pointer_args = false; let mut arg_ids = vec![]; for (i, arg) in args.iter().enumerate() { if let DataType::Ptr(_) = arg.data_type { has_pointer_args = true; let root_ident = scope.idents.get(find_pointer_expr_root(arg)).unwrap(); match root_ident { RootIdentifier::Mem(loc) => { analysis .points_to .entry(ident) .or_default() .entry(i as u32) .or_default() .insert(*loc); } RootIdentifier::Param(id) => { let locs = analysis.points_to.get(cx.name).unwrap().get(id).unwrap() as *const _; analysis .points_to .entry(ident) .or_default() .entry(i as u32) .or_default() // This should be safe as long as cx.name != ident (which shouldn't be the // case since recursion is forbidden in WGSL) .extend(unsafe { &*locs }); } } arg_ids.push(Some(*root_ident)); } else { visit_expr(analysis, scope, cx, arg); arg_ids.push(None); } } if has_pointer_args { let id = analysis.next_id(); analysis .calls .entry(cx.name) .or_default() .insert(FnCall(id, ident, arg_ids)); } } fn find_pointer_expr_root(node: &ExprNode) -> &str { match &node.expr { Expr::Var(expr) => &expr.ident, Expr::Postfix(expr) => find_pointer_expr_root(&expr.inner), Expr::UnOp(expr) => find_pointer_expr_root(&expr.inner), _ => unreachable!("invalid subexpression encountered in pointer expression"), } }
{ self.0.hash(state); }
0002_profilefeeditem.py
# Generated by Django 2.2 on 2020-12-18 13:14 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration):
dependencies = [ ('profiles_api', '0001_initial'), ] operations = [ migrations.CreateModel( name='ProfileFeedItem', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('status_text', models.CharField(max_length=255)), ('created_on', models.DateTimeField(auto_now_add=True)), ('user_profile', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), ]
e0059.rs
#![feature(unboxed_closures)] /* cargo test --test e0059 cargo test --test e0059 with_error -- --nocapture cargo test --test e0059 without_error1 -- --nocapture */ /* The built-in function traits are generic over a tuple of the function arguments. If one uses angle-bracket notation (Fn<(T,), Output=U>) instead of parentheses (Fn(T) -> U) to denote the function trait, the type parameter should be a tuple. Otherwise function call notation cannot be used and the trait will not be implemented by closures. */ // I lot of problems with recursion_limit #[cfg(test)] mod tests { #[test] fn with_error() { // fn foo1<F: Fn<i32>>(f: F) -> F::Output { f(3) } // error } #[test] fn without_error1() { #[allow(dead_code)] fn foo2<F: Fn<(i32,)>>(f: F) -> F::Output
} }
{ f(3) }
BrandAAuth.service.ts
export class BrandAAuthService {}
TestRunnerCli.js
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.TestRunnerCli = exports.MENUS = void 0; const code_frame_1 = require("@babel/code-frame"); const path_1 = __importDefault(require("path")); const nanocolors_1 = require("nanocolors"); const open_1 = __importDefault(require("open")); const writeCoverageReport_1 = require("./writeCoverageReport"); const getSelectFilesMenu_1 = require("./getSelectFilesMenu"); const getWatchCommands_1 = require("./getWatchCommands"); const DynamicTerminal_1 = require("./terminal/DynamicTerminal"); const BufferedLogger_1 = require("./BufferedLogger"); const getManualDebugMenu_1 = require("./getManualDebugMenu"); const TestSessionStatus_1 = require("../test-session/TestSessionStatus"); exports.MENUS = { NONE: 'none', OVERVIEW: 'overview', FOCUS_SELECT_FILE: 'focus', DEBUG_SELECT_FILE: 'debug', MANUAL_DEBUG: 'manual-debug', }; const KEYCODES = { ENTER: '\r', ESCAPE: '\u001b', CTRL_C: '\u0003', CTRL_D: '\u0004', }; class
{ constructor(config, runner) { this.terminal = new DynamicTerminal_1.DynamicTerminal(); this.reportedFilesByTestRun = new Map(); this.activeMenu = exports.MENUS.NONE; this.menuSucceededAndPendingFiles = []; this.menuFailedFiles = []; this.pendingReportPromises = []; this.lastStaticLog = -1; this.config = config; this.runner = runner; this.logger = this.config.logger; this.sessions = runner.sessions; this.localAddress = `${this.config.protocol}//${this.config.hostname}:${this.config.port}/`; if (config.watch && !this.terminal.isInteractive) { this.runner.stop(new Error('Cannot run watch mode in a non-interactive (TTY) terminal.')); } } start() { var _a; this.setupTerminalEvents(); this.setupRunnerEvents(); this.terminal.start(); for (const reporter of this.config.reporters) { (_a = reporter.start) === null || _a === void 0 ? void 0 : _a.call(reporter, { config: this.config, sessions: this.sessions, testFiles: this.runner.testFiles, startTime: this.runner.startTime, browsers: this.runner.browsers, browserNames: this.runner.browserNames, }); } this.switchMenu(this.config.manual ? exports.MENUS.MANUAL_DEBUG : exports.MENUS.OVERVIEW); if (this.config.watch || (this.config.manual && this.terminal.isInteractive)) { this.terminal.observeDirectInput(); } if (this.config.staticLogging || !this.terminal.isInteractive) { this.logger.log(nanocolors_1.bold(`Running ${this.runner.testFiles.length} test files...\n`)); } if (this.config.open) { open_1.default(this.localAddress); } } setupTerminalEvents() { this.terminal.on('input', key => { var _a; if ([exports.MENUS.DEBUG_SELECT_FILE, exports.MENUS.FOCUS_SELECT_FILE].includes(this.activeMenu)) { const i = Number(key); if (!Number.isNaN(i)) { this.focusTestFileNr(i); return; } } switch (key.toUpperCase()) { case KEYCODES.CTRL_C: case KEYCODES.CTRL_D: case 'Q': if (this.activeMenu === exports.MENUS.OVERVIEW || (this.config.manual && this.activeMenu === exports.MENUS.MANUAL_DEBUG)) { this.runner.stop(); } return; case 'D': if (this.activeMenu === exports.MENUS.OVERVIEW) { if (this.runner.focusedTestFile) { this.runner.startDebugBrowser(this.runner.focusedTestFile); } else if (this.runner.testFiles.length === 1) { this.runner.startDebugBrowser(this.runner.testFiles[0]); } else { this.switchMenu(exports.MENUS.DEBUG_SELECT_FILE); } } else if (this.activeMenu === exports.MENUS.MANUAL_DEBUG) { open_1.default(this.localAddress); } return; case 'F': if (this.activeMenu === exports.MENUS.OVERVIEW && this.runner.testFiles.length > 1) { this.switchMenu(exports.MENUS.FOCUS_SELECT_FILE); } return; case 'C': if (this.activeMenu === exports.MENUS.OVERVIEW && this.config.coverage) { open_1.default(`file://${path_1.default.resolve((_a = this.config.coverageConfig.reportDir) !== null && _a !== void 0 ? _a : '', 'lcov-report', 'index.html')}`); } return; case 'M': this.switchMenu(exports.MENUS.MANUAL_DEBUG); return; case KEYCODES.ESCAPE: if (this.activeMenu === exports.MENUS.OVERVIEW && this.runner.focusedTestFile) { this.runner.focusedTestFile = undefined; this.reportTestResults(true); this.reportTestProgress(); } else if (this.activeMenu === exports.MENUS.MANUAL_DEBUG) { this.switchMenu(exports.MENUS.OVERVIEW); } return; case KEYCODES.ENTER: this.runner.runTests(this.sessions.all()); return; default: return; } }); } setupRunnerEvents() { this.sessions.on('session-status-updated', session => { if (this.activeMenu !== exports.MENUS.OVERVIEW) { return; } if (session.status === TestSessionStatus_1.SESSION_STATUS.FINISHED) { this.reportTestResult(session.testFile); this.reportTestProgress(); } }); this.runner.on('test-run-started', ({ testRun }) => { var _a; for (const reporter of this.config.reporters) { (_a = reporter.onTestRunStarted) === null || _a === void 0 ? void 0 : _a.call(reporter, { testRun }); } if (this.activeMenu !== exports.MENUS.OVERVIEW) { return; } if (testRun !== 0 && this.config.watch) { this.terminal.clear(); } this.reportTestResults(); this.reportTestProgress(false); }); this.runner.on('test-run-finished', ({ testRun, testCoverage }) => { var _a; for (const reporter of this.config.reporters) { (_a = reporter.onTestRunFinished) === null || _a === void 0 ? void 0 : _a.call(reporter, { testRun, sessions: Array.from(this.sessions.all()), testCoverage, focusedTestFile: this.runner.focusedTestFile, }); } if (this.activeMenu !== exports.MENUS.OVERVIEW) { return; } this.testCoverage = testCoverage; if (testCoverage && !this.runner.focusedTestFile) { this.writeCoverageReport(testCoverage); } this.reportSyntaxErrors(); this.reportTestProgress(); }); this.runner.on('finished', () => { this.reportEnd(); }); } focusTestFileNr(i) { var _a; const focusedTestFile = (_a = this.menuFailedFiles[i - 1]) !== null && _a !== void 0 ? _a : this.menuSucceededAndPendingFiles[i - this.menuFailedFiles.length - 1]; const debug = this.activeMenu === exports.MENUS.DEBUG_SELECT_FILE; if (focusedTestFile) { this.runner.focusedTestFile = focusedTestFile; this.switchMenu(exports.MENUS.OVERVIEW); if (debug) { this.runner.startDebugBrowser(focusedTestFile); } } else { this.terminal.clear(); this.logSelectFilesMenu(); } } reportTestResults(forceReport = false) { const { focusedTestFile } = this.runner; const testFiles = focusedTestFile ? [focusedTestFile] : this.runner.testFiles; for (const testFile of testFiles) { this.reportTestResult(testFile, forceReport); } } reportTestResult(testFile, forceReport = false) { var _a; const testRun = this.runner.testRun; const sessionsForTestFile = Array.from(this.sessions.forTestFile(testFile)); const allFinished = sessionsForTestFile.every(s => s.status === TestSessionStatus_1.SESSION_STATUS.FINISHED); if (!allFinished) { // not all sessions for this file are finished return; } let reportedFiles = this.reportedFilesByTestRun.get(testRun); if (!reportedFiles) { reportedFiles = new Set(); this.reportedFilesByTestRun.set(testRun, reportedFiles); } if (!forceReport && reportedFiles.has(testFile)) { // this was file was already reported return; } reportedFiles.add(testFile); const bufferedLogger = new BufferedLogger_1.BufferedLogger(this.logger); for (const reporter of this.config.reporters) { const sessionsForTestFile = Array.from(this.sessions.forTestFile(testFile)); (_a = reporter.reportTestFileResults) === null || _a === void 0 ? void 0 : _a.call(reporter, { logger: bufferedLogger, sessionsForTestFile, testFile, testRun, }); } // all the logs from the reportered were buffered, if they finished before a new test run // actually log them to the terminal here if (this.runner.testRun === testRun) { bufferedLogger.logBufferedMessages(); } } reportTestProgress(final = false) { var _a; if (this.config.manual) { return; } const logStatic = this.config.staticLogging || !this.terminal.isInteractive; if (logStatic && !final) { // print a static progress log only once every 10000ms const now = Date.now(); if (this.lastStaticLog !== -1 && now - this.lastStaticLog < 10000) { return; } this.lastStaticLog = now; } const reports = []; for (const reporter of this.config.reporters) { const report = (_a = reporter.getTestProgress) === null || _a === void 0 ? void 0 : _a.call(reporter, { sessions: Array.from(this.sessions.all()), testRun: this.runner.testRun, focusedTestFile: this.runner.focusedTestFile, testCoverage: this.testCoverage, }); if (report) { reports.push(...report); } } if (this.config.watch) { if (this.runner.focusedTestFile) { reports.push(`Focused on test file: ${nanocolors_1.cyan(path_1.default.relative(process.cwd(), this.runner.focusedTestFile))}\n`); } reports.push(...getWatchCommands_1.getWatchCommands(!!this.config.coverage, this.runner.testFiles, !!this.runner.focusedTestFile), ''); } if (logStatic) { this.terminal.logStatic(reports); } else { this.terminal.logDynamic(reports); } } reportSyntaxErrors() { var _a; // TODO: this special cases the logger of @web/test-runner which implements // logging of syntax errors. we need to make this more generic const logger = this.config.logger; const { loggedSyntaxErrors = new Map() } = logger; if (loggedSyntaxErrors.size === 0) { return; } const report = []; (_a = logger.clearLoggedSyntaxErrors) === null || _a === void 0 ? void 0 : _a.call(logger); for (const [filePath, errors] of loggedSyntaxErrors.entries()) { for (const error of errors) { const { message, code, line, column } = error; const result = code_frame_1.codeFrameColumns(code, { start: { line, column } }, { highlightCode: true }); const relativePath = path_1.default.relative(process.cwd(), filePath); report.push(nanocolors_1.red(`Error while transforming ${nanocolors_1.cyan(relativePath)}: ${message}`)); report.push(result); report.push(''); } } this.terminal.logStatic(report); } writeCoverageReport(testCoverage) { writeCoverageReport_1.writeCoverageReport(testCoverage, this.config.coverageConfig); } switchMenu(menu) { if (this.activeMenu === menu) { return; } this.activeMenu = menu; if (this.config.watch) { this.terminal.clear(); } switch (menu) { case exports.MENUS.OVERVIEW: this.reportTestResults(true); this.reportTestProgress(); if (this.config.watch) { this.terminal.observeDirectInput(); } break; case exports.MENUS.FOCUS_SELECT_FILE: case exports.MENUS.DEBUG_SELECT_FILE: this.logSelectFilesMenu(); break; case exports.MENUS.MANUAL_DEBUG: this.logManualDebugMenu(); break; default: break; } } logSelectFilesMenu() { this.menuSucceededAndPendingFiles = []; this.menuFailedFiles = []; for (const testFile of this.runner.testFiles) { const sessions = Array.from(this.sessions.forTestFile(testFile)); if (sessions.every(t => t.status === TestSessionStatus_1.SESSION_STATUS.FINISHED && !t.passed)) { this.menuFailedFiles.push(testFile); } else { this.menuSucceededAndPendingFiles.push(testFile); } } const selectFilesEntries = getSelectFilesMenu_1.getSelectFilesMenu(this.menuSucceededAndPendingFiles, this.menuFailedFiles); this.terminal.logDynamic([]); this.terminal.logStatic(selectFilesEntries); this.terminal.logPendingUserInput(`Number of the file to ${this.activeMenu === exports.MENUS.FOCUS_SELECT_FILE ? 'focus' : 'debug'}: `); this.terminal.observeConfirmedInput(); } logManualDebugMenu() { this.terminal.logDynamic(getManualDebugMenu_1.getManualDebugMenu(this.config)); } async reportEnd() { var _a; for (const reporter of this.config.reporters) { await ((_a = reporter.stop) === null || _a === void 0 ? void 0 : _a.call(reporter, { sessions: Array.from(this.sessions.all()), testCoverage: this.testCoverage, focusedTestFile: this.runner.focusedTestFile, })); } this.reportTestProgress(true); this.terminal.stop(); this.runner.stop(); } } exports.TestRunnerCli = TestRunnerCli; //# sourceMappingURL=TestRunnerCli.js.map
TestRunnerCli
philharmoniedeparis.py
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor from ..compat import compat_str from ..utils import ( try_get, urljoin, ) class PhilharmonieDeParisIE(InfoExtractor): IE_DESC = 'Philharmonie de Paris' _VALID_URL = r'''(?x) https?:// (?: live\.philharmoniedeparis\.fr/(?:[Cc]oncert/|misc/Playlist\.ashx\?id=)| pad\.philharmoniedeparis\.fr/doc/CIMU/ ) (?P<id>\d+) ''' _TESTS = [{ 'url': 'http://pad.philharmoniedeparis.fr/doc/CIMU/1086697/jazz-a-la-villette-knower', 'md5': 'a0a4b195f544645073631cbec166a2c2', 'info_dict': { 'id': '1086697', 'ext': 'mp4', 'title': 'Jazz à la Villette : Knower', }, }, { 'url': 'http://live.philharmoniedeparis.fr/concert/1032066.html', 'info_dict': { 'id': '1032066', 'title': 'md5:0a031b81807b3593cffa3c9a87a167a0', }, 'playlist_mincount': 2, }, { 'url': 'http://live.philharmoniedeparis.fr/Concert/1030324.html', 'only_matching': True, }, { 'url': 'http://live.philharmoniedeparis.fr/misc/Playlist.ashx?id=1030324&track=&lang=fr', 'only_matching': True, }] _LIVE_URL = 'https://live.philharmoniedeparis.fr' def _real_extract(self, url): video_id = self._match_id(url) config = self._download_json( '%s/otoPlayer/config.ashx' % self._LIVE_URL, video_id, query={ 'id': video_id, 'lang': 'fr-FR', }) def e
source): if not isinstance(source, dict): return title = source.get('title') if not title: return files = source.get('files') if not isinstance(files, dict): return format_urls = set() formats = [] for format_id in ('mobile', 'desktop'): format_url = try_get( files, lambda x: x[format_id]['file'], compat_str) if not format_url or format_url in format_urls: continue format_urls.add(format_url) m3u8_url = urljoin(self._LIVE_URL, format_url) formats.extend(self._extract_m3u8_formats( m3u8_url, video_id, 'mp4', entry_protocol='m3u8_native', m3u8_id='hls', fatal=False)) if not formats: return self._sort_formats(formats) return { 'title': title, 'formats': formats, } thumbnail = urljoin(self._LIVE_URL, config.get('image')) info = extract_entry(config) if info: info.update({ 'id': video_id, 'thumbnail': thumbnail, }) return info entries = [] for num, chapter in enumerate(config['chapters'], start=1): entry = extract_entry(chapter) entry['id'] = '%s-%d' % (video_id, num) entries.append(entry) return self.playlist_result(entries, video_id, config.get('title'))
xtract_entry(
main.rs
fn
() { //i8, u8, i16, u16, i32, u32, i64, u64, isize, usize //f32, f64 let a = 1 + 20; let s = 51 - 44; let d = 4 / 6; let d = 49 % 6; //bool: true/false let c: char = 'z'; println!("{}", c); let t: (i32, f64, char) = (42, 6.12, 'j'); let (_, _, x) = t; t.0; let a = [1, 1, 2, 4, 5]; let a: [i32; 5] = [1, 1, 2, 4, 5]; let a1 = a[0]; }
main
parser_test.go
package parser import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/zclconf/go-cty/cty" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func Test_BasicParsing(t *testing.T) { parser := New() path := createTestFile("test.tf", ` locals { proxy = var.cats_mother } variable "cats_mother" { default = "boots" } provider "cats" { } resource "cats_cat" "mittens" { name = "mittens" special = true } resource "cats_kitten" "the-great-destroyer" { name = "the great destroyer" parent = cats_cat.mittens.name } data "cats_cat" "the-cats-mother" { name = local.proxy } `) blocks, err := parser.ParseDirectory(filepath.Dir(path)) if err != nil { t.Fatal(err) } // variable variables := blocks.OfType("variable") require.Len(t, variables, 1) assert.Equal(t, "variable", variables[0].Type()) require.Len(t, variables[0].Labels(), 1) assert.Equal(t, "cats_mother", variables[0].Labels()[0]) defaultVal := variables[0].GetAttribute("default") require.NotNil(t, defaultVal) assert.Equal(t, cty.String, defaultVal.Value().Type()) assert.Equal(t, "boots", defaultVal.Value().AsString()) // provider providerBlocks := blocks.OfType("provider") require.Len(t, providerBlocks, 1) assert.Equal(t, "provider", providerBlocks[0].Type()) require.Len(t, providerBlocks[0].Labels(), 1) assert.Equal(t, "cats", providerBlocks[0].Labels()[0]) // resources resourceBlocks := blocks.OfType("resource") require.Len(t, resourceBlocks, 2) require.Len(t, resourceBlocks[0].Labels(), 2) assert.Equal(t, "resource", resourceBlocks[0].Type()) assert.Equal(t, "cats_cat", resourceBlocks[0].Labels()[0]) assert.Equal(t, "mittens", resourceBlocks[0].Labels()[1]) assert.Equal(t, "mittens", resourceBlocks[0].GetAttribute("name").Value().AsString()) assert.True(t, resourceBlocks[0].GetAttribute("special").Value().True()) assert.Equal(t, "resource", resourceBlocks[1].Type()) assert.Equal(t, "cats_kitten", resourceBlocks[1].Labels()[0]) assert.Equal(t, "the great destroyer", resourceBlocks[1].GetAttribute("name").Value().AsString()) assert.Equal(t, "mittens", resourceBlocks[1].GetAttribute("parent").Value().AsString()) // data dataBlocks := blocks.OfType("data") require.Len(t, dataBlocks, 1) require.Len(t, dataBlocks[0].Labels(), 2) assert.Equal(t, "data", dataBlocks[0].Type()) assert.Equal(t, "cats_cat", dataBlocks[0].Labels()[0]) assert.Equal(t, "the-cats-mother", dataBlocks[0].Labels()[1]) assert.Equal(t, "boots", dataBlocks[0].GetAttribute("name").Value().AsString()) } func Test_Modules(t *testing.T) { path := createTestFileWithModule(` module "my-mod" { source = "../module" input = "ok" } output "result" { value = module.my-mod.result } `, ` variable "input" { default = "?" } output "result" { value = var.input } `, "module", ) parser := New() blocks, err := parser.ParseDirectory(path) if err != nil { t.Fatal(err) } modules := blocks.OfType("module") require.Len(t, modules, 1) module := modules[0] assert.Equal(t, "module", module.Type()) assert.Equal(t, "module.my-mod", module.Name()) inputAttr := module.GetAttribute("input") require.NotNil(t, inputAttr) require.Equal(t, cty.String, inputAttr.Value().Type()) assert.Equal(t, "ok", inputAttr.Value().AsString()) outputs := blocks.OfType("output") require.Len(t, outputs, 1) output := outputs[0] assert.Equal(t, "output.result", output.Name()) valAttr := output.GetAttribute("value") require.NotNil(t, valAttr) require.Equal(t, cty.String, valAttr.Type()) assert.Equal(t, "ok", valAttr.Value().AsString()) } func Test_NestedParentModule(t *testing.T) { path := createTestFileWithModule(` module "my-mod" { source = "../." input = "ok" } output "result" { value = module.my-mod.result } `, ` variable "input" { default = "?" } output "result" { value = var.input } `, "", ) parser := New() blocks, err := parser.ParseDirectory(path) if err != nil { t.Fatal(err) } modules := blocks.OfType("module") require.Len(t, modules, 1) module := modules[0] assert.Equal(t, "module", module.Type()) assert.Equal(t, "module.my-mod", module.Name()) inputAttr := module.GetAttribute("input") require.NotNil(t, inputAttr) require.Equal(t, cty.String, inputAttr.Value().Type()) assert.Equal(t, "ok", inputAttr.Value().AsString()) outputs := blocks.OfType("output") require.Len(t, outputs, 1) output := outputs[0] assert.Equal(t, "output.result", output.Name()) valAttr := output.GetAttribute("value") require.NotNil(t, valAttr) require.Equal(t, cty.String, valAttr.Type()) assert.Equal(t, "ok", valAttr.Value().AsString()) } func
(filename, contents string) string { dir, err := ioutil.TempDir(os.TempDir(), "tfsec") if err != nil { panic(err) } path := filepath.Join(dir, filename) if err := ioutil.WriteFile(path, []byte(contents), 0755); err != nil { panic(err) } return path } func createTestFileWithModule(contents string, moduleContents string, moduleName string) string { dir, err := ioutil.TempDir(os.TempDir(), "tfsec") if err != nil { panic(err) } rootPath := filepath.Join(dir, "main") modulePath := dir if len(moduleName) > 0 { modulePath = filepath.Join(modulePath, moduleName) } if err := os.Mkdir(rootPath, 0755); err != nil { panic(err) } if modulePath != dir { if err := os.Mkdir(modulePath, 0755); err != nil { panic(err) } } if err := ioutil.WriteFile(filepath.Join(rootPath, "main.tf"), []byte(contents), 0755); err != nil { panic(err) } if err := ioutil.WriteFile(filepath.Join(modulePath, "main.tf"), []byte(moduleContents), 0755); err != nil { panic(err) } return rootPath }
createTestFile
joi-phone-number.d.ts
declare module 'joi-phone-number';
limits_h.rs
pub const INT_MAX: libc::c_int = crate::internal::__INT_MAX__;
pub const INT_MIN: libc::c_int = -crate::internal::__INT_MAX__ - 1 as libc::c_int; pub const CHAR_BIT: libc::c_int = 8 as libc::c_int;
main.rs
// Copyright (C) 2017-2019 Baidu, Inc. All Rights Reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in // the documentation and/or other materials provided with the // distribution. // * Neither the name of Baidu, Inc., nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #![allow(deprecated)] extern crate sgx_types; extern crate sgx_urts; extern crate dirs; use sgx_types::*; use sgx_urts::SgxEnclave; extern crate mio; use mio::tcp::TcpStream; use std::os::unix::io::AsRawFd; use std::ffi::CString; use std::fs; use std::path; use std::net::SocketAddr; use std::str; use std::ptr; use std::io::{self, Read, Write}; const BUFFER_SIZE: usize = 1024; static ENCLAVE_FILE: &'static str = "enclave.signed.so"; static ENCLAVE_TOKEN: &'static str = "enclave.token"; extern { fn tls_client_new(eid: sgx_enclave_id_t, retval: *mut *const c_void, fd: c_int, hostname: *const c_char, cert: *const c_char) -> sgx_status_t; fn tls_client_read(eid: sgx_enclave_id_t, retval: *mut c_int, session: *const c_void, buf: *mut c_void, cnt: c_int) -> sgx_status_t; fn tls_client_write(eid: sgx_enclave_id_t, retval: *mut c_int, session: *const c_void, buf: *const c_void, cnt: c_int) -> sgx_status_t; fn tls_client_wants_read(eid: sgx_enclave_id_t, retval: *mut c_int, session: *const c_void) -> sgx_status_t; fn tls_client_wants_write(eid: sgx_enclave_id_t, retval: *mut c_int, session: *const c_void) -> sgx_status_t; fn tls_client_close(eid: sgx_enclave_id_t, session: *const c_void) -> sgx_status_t; } fn init_enclave() -> SgxResult<SgxEnclave> { let mut launch_token: sgx_launch_token_t = [0; 1024]; let mut launch_token_updated: i32 = 0; // Step 1: try to retrieve the launch token saved by last transaction // if there is no token, then create a new one. // // try to get the token saved in $HOME */ let mut home_dir = path::PathBuf::new(); let use_token = match dirs::home_dir() { Some(path) => { println!("[+] Home dir is {}", path.display()); home_dir = path; true }, None => { println!("[-] Cannot get home dir"); false } }; let token_file: path::PathBuf = home_dir.join(ENCLAVE_TOKEN);; if use_token == true { match fs::File::open(&token_file) { Err(_) => { println!("[-] Open token file {} error! Will create one.", token_file.as_path().to_str().unwrap()); }, Ok(mut f) => { println!("[+] Open token file success! "); match f.read(&mut launch_token) { Ok(1024) => { println!("[+] Token file valid!"); }, _ => println!("[+] Token file invalid, will create new token file"), } } } } // Step 2: call sgx_create_enclave to initialize an enclave instance // Debug Support: set 2nd parameter to 1 let debug = 1; let mut misc_attr = sgx_misc_attribute_t {secs_attr: sgx_attributes_t { flags:0, xfrm:0}, misc_select:0}; let enclave = try!(SgxEnclave::create(ENCLAVE_FILE, debug, &mut launch_token, &mut launch_token_updated, &mut misc_attr)); // Step 3: save the launch token if it is updated if use_token == true && launch_token_updated != 0 { // reopen the file with write capablity match fs::File::create(&token_file) { Ok(mut f) => { match f.write_all(&launch_token) { Ok(()) => println!("[+] Saved updated launch token!"), Err(_) => println!("[-] Failed to save updated launch token!"),
}, Err(_) => { println!("[-] Failed to save updated enclave token, but doesn't matter"); }, } } Ok(enclave) } const CLIENT: mio::Token = mio::Token(0); /// This encapsulates the TCP-level connection, some connection /// state, and the underlying TLS-level session. struct TlsClient { enclave_id: sgx_enclave_id_t, socket: TcpStream, closing: bool, tlsclient: *const c_void, } impl TlsClient { fn ready(&mut self, poll: &mut mio::Poll, ev: &mio::Event) -> bool { assert_eq!(ev.token(), CLIENT); if ev.readiness().is_error() { println!("Error"); return false; } if ev.readiness().is_readable() { self.do_read(); } if ev.readiness().is_writable() { self.do_write(); } if self.is_closed() { println!("Connection closed"); return false; } self.reregister(poll); true } } impl TlsClient { fn new(enclave_id: sgx_enclave_id_t, sock: TcpStream, hostname: &str, cert: &str) -> Option<TlsClient> { println!("[+] TlsClient new {} {}", hostname, cert); let mut tlsclient: *const c_void = ptr::null(); let c_host = CString::new(hostname.to_string()).unwrap(); let c_cert = CString::new(cert.to_string()).unwrap(); let retval = unsafe { tls_client_new(enclave_id, &mut tlsclient as *mut *const c_void, sock.as_raw_fd(), c_host.as_ptr() as *const c_char, c_cert.as_ptr() as *const c_char) }; if retval != sgx_status_t::SGX_SUCCESS { println!("[-] ECALL Enclave [tls_client_new] Failed {}!", retval); return Option::None; } if tlsclient.is_null() { println!("[-] New enclave tlsclient error"); return Option::None; } Option::Some( TlsClient { enclave_id: enclave_id, socket: sock, closing: false, tlsclient: tlsclient as *const c_void, }) } fn close(&self) { let retval = unsafe { tls_client_close(self.enclave_id, self.tlsclient) }; if retval != sgx_status_t::SGX_SUCCESS { println!("[-] ECALL Enclave [tls_client_close] Failed {}!", retval); } } fn read_tls(&self, buf: &mut [u8]) -> isize { let mut retval = -1; let result = unsafe { tls_client_read(self.enclave_id, &mut retval, self.tlsclient, buf.as_mut_ptr() as * mut c_void, buf.len() as c_int) }; match result { sgx_status_t::SGX_SUCCESS => { retval as isize } _ => { println!("[-] ECALL Enclave [tls_client_read] Failed {}!", result); -1 } } } fn write_tls(&self, buf: &[u8]) -> isize { let mut retval = -1; let result = unsafe { tls_client_write(self.enclave_id, &mut retval, self.tlsclient, buf.as_ptr() as * const c_void, buf.len() as c_int) }; match result { sgx_status_t::SGX_SUCCESS => { retval as isize } _ => { println!("[-] ECALL Enclave [tls_client_write] Failed {}!", result); -1 } } } /// We're ready to do a read. fn do_read(&mut self) { // BUFFER_SIZE = 1024, just for test. // Do read all plaintext, you need to do more ecalls to get buffer size and buffer. let mut plaintext = vec![0; BUFFER_SIZE]; let rc = self.read_tls(plaintext.as_mut_slice()); if rc == -1 { println!("TLS read error: {:?}", rc); self.closing = true; return; } plaintext.resize(rc as usize, 0); io::stdout().write_all(&plaintext).unwrap(); } fn do_write(&mut self) { let buf = Vec::new(); self.write_tls(buf.as_slice()); } fn register(&self, poll: &mut mio::Poll) { poll.register(&self.socket, CLIENT, self.ready_interest(), mio::PollOpt::level() | mio::PollOpt::oneshot()) .unwrap(); } fn reregister(&self, poll: &mut mio::Poll) { poll.reregister(&self.socket, CLIENT, self.ready_interest(), mio::PollOpt::level() | mio::PollOpt::oneshot()) .unwrap(); } fn wants_read(&self) -> bool { let mut retval = -1; let result = unsafe { tls_client_wants_read(self.enclave_id, &mut retval, self.tlsclient) }; match result { sgx_status_t::SGX_SUCCESS => { }, _ => { println!("[-] ECALL Enclave [tls_client_wants_read] Failed {}!", result); return false; } } match retval { 0 => false, _ => true } } fn wants_write(&self) -> bool { let mut retval = -1; let result = unsafe { tls_client_wants_write(self.enclave_id, &mut retval, self.tlsclient) }; match result { sgx_status_t::SGX_SUCCESS => { }, _ => { println!("[-] ECALL Enclave [tls_client_wants_write] Failed {}!", result); return false; } } match retval { 0 => false, _ => true } } // Use wants_read/wants_write to register for different mio-level // IO readiness events. fn ready_interest(&self) -> mio::Ready { let rd = self.wants_read(); let wr = self.wants_write(); if rd && wr { mio::Ready::readable() | mio::Ready::writable() } else if wr { mio::Ready::writable() } else { mio::Ready::readable() } } fn is_closed(&self) -> bool { self.closing } } /// We implement `io::Write` and pass through to the TLS session impl io::Write for TlsClient { fn write(&mut self, bytes: &[u8]) -> io::Result<usize> { Ok(self.write_tls(bytes) as usize) } // unused fn flush(&mut self) -> io::Result<()> { Ok(()) } } impl io::Read for TlsClient { fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> { Ok(self.read_tls(bytes) as usize) } } fn lookup_ipv4(host: &str, port: u16) -> SocketAddr { use std::net::ToSocketAddrs; let addrs = (host, port).to_socket_addrs().unwrap(); for addr in addrs { if let SocketAddr::V4(_) = addr { return addr; } } unreachable!("Cannot lookup address"); } fn main() { let enclave = match init_enclave() { Ok(r) => { println!("[+] Init Enclave Successful {}!", r.geteid()); r }, Err(x) => { println!("[-] Init Enclave Failed {}!", x.as_str()); return; }, }; println!("[+] Test tlsclient in enclave, start!"); let port = 8443; let hostname = "localhost"; let cert = "./ca.cert"; let addr = lookup_ipv4(hostname, port); let sock = TcpStream::connect(&addr).expect("[-] Connect tls server failed!"); let tlsclient = TlsClient::new(enclave.geteid(), sock, hostname, cert); if tlsclient.is_some() { println!("[+] Tlsclient new success!"); let mut tlsclient = tlsclient.unwrap(); let httpreq = format!("GET / HTTP/1.1\r\nHost: {}\r\nConnection: \ close\r\nAccept-Encoding: identity\r\n\r\n", hostname); tlsclient.write_all(httpreq.as_bytes()).unwrap(); let mut poll = mio::Poll::new() .unwrap(); let mut events = mio::Events::with_capacity(32); tlsclient.register(&mut poll); 'outer: loop { poll.poll(&mut events, None).unwrap(); for ev in events.iter() { if !tlsclient.ready(&mut poll, &ev) { tlsclient.close(); break 'outer ; } } } } else { println!("[-] Tlsclient new failed!"); } println!("[+] Test tlsclient in enclave, done!"); enclave.destroy(); }
}
dependencies.go
package model import ( "github.com/mongodb/grip" "github.com/pkg/errors" ) type dependencyIncluder struct { Project *Project requester string included map[TVPair]bool } // IncludeDependencies takes a project and a slice of variant/task pairs names // and returns the expanded set of variant/task pairs to include all the dependencies/requirements // for the given set of tasks. // If any dependency is cross-variant, it will include the variant and task for that dependency. // This function can return an error, but it should be treated as an informational warning func IncludeDependencies(project *Project, tvpairs []TVPair, requester string) ([]TVPair, error) { di := &dependencyIncluder{Project: project, requester: requester} return di.include(tvpairs) } // include crawls the tasks represented by the combination of variants and tasks and // add or removes tasks based on the dependency graph. Dependent tasks // are added; tasks that depend on unreachable tasks are pruned. New slices // of variants and tasks are returned. func (di *dependencyIncluder) include(initialDeps []TVPair) ([]TVPair, error) { di.included = map[TVPair]bool{} warnings := grip.NewBasicCatcher() // handle each pairing, recursively adding and pruning based // on the task's dependencies for _, d := range initialDeps { _, err := di.handle(d) warnings.Add(err) } outPairs := []TVPair{} for pair, shouldInclude := range di.included { if shouldInclude { outPairs = append(outPairs, pair) } } return outPairs, warnings.Resolve() } // handle finds and includes all tasks that the given task/variant pair depends // on. Returns true if the task and all of its dependent tasks can be scheduled // for the requester. Returns false if it cannot be scheduled, with an error // explaining why func (di *dependencyIncluder) handle(pair TVPair) (bool, error) { if included, ok := di.included[pair]; ok { // we've been here before, so don't redo work return included, nil } // if the given task is a task group, recurse on each task if tg := di.Project.FindTaskGroup(pair.TaskName); tg != nil { for _, t := range tg.Tasks { ok, err := di.handle(TVPair{TaskName: t, Variant: pair.Variant}) if !ok { di.included[pair] = false return false, errors.Wrapf(err, "task group '%s' in variant '%s' contains unschedulable task '%s'", pair.TaskName, pair.Variant, t) } } return true, nil } // we must load the BuildVariantTaskUnit for the task/variant pair, // since it contains the full scope of dependency information bvt := di.Project.FindTaskForVariant(pair.TaskName, pair.Variant) if bvt == nil { di.included[pair] = false return false, errors.Errorf("task '%s' does not exist in project '%s' for variant '%s'", pair.TaskName, di.Project.Identifier, pair.Variant) } if bvt.SkipOnRequester(di.requester) { di.included[pair] = false return false, errors.Errorf("task '%s' in variant '%s' cannot be run for a '%s'", pair.TaskName, pair.Variant, di.requester) } di.included[pair] = true // queue up all dependencies for recursive inclusion deps := di.expandDependencies(pair, bvt.DependsOn) for _, dep := range deps { ok, err := di.handle(dep) if !ok { di.included[pair] = false return false, errors.Wrapf(err, "task '%s' in variant '%s' has an unschedulable dependency", pair.TaskName, pair.Variant) } } // we've reached a point where we know it is safe to include the current task return true, nil } // expandDependencies finds all tasks depended on by the current task/variant pair. func (di *dependencyIncluder) expandDependencies(pair TVPair, depends []TaskUnitDependency) []TVPair { deps := []TVPair{} for _, d := range depends { // don't automatically add dependencies if they are marked patch_optional if d.PatchOptional { continue } switch { case d.Variant == AllVariants && d.Name == AllDependencies: // task = *, variant = * // Here we get all variants and tasks (excluding the current task) // and add them to the list of tasks and variants. for _, v := range di.Project.BuildVariants { for _, t := range v.Tasks { if t.Name == pair.TaskName && v.Name == pair.Variant { continue } projectTask := di.Project.FindTaskForVariant(t.Name, v.Name) if projectTask != nil
} } case d.Variant == AllVariants: // specific task, variant = * // In the case where we depend on a task on all variants, we fetch the task's // dependencies, then add that task for all variants that have it. for _, v := range di.Project.BuildVariants { for _, t := range v.Tasks { if t.Name != d.Name { continue } if t.Name == pair.TaskName && v.Name == pair.Variant { continue } projectTask := di.Project.FindTaskForVariant(t.Name, v.Name) if projectTask != nil { if projectTask.SkipOnRequester(di.requester) { continue } deps = append(deps, TVPair{TaskName: t.Name, Variant: v.Name}) } } } case d.Name == AllDependencies: // task = *, specific variant // Here we add every task for a single variant. We add the dependent variant, // then add all of that variant's task, as well as their dependencies. v := d.Variant if v == "" { v = pair.Variant } variant := di.Project.FindBuildVariant(v) if variant != nil { for _, t := range variant.Tasks { if t.Name == pair.TaskName { continue } projectTask := di.Project.FindTaskForVariant(t.Name, v) if projectTask != nil { if projectTask.SkipOnRequester(di.requester) { continue } deps = append(deps, TVPair{TaskName: t.Name, Variant: variant.Name}) } } } default: // specific name, specific variant // We simply add a single task/variant and its dependencies. This does not do // the requester check above because we assume the user has configured this // correctly v := d.Variant if v == "" { v = pair.Variant } deps = append(deps, TVPair{TaskName: d.Name, Variant: v}) } } return deps }
{ if projectTask.SkipOnRequester(di.requester) { continue } deps = append(deps, TVPair{TaskName: t.Name, Variant: v.Name}) }
index.ts
export * from './nft' export * from './api' export * from './transactions' export * from './query' export * from './red-envelope'
export * from './geetest'
export * from './search'
abci.go
package client import ( "encoding/binary" "encoding/json" "fmt" "github.com/tendermint/tendermint/abci/example/code" "github.com/tendermint/tendermint/abci/types" "github.com/tendermint/tendermint/version" "webchatABCI/query" "webchatABCI/txn" "github.com/tendermint/tendermint/libs/db" ) var ( stateKey = []byte("webchat") ProtocolVersion version.Protocol = 0x1 ) func loadState(db db.DB) State { stateBytes := db.Get(stateKey) var cState State if len(stateBytes) != 0 { err := json.Unmarshal(stateBytes, &cState) if err != nil { panic(err) } } else { cState = State{ ChainID: "chain0", Size: 0, Height: 0, AppHash: []byte{}, MessageTimestamp: 0, } } cState.db = db return cState } func saveState(state State) { stateBytes, err := json.Marshal(state) if err != nil { panic(err) } state.db.Set(stateKey, stateBytes) } var _ types.Application = (*WebChatApplication)(nil) type WebChatApplication struct { types.BaseApplication state State } func (app *WebChatApplication) GetState() *State { return &app.state } type Txn struct { Type string `json:"type"` Data interface{} `json:"data"` Nonce []byte `json:"nonce"` } func (app *WebChatApplication) Info(req types.RequestInfo) types.ResponseInfo { return types.ResponseInfo{ Data: fmt.Sprintf("{\"size\":%v}", app.state.Size), Version: version.ABCIVersion, AppVersion: ProtocolVersion.Uint64(), } } func NewWebChatApplication() *WebChatApplication { webChat := loadState(db.NewMemDB()) webChat.txnHandler = txn.CreateNewTxnHandler(&webChat.MessageTimestamp) webChat.queryHandler = query.CreateQueryHandler(&webChat.MessageTimestamp) return &WebChatApplication{state: webChat} } func (app *WebChatApplication) CheckTx(tx []byte) types.ResponseCheckTx { obj := &Txn{} err := json.Unmarshal(tx, obj) if err != nil { return types.ResponseCheckTx{Code: code.CodeTypeEncodingError} } txnHandler := app.state.txnHandler.GetTxnHandler(obj.Type) if txnHandler == nil { return types.ResponseCheckTx{ Code: code.CodeTypeUnknownError, Log: fmt.Sprintf(`No Txn handler match "%v"`, obj.Type), } } return txnHandler.Check(app.state.db, obj.Data) } func (app *WebChatApplication) DeliverTx(tx []byte) types.ResponseDeliverTx { obj := &Txn{} err := json.Unmarshal(tx, obj) if err != nil { return types.ResponseDeliverTx{Code: code.CodeTypeEncodingError} } txnHandler := app.state.txnHandler.GetTxnHandler(obj.Type) if txnHandler == nil { return types.ResponseDeliverTx{ Code: code.CodeTypeUnknownError, Log: fmt.Sprintf(`No Txn handler match "%v"`, obj.Type), } } return txnHandler.Deliver(app.state.db, obj.Data) } func (app *WebChatApplication) Commit() types.ResponseCommit { // Using a memdb - just return the big endian size of the db appHash := make([]byte, 8) binary.PutVarint(appHash, app.state.Size) app.state.AppHash = appHash app.state.Height += 1 saveState(app.state) return types.ResponseCommit{Data: appHash} } func (app *WebChatApplication) Query(reqQuery types.RequestQuery) (resQuery types.ResponseQuery) { data := reqQuery.GetData() obj := &Txn{} err := json.Unmarshal(data, obj) if err != nil {
queryHandler := app.state.queryHandler.GetQueryHandler(obj.Type) if queryHandler == nil { return types.ResponseQuery { Code: code.CodeTypeUnknownError, Log: fmt.Sprintf(`No Query handler match "%v"`, obj.Type), } } reqQuery.Data, _ = json.Marshal(obj.Data) return queryHandler.Query(app.state.db, reqQuery) }
return types.ResponseQuery{Code: code.CodeTypeEncodingError} }
tutorial-setting-list.js
import { css, html } from 'lit-element' import { connect } from 'pwa-helpers/connect-mixin.js' import { i18next, localize } from '@things-factory/i18n-base' import { openPopup } from '@things-factory/layout-base' import gql from 'graphql-tag' import { client, CustomAlert, PageView, store } from '@things-factory/shell' import { ScrollbarStyles } from '@things-factory/styles' import { gqlBuilder, isMobileDevice } from '@things-factory/utils' import '@things-factory/form-ui' import '@things-factory/grist-ui' import './tutorial-detail' class
extends connect(store)(localize(i18next)(PageView)) { static get properties() { return { _searchFields: Array, config: Object, data: Object } } static get styles() { return [ ScrollbarStyles, css` :host { display: flex; flex-direction: column; overflow: hidden; } search-form { overflow: visible; } data-grist { overflow-y: auto; flex: 1; } ` ] } get context() { return { title: i18next.t('title.tutorial_setting'), actions: [ { title: i18next.t('button.save'), action: this._saveTutorial.bind(this) }, { title: i18next.t('button.delete'), action: this._deleteTutorial.bind(this) } ] } } render() { return html` <search-form id="search-form" .fields=${this._searchFields} @submit=${() => this.dataGrist.fetch()}></search-form> <data-grist .mode=${isMobileDevice() ? 'LIST' : 'GRID'} .config=${this.config} .fetchHandler="${this.fetchHandler.bind(this)}" ></data-grist> ` } pageUpdated(changes, lifecycle) { if (this.active) { this.dataGrist.fetch() } } async pageInitialized() { this._searchFields = [ { name: 'name', label: i18next.t('field.name'), type: 'text', props: { searchOper: 'i_like' } }, { name: 'description', label: i18next.t('field.description'), type: 'text', props: { searchOper: 'i_like' } }, { name: 'resourceUrl', name: i18next.t('field.resource_url'), type: 'text', props: { searchOper: 'i_like' } } ] this.config = { rows: { selectable: { multiple: true } }, columns: [ { type: 'gutter', gutterName: 'sequence' }, { type: 'gutter', gutterName: 'row-selector', multiple: true }, { type: 'gutter', gutterName: 'button', icon: 'reorder', handlers: { click: (columns, data, column, record, rowIndex) => { openPopup( html` <tutorial-detail @role-updated="${() => { document.dispatchEvent( new CustomEvent('notify', { detail: { message: i18next.t('text.info_update_successfully') } }) ) this.dataGrist.fetch() }}" .tutorialId="${record.id}" .name="${record.name}" .description="${record.description}" ></tutorial-detail> `, { backdrop: true, size: 'large', title: `${i18next.t('title.tutorial_detail')} - ${record.name}` } ) } } }, { type: 'string', name: 'name', header: i18next.t('field.name'), record: { editable: true, align: 'left' }, sortable: true, width: 200 }, { type: 'string', name: 'description', header: i18next.t('field.description'), record: { editable: true, align: 'left' }, sortable: true, width: 300 }, { type: 'string', name: 'resourceUrl', header: i18next.t('field.resource_url'), record: { editable: true, align: 'left' }, sortable: true, width: 300 }, { type: 'string', name: 'value', header: i18next.t('field.value'), record: { editable: true, align: 'left' }, sortable: true, width: 300 }, { type: 'string', name: 'duration', header: i18next.t('field.duration'), record: { editable: true, align: 'left' }, sortable: true, width: 300 }, { type: 'integer', name: 'rank', header: i18next.t('field.rank'), record: { editable: true, align: 'center' }, sortable: true, width: 80 } ] } } get searchForm() { return this.shadowRoot.querySelector('search-form') } get dataGrist() { return this.shadowRoot.querySelector('data-grist') } async fetchHandler({ page, limit, sorters = [] }) { const response = await client.query({ query: gql` query { tutorials(${gqlBuilder.buildArgs({ filters: this.searchForm.queryFilters, pagination: { page, limit }, sortings: sorters })}) { items { id name description resourceUrl value duration rank } total } } ` }) return { total: response.data.tutorials.total || 0, records: response.data.tutorials.items || [] } } async _saveTutorial() { let patches = this.dataGrist.exportPatchList({ flagName: 'cuFlag' }) if (patches && patches.length) { const response = await client.query({ query: gql` mutation { updateMultipleTutorial(${gqlBuilder.buildArgs({ patches })}) { id name description resourceUrl value duration rank } } ` }) if (!response.errors) { this.dataGrist.fetch() document.dispatchEvent( new CustomEvent('notify', { detail: { message: i18next.t('text.data_updated_successfully') } }) ) } } } async _deleteTutorial() { CustomAlert({ title: i18next.t('text.are_you_sure'), text: i18next.t('text.you_wont_be_able_to_revert_this'), type: 'warning', confirmButton: { text: i18next.t('button.delete'), color: '#22a6a7' }, cancelButton: { text: 'cancel', color: '#cfcfcf' }, callback: async result => { if (result.value) { const ids = this.dataGrist.selected.map(record => record.id) if (ids && ids.length > 0) { const response = await client.query({ query: gql` mutation { deleteTutorials(${gqlBuilder.buildArgs({ ids })}) } ` }) if (!response.errors) { this.dataGrist.fetch() document.dispatchEvent( new CustomEvent('notify', { detail: { message: i18next.t('text.data_deleted_successfully') } }) ) } } } } }) } _showToast({ type, message }) { document.dispatchEvent( new CustomEvent('notify', { detail: { type, message } }) ) } } window.customElements.define('tutorial-setting-list', TutorialSettingList)
TutorialSettingList
assessments.py
# Copyright 2012 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Classes and methods to manage all aspects of student assessments.""" __author__ = '[email protected] (Philip Guo)' import datetime import json from models import models from models import utils from models.models import Student from models.models import StudentAnswersEntity from utils import BaseHandler from google.appengine.ext import db def store_score(student, assessment_type, score): """Stores a student's score on a particular assessment. Args: student: the student whose data is stored. assessment_type: the type of the assessment. score: the student's score on this assessment. Returns: the (possibly modified) assessment_type, which the caller can use to render an appropriate response page. """ # FIXME: Course creators can edit this code to implement custom # assessment scoring and storage behavior # TODO(pgbovine): Note that the latest version of answers are always saved, # but scores are only saved if they're higher than the previous attempt. # This can lead to unexpected analytics behavior. Resolve this. existing_score = utils.get_score(student, assessment_type) # remember to cast to int for comparison if (existing_score is None) or (score > int(existing_score)): utils.set_score(student, assessment_type, score) # special handling for computing final score: if assessment_type == 'postcourse': midcourse_score = utils.get_score(student, 'midcourse') if midcourse_score is None: midcourse_score = 0 else: midcourse_score = int(midcourse_score) if existing_score is None: postcourse_score = score else: postcourse_score = int(existing_score) if score > postcourse_score: postcourse_score = score # Calculate overall score based on a formula overall_score = int((0.3 * midcourse_score) + (0.7 * postcourse_score)) # TODO(pgbovine): this changing of assessment_type is ugly ... if overall_score >= 70: assessment_type = 'postcourse_pass' else: assessment_type = 'postcourse_fail' utils.set_score(student, 'overall_score', overall_score) return assessment_type class AnswerHandler(BaseHandler): """Handler for saving assessment answers.""" # Find student entity and save answers @db.transactional(xg=True) def
( self, email, assessment_type, new_answers, score): """Stores answer and updates user scores.""" student = Student.get_by_email(email) # It may be that old Student entities don't have user_id set; fix it. if not student.user_id: student.user_id = self.get_user().user_id() answers = StudentAnswersEntity.get_by_key_name(student.user_id) if not answers: answers = StudentAnswersEntity(key_name=student.user_id) answers.updated_on = datetime.datetime.now() utils.set_answer(answers, assessment_type, new_answers) assessment_type = store_score(student, assessment_type, score) student.put() answers.put() # Also record the event, which is useful for tracking multiple # submissions and history. models.EventEntity.record( 'submit-assessment', self.get_user(), json.dumps({ 'type': 'assessment-%s' % assessment_type, 'values': new_answers, 'location': 'AnswerHandler'})) return (student, assessment_type) def post(self): """Handles POST requests.""" student = self.personalize_page_and_get_enrolled() if not student: return if not self.assert_xsrf_token_or_fail(self.request, 'assessment-post'): return assessment_type = self.request.get('assessment_type') # Convert answers from JSON to dict. answers = self.request.get('answers') if answers: answers = json.loads(answers) else: answers = [] # TODO(pgbovine): consider storing as float for better precision score = int(round(float(self.request.get('score')))) # Record score. (student, assessment_type) = self.update_assessment_transaction( student.key().name(), assessment_type, answers, score) self.template_value['navbar'] = {'course': True} self.template_value['assessment'] = assessment_type self.template_value['student_score'] = utils.get_score( student, 'overall_score') self.render('test_confirmation.html')
update_assessment_transaction
bot_config.py
import configparser class BotConfig: def
(self, path): parser = configparser.ConfigParser() # open the file implicitly because parser.read() will not fail if file is not readable file = open(path) parser.read_file(file) file.close() if 'Bot' not in parser.sections(): raise Exception('All parameters must reside in section ''Bot''') bot_section = parser['Bot'] self.address = bot_section.get('address', 'localhost') port_string = bot_section.get('port', '9091') try: self.port = int(port_string) except ValueError: raise ValueError('Port ''%s'' is invalid' % port_string) try: self.user = bot_section.get('user') except KeyError: self.user = None try: self.password = bot_section.get('password') except KeyError: self.password = None if self.password and not self.user: raise Exception('Password with no user name is meaningless') self.token = bot_section.get('token', '') if not self.token: raise Exception('Telegram token is required') self.secret = bot_section.get('secret', '') if not self.secret: raise Exception('Secret is required') try: self.persistence_file = bot_section.get('persistence_file') except KeyError: self.persistence_file = None def __str__(self): result = '{address:<%s> ' \ 'port:<%d> ' % (self.address, self.port) if not self.user: result += 'user:None ' else: result += 'user:<%s> ' % self.user if not self.password: result += 'password:None' else: result += 'password:present ' result += 'token:present ' result += 'secret:present ' result += 'persistence_file:<%s>}' % self.persistence_file return result def __repr__(self): return '{address:''%s'' port:%d user:''%s'' password:''%s'' ' \ 'token:''%s'' secret:''%s'' persistence_file:''%s''}' \ % (self.address, self.port, self.user, self.password, self.token, self.secret, self.persistence_file)
__init__
scene.ts
import type { Area } from '@src/types'; import easelJS from './easeljs'; export class
extends easelJS.Container { public debug: any = undefined; constructor(public coordonates: Area) { super(); const mtx = this.getMatrix(); mtx.translate(coordonates.x, coordonates.y); this.transformMatrix = mtx; this.setBounds(0, 0, coordonates.width, coordonates.height); } draw(ctx: CanvasRenderingContext2D, ignoreCache: boolean) { // if ((this as any).DisplayObject_draw(ctx, ignoreCache)) { return true; } return super.draw(ctx, ignoreCache); // return true; } }
Scene
impl.go
package inccounter import ( "fmt" "github.com/iotaledger/wasp/packages/iscp" "github.com/iotaledger/wasp/packages/iscp/assert" "github.com/iotaledger/wasp/packages/iscp/coreutil" "github.com/iotaledger/wasp/packages/kv/codec" "github.com/iotaledger/wasp/packages/kv/collections" "github.com/iotaledger/wasp/packages/kv/dict" "github.com/iotaledger/wasp/packages/kv/kvdecoder" "github.com/iotaledger/wasp/packages/vm/core" "github.com/iotaledger/wasp/packages/vm/core/root" ) var Contract = coreutil.NewContract("inccounter", "Increment counter, a PoC smart contract") var Processor = Contract.Processor(initialize, FuncIncCounter.WithHandler(incCounter), FuncIncAndRepeatOnceAfter5s.WithHandler(incCounterAndRepeatOnce), FuncIncAndRepeatMany.WithHandler(incCounterAndRepeatMany), FuncSpawn.WithHandler(spawn), FuncGetCounter.WithHandler(getCounter), ) var ( FuncIncCounter = coreutil.Func("incCounter") FuncIncAndRepeatOnceAfter5s = coreutil.Func("incAndRepeatOnceAfter5s") FuncIncAndRepeatMany = coreutil.Func("incAndRepeatMany") FuncSpawn = coreutil.Func("spawn") FuncGetCounter = coreutil.ViewFunc("getCounter") ) const ( VarNumRepeats = "numRepeats" VarCounter = "counter" VarName = "name" VarDescription = "dscr" ) func initialize(ctx iscp.Sandbox) (dict.Dict, error) { ctx.Log().Debugf("inccounter.init in %s", ctx.Contract().String()) params := ctx.Params() val, _, err := codec.DecodeInt64(params.MustGet(VarCounter)) if err != nil { return nil, fmt.Errorf("incCounter: %v", err) } ctx.State().Set(VarCounter, codec.EncodeInt64(val)) ctx.Event(fmt.Sprintf("inccounter.init.success. counter = %d", val)) return nil, nil } func incCounter(ctx iscp.Sandbox) (dict.Dict, error) { ctx.Log().Debugf("inccounter.incCounter in %s", ctx.Contract().String()) par := kvdecoder.New(ctx.Params(), ctx.Log()) inc := par.MustGetInt64(VarCounter, 1) state := kvdecoder.New(ctx.State(), ctx.Log()) val := state.MustGetInt64(VarCounter, 0) ctx.Log().Infof("incCounter: increasing counter value %d by %d, anchor index: #%d", val, inc, ctx.StateAnchor().StateIndex()) tra := "(empty)" if ctx.IncomingTransfer() != nil { tra = ctx.IncomingTransfer().String() } ctx.Log().Infof("incCounter: incoming transfer: %s", tra) ctx.State().Set(VarCounter, codec.EncodeInt64(val+inc)) return nil, nil } func incCounterAndRepeatOnce(ctx iscp.Sandbox) (dict.Dict, error) { ctx.Log().Debugf("inccounter.incCounterAndRepeatOnce") state := ctx.State() val, _, _ := codec.DecodeInt64(state.MustGet(VarCounter)) ctx.Log().Debugf(fmt.Sprintf("incCounterAndRepeatOnce: increasing counter value: %d", val)) state.Set(VarCounter, codec.EncodeInt64(val+1)) if !ctx.Send(ctx.ChainID().AsAddress(), iscp.NewTransferIotas(1), &iscp.SendMetadata{ TargetContract: ctx.Contract(), EntryPoint: FuncIncCounter.Hname(), }, iscp.SendOptions{ TimeLock: 5 * 60, }) { return nil, fmt.Errorf("incCounterAndRepeatOnce: not enough funds") } ctx.Log().Debugf("incCounterAndRepeatOnce: PostRequestToSelfWithDelay RequestInc 5 sec") return nil, nil } func incCounterAndRepeatMany(ctx iscp.Sandbox) (dict.Dict, error) { ctx.Log().Debugf("inccounter.incCounterAndRepeatMany") state := ctx.State() params := ctx.Params() val, _, _ := codec.DecodeInt64(state.MustGet(VarCounter)) state.Set(VarCounter, codec.EncodeInt64(val+1)) ctx.Log().Debugf("inccounter.incCounterAndRepeatMany: increasing counter value: %d", val) numRepeats, ok, err := codec.DecodeInt64(params.MustGet(VarNumRepeats)) if err != nil { ctx.Log().Panicf("%s", err) } if !ok { numRepeats, _, _ = codec.DecodeInt64(state.MustGet(VarNumRepeats)) } if numRepeats == 0 { ctx.Log().Debugf("inccounter.incCounterAndRepeatMany: finished chain of requests. counter value: %d", val) return nil, nil } ctx.Log().Debugf("chain of %d requests ahead", numRepeats) state.Set(VarNumRepeats, codec.EncodeInt64(numRepeats-1)) if !ctx.Send(ctx.ChainID().AsAddress(), iscp.NewTransferIotas(1), &iscp.SendMetadata{ TargetContract: ctx.Contract(), EntryPoint: FuncIncAndRepeatMany.Hname(), }, iscp.SendOptions{ TimeLock: 1 * 60, }) { ctx.Log().Debugf("incCounterAndRepeatMany. remaining repeats = %d", numRepeats-1) } else { ctx.Log().Debugf("incCounterAndRepeatMany FAILED. remaining repeats = %d", numRepeats-1) } return nil, nil } // spawn deploys new contract and calls it func spawn(ctx iscp.Sandbox) (dict.Dict, error) { ctx.Log().Debugf("inccounter.spawn") state := kvdecoder.New(ctx.State(), ctx.Log()) val := state.MustGetInt64(VarCounter) par := kvdecoder.New(ctx.Params(), ctx.Log()) name := par.MustGetString(VarName) dscr := par.MustGetString(VarDescription, "N/A") a := assert.NewAssert(ctx.Log()) callPar := dict.New() callPar.Set(VarCounter, codec.EncodeInt64(val+1)) err := ctx.DeployContract(Contract.ProgramHash, name, dscr, callPar) a.RequireNoError(err) // increase counter in newly spawned contract hname := iscp.Hn(name) _, err = ctx.Call(hname, FuncIncCounter.Hname(), nil, nil) a.RequireNoError(err) res, err := ctx.Call(root.Contract.Hname(), root.FuncGetChainInfo.Hname(), nil, nil) a.RequireNoError(err) creg := collections.NewMapReadOnly(res, root.VarContractRegistry) a.Require(int(creg.MustLen()) == len(core.AllCoreContractsByHash)+2, "unexpected contract registry len %d", creg.MustLen()) ctx.Log().Debugf("inccounter.spawn: new contract name = %s hname = %s", name, hname.String()) return nil, nil } func
(ctx iscp.SandboxView) (dict.Dict, error) { state := ctx.State() val, _, _ := codec.DecodeInt64(state.MustGet(VarCounter)) ret := dict.New() ret.Set(VarCounter, codec.EncodeInt64(val)) return ret, nil }
getCounter
directives.module.ts
import { CommonModule } from '@angular/common'; import { NgModule } from '@angular/core'; import { DisableControlDirective } from './disable-control.directive'; import { FocusedDirective } from './focused.directive'; @NgModule({ imports: [CommonModule], declarations: [FocusedDirective, DisableControlDirective], exports: [FocusedDirective, DisableControlDirective] }) export class
{}
DirectivesModule
mongo.go
// Description: a session middleware based on mongodb, gorilla-session and gin-gonic // Author: ZHU HAIHUA // Since: 2016-04-07 20:20 package sessions import ( ginsession "github.com/gin-gonic/contrib/sessions" "github.com/gorilla/sessions" "github.com/kidstuff/mongostore" "gopkg.in/mgo.v2" ) type MongoStore interface { ginsession.Store
type mongoStore struct { *mongostore.MongoStore } // NewMongoStore return a session store based on mongodb // func NewMongoStore(s *mgo.Session, dbName, collectionName string, maxAge int, ensureTTL bool, keyPairs ...[]byte) MongoStore { store := mongostore.NewMongoStore(s.DB(dbName).C(collectionName), maxAge, ensureTTL, keyPairs...) return &mongoStore{store} } func (c *mongoStore) Options(options ginsession.Options) { c.MongoStore.Options = &sessions.Options{ Path: options.Path, Domain: options.Domain, MaxAge: options.MaxAge, Secure: options.Secure, HttpOnly: options.HttpOnly, } }
}
mempool_item.py
from dataclasses import dataclass from typing import List from beer.consensus.cost_calculator import NPCResult from beer.types.blockchain_format.coin import Coin from beer.types.blockchain_format.program import SerializedProgram from beer.types.blockchain_format.sized_bytes import bytes32 from beer.types.spend_bundle import SpendBundle from beer.util.ints import uint64 from beer.util.streamable import Streamable, streamable @dataclass(frozen=True) @streamable class MempoolItem(Streamable): spend_bundle: SpendBundle fee: uint64 npc_result: NPCResult cost: uint64 spend_bundle_name: bytes32 additions: List[Coin] removals: List[Coin] program: SerializedProgram def __lt__(self, other): return self.fee_per_cost < other.fee_per_cost @property def fee_per_cost(self) -> float:
@property def name(self) -> bytes32: return self.spend_bundle_name
return int(self.fee) / int(self.cost)
closure.rs
//! Code for type-checking closure expressions. use super::{check_fn, Expectation, FnCtxt, GeneratorTypes}; use crate::astconv::AstConv; use rustc_hir as hir; use rustc_hir::def_id::DefId; use rustc_hir::lang_items::LangItem; use rustc_infer::infer::type_variable::{TypeVariableOrigin, TypeVariableOriginKind}; use rustc_infer::infer::LateBoundRegionConversionTime; use rustc_infer::infer::{InferOk, InferResult}; use rustc_middle::ty::fold::TypeFoldable; use rustc_middle::ty::subst::InternalSubsts; use rustc_middle::ty::{self, Ty}; use rustc_span::source_map::Span; use rustc_target::spec::abi::Abi; use rustc_trait_selection::traits::error_reporting::ArgKind; use rustc_trait_selection::traits::error_reporting::InferCtxtExt as _; use std::cmp; use std::iter; /// What signature do we *expect* the closure to have from context? #[derive(Debug)] struct ExpectedSig<'tcx> { /// Span that gave us this expectation, if we know that. cause_span: Option<Span>, sig: ty::PolyFnSig<'tcx>, } struct ClosureSignatures<'tcx> { bound_sig: ty::PolyFnSig<'tcx>, liberated_sig: ty::FnSig<'tcx>, } impl<'a, 'tcx> FnCtxt<'a, 'tcx> { #[instrument(skip(self, expr, _capture, decl, body_id), level = "debug")] pub fn check_expr_closure( &self, expr: &hir::Expr<'_>, _capture: hir::CaptureBy, decl: &'tcx hir::FnDecl<'tcx>, body_id: hir::BodyId, gen: Option<hir::Movability>, expected: Expectation<'tcx>, ) -> Ty<'tcx> { trace!("decl = {:#?}", decl); trace!("expr = {:#?}", expr); // It's always helpful for inference if we know the kind of // closure sooner rather than later, so first examine the expected // type, and see if can glean a closure kind from there. let (expected_sig, expected_kind) = match expected.to_option(self) { Some(ty) => self.deduce_expectations_from_expected_type(ty), None => (None, None), }; let body = self.tcx.hir().body(body_id); self.check_closure(expr, expected_kind, decl, body, gen, expected_sig) } #[instrument(skip(self, expr, body, decl), level = "debug")] fn check_closure( &self, expr: &hir::Expr<'_>, opt_kind: Option<ty::ClosureKind>, decl: &'tcx hir::FnDecl<'tcx>, body: &'tcx hir::Body<'tcx>, gen: Option<hir::Movability>, expected_sig: Option<ExpectedSig<'tcx>>, ) -> Ty<'tcx> { trace!("decl = {:#?}", decl); let expr_def_id = self.tcx.hir().local_def_id(expr.hir_id); debug!(?expr_def_id); let ClosureSignatures { bound_sig, liberated_sig } = self.sig_of_closure(expr.hir_id, expr_def_id.to_def_id(), decl, body, expected_sig); debug!(?bound_sig, ?liberated_sig); let return_type_pre_known = !liberated_sig.output().is_ty_infer(); let generator_types = check_fn( self, self.param_env, liberated_sig, decl, expr.hir_id, body, gen, return_type_pre_known, ) .1; let parent_substs = InternalSubsts::identity_for_item( self.tcx, self.tcx.typeck_root_def_id(expr_def_id.to_def_id()), ); let tupled_upvars_ty = self.infcx.next_ty_var(TypeVariableOrigin { kind: TypeVariableOriginKind::ClosureSynthetic, span: self.tcx.hir().span(expr.hir_id), }); if let Some(GeneratorTypes { resume_ty, yield_ty, interior, movability }) = generator_types { let generator_substs = ty::GeneratorSubsts::new( self.tcx, ty::GeneratorSubstsParts { parent_substs, resume_ty, yield_ty, return_ty: liberated_sig.output(), witness: interior, tupled_upvars_ty, }, ); return self.tcx.mk_generator( expr_def_id.to_def_id(), generator_substs.substs, movability, ); } // Tuple up the arguments and insert the resulting function type into // the `closures` table. let sig = bound_sig.map_bound(|sig| { self.tcx.mk_fn_sig( iter::once(self.tcx.intern_tup(sig.inputs())), sig.output(), sig.c_variadic, sig.unsafety, sig.abi, ) }); debug!(?sig, ?opt_kind); let closure_kind_ty = match opt_kind { Some(kind) => kind.to_ty(self.tcx), // Create a type variable (for now) to represent the closure kind. // It will be unified during the upvar inference phase (`upvar.rs`) None => self.infcx.next_ty_var(TypeVariableOrigin { // FIXME(eddyb) distinguish closure kind inference variables from the rest. kind: TypeVariableOriginKind::ClosureSynthetic, span: expr.span, }), }; let closure_substs = ty::ClosureSubsts::new( self.tcx, ty::ClosureSubstsParts { parent_substs, closure_kind_ty, closure_sig_as_fn_ptr_ty: self.tcx.mk_fn_ptr(sig), tupled_upvars_ty, }, ); let closure_type = self.tcx.mk_closure(expr_def_id.to_def_id(), closure_substs.substs); debug!(?expr.hir_id, ?closure_type); closure_type } /// Given the expected type, figures out what it can about this closure we /// are about to type check: #[instrument(skip(self), level = "debug")] fn deduce_expectations_from_expected_type( &self, expected_ty: Ty<'tcx>, ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>)
fn deduce_expectations_from_obligations( &self, expected_vid: ty::TyVid, ) -> (Option<ExpectedSig<'tcx>>, Option<ty::ClosureKind>) { let expected_sig = self.obligations_for_self_ty(expected_vid).find_map(|(_, obligation)| { debug!( "deduce_expectations_from_obligations: obligation.predicate={:?}", obligation.predicate ); let bound_predicate = obligation.predicate.kind(); if let ty::PredicateKind::Projection(proj_predicate) = obligation.predicate.kind().skip_binder() { // Given a Projection predicate, we can potentially infer // the complete signature. self.deduce_sig_from_projection( Some(obligation.cause.span), bound_predicate.rebind(proj_predicate), ) } else { None } }); // Even if we can't infer the full signature, we may be able to // infer the kind. This can occur when we elaborate a predicate // like `F : Fn<A>`. Note that due to subtyping we could encounter // many viable options, so pick the most restrictive. let expected_kind = self .obligations_for_self_ty(expected_vid) .filter_map(|(tr, _)| self.tcx.fn_trait_kind_from_lang_item(tr.def_id())) .fold(None, |best, cur| Some(best.map_or(cur, |best| cmp::min(best, cur)))); (expected_sig, expected_kind) } /// Given a projection like "<F as Fn(X)>::Result == Y", we can deduce /// everything we need to know about a closure or generator. /// /// The `cause_span` should be the span that caused us to /// have this expected signature, or `None` if we can't readily /// know that. fn deduce_sig_from_projection( &self, cause_span: Option<Span>, projection: ty::PolyProjectionPredicate<'tcx>, ) -> Option<ExpectedSig<'tcx>> { let tcx = self.tcx; debug!("deduce_sig_from_projection({:?})", projection); let trait_def_id = projection.trait_def_id(tcx); let is_fn = tcx.fn_trait_kind_from_lang_item(trait_def_id).is_some(); let gen_trait = tcx.require_lang_item(LangItem::Generator, cause_span); let is_gen = gen_trait == trait_def_id; if !is_fn && !is_gen { debug!("deduce_sig_from_projection: not fn or generator"); return None; } if is_gen { // Check that we deduce the signature from the `<_ as std::ops::Generator>::Return` // associated item and not yield. let return_assoc_item = self.tcx.associated_items(gen_trait).in_definition_order().nth(1).unwrap().def_id; if return_assoc_item != projection.projection_def_id() { debug!("deduce_sig_from_projection: not return assoc item of generator"); return None; } } let input_tys = if is_fn { let arg_param_ty = projection.skip_binder().projection_ty.substs.type_at(1); let arg_param_ty = self.resolve_vars_if_possible(arg_param_ty); debug!("deduce_sig_from_projection: arg_param_ty={:?}", arg_param_ty); match arg_param_ty.kind() { ty::Tuple(tys) => tys.into_iter().map(|k| k.expect_ty()).collect::<Vec<_>>(), _ => return None, } } else { // Generators with a `()` resume type may be defined with 0 or 1 explicit arguments, // else they must have exactly 1 argument. For now though, just give up in this case. return None; }; let ret_param_ty = projection.skip_binder().ty; let ret_param_ty = self.resolve_vars_if_possible(ret_param_ty); debug!("deduce_sig_from_projection: ret_param_ty={:?}", ret_param_ty); let sig = projection.rebind(self.tcx.mk_fn_sig( input_tys.iter(), &ret_param_ty, false, hir::Unsafety::Normal, Abi::Rust, )); debug!("deduce_sig_from_projection: sig={:?}", sig); Some(ExpectedSig { cause_span, sig }) } fn sig_of_closure( &self, hir_id: hir::HirId, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, expected_sig: Option<ExpectedSig<'tcx>>, ) -> ClosureSignatures<'tcx> { if let Some(e) = expected_sig { self.sig_of_closure_with_expectation(hir_id, expr_def_id, decl, body, e) } else { self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body) } } /// If there is no expected signature, then we will convert the /// types that the user gave into a signature. #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")] fn sig_of_closure_no_expectation( &self, hir_id: hir::HirId, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, ) -> ClosureSignatures<'tcx> { let bound_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body); self.closure_sigs(expr_def_id, body, bound_sig) } /// Invoked to compute the signature of a closure expression. This /// combines any user-provided type annotations (e.g., `|x: u32| /// -> u32 { .. }`) with the expected signature. /// /// The approach is as follows: /// /// - Let `S` be the (higher-ranked) signature that we derive from the user's annotations. /// - Let `E` be the (higher-ranked) signature that we derive from the expectations, if any. /// - If we have no expectation `E`, then the signature of the closure is `S`. /// - Otherwise, the signature of the closure is E. Moreover: /// - Skolemize the late-bound regions in `E`, yielding `E'`. /// - Instantiate all the late-bound regions bound in the closure within `S` /// with fresh (existential) variables, yielding `S'` /// - Require that `E' = S'` /// - We could use some kind of subtyping relationship here, /// I imagine, but equality is easier and works fine for /// our purposes. /// /// The key intuition here is that the user's types must be valid /// from "the inside" of the closure, but the expectation /// ultimately drives the overall signature. /// /// # Examples /// /// ``` /// fn with_closure<F>(_: F) /// where F: Fn(&u32) -> &u32 { .. } /// /// with_closure(|x: &u32| { ... }) /// ``` /// /// Here: /// - E would be `fn(&u32) -> &u32`. /// - S would be `fn(&u32) -> /// - E' is `&'!0 u32 -> &'!0 u32` /// - S' is `&'?0 u32 -> ?T` /// /// S' can be unified with E' with `['?0 = '!0, ?T = &'!10 u32]`. /// /// # Arguments /// /// - `expr_def_id`: the `DefId` of the closure expression /// - `decl`: the HIR declaration of the closure /// - `body`: the body of the closure /// - `expected_sig`: the expected signature (if any). Note that /// this is missing a binder: that is, there may be late-bound /// regions with depth 1, which are bound then by the closure. #[instrument(skip(self, hir_id, expr_def_id, decl, body), level = "debug")] fn sig_of_closure_with_expectation( &self, hir_id: hir::HirId, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx> { // Watch out for some surprises and just ignore the // expectation if things don't see to match up with what we // expect. if expected_sig.sig.c_variadic() != decl.c_variadic { return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body); } else if expected_sig.sig.skip_binder().inputs_and_output.len() != decl.inputs.len() + 1 { return self.sig_of_closure_with_mismatched_number_of_arguments( expr_def_id, decl, body, expected_sig, ); } // Create a `PolyFnSig`. Note the oddity that late bound // regions appearing free in `expected_sig` are now bound up // in this binder we are creating. assert!(!expected_sig.sig.skip_binder().has_vars_bound_above(ty::INNERMOST)); let bound_sig = expected_sig.sig.map_bound(|sig| { self.tcx.mk_fn_sig( sig.inputs().iter().cloned(), sig.output(), sig.c_variadic, hir::Unsafety::Normal, Abi::RustCall, ) }); // `deduce_expectations_from_expected_type` introduces // late-bound lifetimes defined elsewhere, which we now // anonymize away, so as not to confuse the user. let bound_sig = self.tcx.anonymize_late_bound_regions(bound_sig); let closure_sigs = self.closure_sigs(expr_def_id, body, bound_sig); // Up till this point, we have ignored the annotations that the user // gave. This function will check that they unify successfully. // Along the way, it also writes out entries for types that the user // wrote into our typeck results, which are then later used by the privacy // check. match self.check_supplied_sig_against_expectation( hir_id, expr_def_id, decl, body, &closure_sigs, ) { Ok(infer_ok) => self.register_infer_ok_obligations(infer_ok), Err(_) => return self.sig_of_closure_no_expectation(hir_id, expr_def_id, decl, body), } closure_sigs } fn sig_of_closure_with_mismatched_number_of_arguments( &self, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, expected_sig: ExpectedSig<'tcx>, ) -> ClosureSignatures<'tcx> { let hir = self.tcx.hir(); let expr_map_node = hir.get_if_local(expr_def_id).unwrap(); let expected_args: Vec<_> = expected_sig .sig .skip_binder() .inputs() .iter() .map(|ty| ArgKind::from_expected_ty(ty, None)) .collect(); let (closure_span, found_args) = match self.get_fn_like_arguments(expr_map_node) { Some((sp, args)) => (Some(sp), args), None => (None, Vec::new()), }; let expected_span = expected_sig.cause_span.unwrap_or_else(|| hir.span_if_local(expr_def_id).unwrap()); self.report_arg_count_mismatch( expected_span, closure_span, expected_args, found_args, true, ) .emit(); let error_sig = self.error_sig_of_closure(decl); self.closure_sigs(expr_def_id, body, error_sig) } /// Enforce the user's types against the expectation. See /// `sig_of_closure_with_expectation` for details on the overall /// strategy. fn check_supplied_sig_against_expectation( &self, hir_id: hir::HirId, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, expected_sigs: &ClosureSignatures<'tcx>, ) -> InferResult<'tcx, ()> { // Get the signature S that the user gave. // // (See comment on `sig_of_closure_with_expectation` for the // meaning of these letters.) let supplied_sig = self.supplied_sig_of_closure(hir_id, expr_def_id, decl, body); debug!("check_supplied_sig_against_expectation: supplied_sig={:?}", supplied_sig); // FIXME(#45727): As discussed in [this comment][c1], naively // forcing equality here actually results in suboptimal error // messages in some cases. For now, if there would have been // an obvious error, we fallback to declaring the type of the // closure to be the one the user gave, which allows other // error message code to trigger. // // However, I think [there is potential to do even better // here][c2], since in *this* code we have the precise span of // the type parameter in question in hand when we report the // error. // // [c1]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341089706 // [c2]: https://github.com/rust-lang/rust/pull/45072#issuecomment-341096796 self.infcx.commit_if_ok(|_| { let mut all_obligations = vec![]; // The liberated version of this signature should be a subtype // of the liberated form of the expectation. for ((hir_ty, &supplied_ty), expected_ty) in iter::zip( iter::zip( decl.inputs, supplied_sig.inputs().skip_binder(), // binder moved to (*) below ), expected_sigs.liberated_sig.inputs(), // `liberated_sig` is E'. ) { // Instantiate (this part of..) S to S', i.e., with fresh variables. let (supplied_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars( hir_ty.span, LateBoundRegionConversionTime::FnCall, supplied_sig.inputs().rebind(supplied_ty), ); // recreated from (*) above // Check that E' = S'. let cause = self.misc(hir_ty.span); let InferOk { value: (), obligations } = self.at(&cause, self.param_env).eq(*expected_ty, supplied_ty)?; all_obligations.extend(obligations); } let (supplied_output_ty, _) = self.infcx.replace_bound_vars_with_fresh_vars( decl.output.span(), LateBoundRegionConversionTime::FnCall, supplied_sig.output(), ); let cause = &self.misc(decl.output.span()); let InferOk { value: (), obligations } = self .at(cause, self.param_env) .eq(expected_sigs.liberated_sig.output(), supplied_output_ty)?; all_obligations.extend(obligations); Ok(InferOk { value: (), obligations: all_obligations }) }) } /// If there is no expected signature, then we will convert the /// types that the user gave into a signature. /// /// Also, record this closure signature for later. #[instrument(skip(self, decl, body), level = "debug")] fn supplied_sig_of_closure( &self, hir_id: hir::HirId, expr_def_id: DefId, decl: &hir::FnDecl<'_>, body: &hir::Body<'_>, ) -> ty::PolyFnSig<'tcx> { let astconv: &dyn AstConv<'_> = self; trace!("decl = {:#?}", decl); debug!(?body.generator_kind); let bound_vars = self.tcx.late_bound_vars(hir_id); // First, convert the types that the user supplied (if any). let supplied_arguments = decl.inputs.iter().map(|a| astconv.ast_ty_to_ty(a)); let supplied_return = match decl.output { hir::FnRetTy::Return(ref output) => astconv.ast_ty_to_ty(&output), hir::FnRetTy::DefaultReturn(_) => match body.generator_kind { // In the case of the async block that we create for a function body, // we expect the return type of the block to match that of the enclosing // function. Some(hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Fn)) => { debug!("closure is async fn body"); self.deduce_future_output_from_obligations(expr_def_id).unwrap_or_else(|| { // AFAIK, deducing the future output // always succeeds *except* in error cases // like #65159. I'd like to return Error // here, but I can't because I can't // easily (and locally) prove that we // *have* reported an // error. --nikomatsakis astconv.ty_infer(None, decl.output.span()) }) } _ => astconv.ty_infer(None, decl.output.span()), }, }; let result = ty::Binder::bind_with_vars( self.tcx.mk_fn_sig( supplied_arguments, supplied_return, decl.c_variadic, hir::Unsafety::Normal, Abi::RustCall, ), bound_vars, ); debug!(?result); let c_result = self.inh.infcx.canonicalize_response(result); self.typeck_results.borrow_mut().user_provided_sigs.insert(expr_def_id, c_result); result } /// Invoked when we are translating the generator that results /// from desugaring an `async fn`. Returns the "sugared" return /// type of the `async fn` -- that is, the return type that the /// user specified. The "desugared" return type is an `impl /// Future<Output = T>`, so we do this by searching through the /// obligations to extract the `T`. fn deduce_future_output_from_obligations(&self, expr_def_id: DefId) -> Option<Ty<'tcx>> { debug!("deduce_future_output_from_obligations(expr_def_id={:?})", expr_def_id); let ret_coercion = self.ret_coercion.as_ref().unwrap_or_else(|| { span_bug!(self.tcx.def_span(expr_def_id), "async fn generator outside of a fn") }); // In practice, the return type of the surrounding function is // always a (not yet resolved) inference variable, because it // is the hidden type for an `impl Trait` that we are going to // be inferring. let ret_ty = ret_coercion.borrow().expected_ty(); let ret_ty = self.inh.infcx.shallow_resolve(ret_ty); let ret_vid = match *ret_ty.kind() { ty::Infer(ty::TyVar(ret_vid)) => ret_vid, ty::Error(_) => return None, _ => span_bug!( self.tcx.def_span(expr_def_id), "async fn generator return type not an inference variable" ), }; // Search for a pending obligation like // // `<R as Future>::Output = T` // // where R is the return type we are expecting. This type `T` // will be our output. let output_ty = self.obligations_for_self_ty(ret_vid).find_map(|(_, obligation)| { let bound_predicate = obligation.predicate.kind(); if let ty::PredicateKind::Projection(proj_predicate) = bound_predicate.skip_binder() { self.deduce_future_output_from_projection( obligation.cause.span, bound_predicate.rebind(proj_predicate), ) } else { None } }); debug!("deduce_future_output_from_obligations: output_ty={:?}", output_ty); output_ty } /// Given a projection like /// /// `<X as Future>::Output = T` /// /// where `X` is some type that has no late-bound regions, returns /// `Some(T)`. If the projection is for some other trait, returns /// `None`. fn deduce_future_output_from_projection( &self, cause_span: Span, predicate: ty::PolyProjectionPredicate<'tcx>, ) -> Option<Ty<'tcx>> { debug!("deduce_future_output_from_projection(predicate={:?})", predicate); // We do not expect any bound regions in our predicate, so // skip past the bound vars. let predicate = match predicate.no_bound_vars() { Some(p) => p, None => { debug!("deduce_future_output_from_projection: has late-bound regions"); return None; } }; // Check that this is a projection from the `Future` trait. let trait_def_id = predicate.projection_ty.trait_def_id(self.tcx); let future_trait = self.tcx.require_lang_item(LangItem::Future, Some(cause_span)); if trait_def_id != future_trait { debug!("deduce_future_output_from_projection: not a future"); return None; } // The `Future` trait has only one associted item, `Output`, // so check that this is what we see. let output_assoc_item = self.tcx.associated_items(future_trait).in_definition_order().next().unwrap().def_id; if output_assoc_item != predicate.projection_ty.item_def_id { span_bug!( cause_span, "projecting associated item `{:?}` from future, which is not Output `{:?}`", predicate.projection_ty.item_def_id, output_assoc_item, ); } // Extract the type from the projection. Note that there can // be no bound variables in this type because the "self type" // does not have any regions in it. let output_ty = self.resolve_vars_if_possible(predicate.ty); debug!("deduce_future_output_from_projection: output_ty={:?}", output_ty); Some(output_ty) } /// Converts the types that the user supplied, in case that doing /// so should yield an error, but returns back a signature where /// all parameters are of type `TyErr`. fn error_sig_of_closure(&self, decl: &hir::FnDecl<'_>) -> ty::PolyFnSig<'tcx> { let astconv: &dyn AstConv<'_> = self; let supplied_arguments = decl.inputs.iter().map(|a| { // Convert the types that the user supplied (if any), but ignore them. astconv.ast_ty_to_ty(a); self.tcx.ty_error() }); if let hir::FnRetTy::Return(ref output) = decl.output { astconv.ast_ty_to_ty(&output); } let result = ty::Binder::dummy(self.tcx.mk_fn_sig( supplied_arguments, self.tcx.ty_error(), decl.c_variadic, hir::Unsafety::Normal, Abi::RustCall, )); debug!("supplied_sig_of_closure: result={:?}", result); result } fn closure_sigs( &self, expr_def_id: DefId, body: &hir::Body<'_>, bound_sig: ty::PolyFnSig<'tcx>, ) -> ClosureSignatures<'tcx> { let liberated_sig = self.tcx().liberate_late_bound_regions(expr_def_id, bound_sig); let liberated_sig = self.inh.normalize_associated_types_in( body.value.span, body.value.hir_id, self.param_env, liberated_sig, ); ClosureSignatures { bound_sig, liberated_sig } } }
{ match *expected_ty.kind() { ty::Dynamic(ref object_type, ..) => { let sig = object_type.projection_bounds().find_map(|pb| { let pb = pb.with_self_ty(self.tcx, self.tcx.types.trait_object_dummy_self); self.deduce_sig_from_projection(None, pb) }); let kind = object_type .principal_def_id() .and_then(|did| self.tcx.fn_trait_kind_from_lang_item(did)); (sig, kind) } ty::Infer(ty::TyVar(vid)) => self.deduce_expectations_from_obligations(vid), ty::FnPtr(sig) => { let expected_sig = ExpectedSig { cause_span: None, sig }; (Some(expected_sig), Some(ty::ClosureKind::Fn)) } _ => (None, None), } }
uart.rs
extern crate byteorder; extern crate serial; use std::sync::mpsc::{channel, Receiver, Sender, TryRecvError}; use std::sync::{Arc, Mutex, Condvar}; use std::thread; use std::time::Duration; use log::{debug, error, info}; use serial::prelude::*; use byteorder::{BigEndian, ReadBytesExt, WriteBytesExt}; use super::BridgeError; use crate::config::Config; pub struct UartBridge { path: String, baudrate: usize, main_tx: Sender<ConnectThreadRequests>, main_rx: Arc<(Mutex<Option<ConnectThreadResponses>>, Condvar)>, mutex: Arc<Mutex<()>>, poll_thread: Option<thread::JoinHandle<()>>, } impl Clone for UartBridge { fn clone(&self) -> Self { UartBridge { path: self.path.clone(), baudrate: self.baudrate.clone(), main_tx: self.main_tx.clone(), main_rx: self.main_rx.clone(), mutex: self.mutex.clone(), poll_thread: None, } } } enum ConnectThreadRequests { StartPolling(String /* path */, usize /* baudrate */), Exit, Poke(u32 /* addr */, u32 /* val */), Peek(u32 /* addr */), } #[derive(Debug)] enum ConnectThreadResponses { Exiting, OpenedDevice, PeekResult(Result<u32, BridgeError>), PokeResult(Result<(), BridgeError>), } impl UartBridge { pub fn new(cfg: &Config) -> Result<Self, BridgeError> { let (main_tx, thread_rx) = channel(); let cv = Arc::new((Mutex::new(None), Condvar::new())); let path = match &cfg.serial_port { Some(s) => s.clone(), None => panic!("no serial port path was found"), }; let baudrate = cfg.serial_baud.expect("no serial port baudrate was found"); let thr_cv = cv.clone(); let thr_path = path.clone(); let poll_thread = Some(thread::spawn(move || { Self::serial_connect_thread(thr_cv, thread_rx, thr_path, baudrate) })); Ok(UartBridge { path, baudrate, main_tx, main_rx: cv, mutex: Arc::new(Mutex::new(())), poll_thread, }) } fn serial_connect_thread( tx: Arc<(Mutex<Option<ConnectThreadResponses>>, Condvar)>, rx: Receiver<ConnectThreadRequests>, path: String, baud: usize ) { let mut path = path; let mut baud = baud; let mut print_waiting_message = true; let mut first_run = true; let &(ref response, ref cvar) = &*tx; loop { let mut port = match serial::open(&path) { Ok(port) => { info!("Re-opened serial device {}", path); if first_run { *response.lock().unwrap() = Some(ConnectThreadResponses::OpenedDevice); first_run = false; cvar.notify_one(); } print_waiting_message = true; port }, Err(e) => { if print_waiting_message { print_waiting_message = false; error!("unable to open serial device, will wait for it to appear again: {}", e); } thread::park_timeout(Duration::from_millis(500)); continue; } }; if let Err(e) = port.reconfigure(&|settings| { settings.set_baud_rate(serial::BaudRate::from_speed(baud))?; settings.set_char_size(serial::Bits8); settings.set_parity(serial::ParityNone); settings.set_stop_bits(serial::Stop1); settings.set_flow_control(serial::FlowNone); Ok(()) }) { error!("unable to reconfigure serial port {} -- connection may not work", e); } if let Err(e) = port.set_timeout(Duration::from_millis(1000)) { error!("unable to set port duration timeout: {}", e); } let mut keep_going = true; let mut result_error = "".to_owned(); while keep_going { let var = rx.recv(); match var { Err(_) => { error!("connection closed"); return; }, Ok(o) => match o { ConnectThreadRequests::Exit => { debug!("serial_connect_thread requested exit"); *response.lock().unwrap() = Some(ConnectThreadResponses::Exiting); cvar.notify_one(); return; } ConnectThreadRequests::StartPolling(p, v) => { path = p.clone(); baud = v; } ConnectThreadRequests::Peek(addr) => { let result = Self::do_peek(&mut port, addr); if let Err(err) = &result { result_error = format!("peek {:?} @ {:08x}", err, addr); keep_going = false; } *response.lock().unwrap() = Some(ConnectThreadResponses::PeekResult(result)); cvar.notify_one(); } ConnectThreadRequests::Poke(addr, val) => { let result = Self::do_poke(&mut port, addr, val); if let Err(err) = &result { result_error = format!("poke {:?} @ {:08x}", err, addr); keep_going = false; } *response.lock().unwrap() = Some(ConnectThreadResponses::PokeResult(result)); cvar.notify_one(); } }, } } error!("serial port was closed: {}", result_error); thread::park_timeout(Duration::from_millis(500)); // Respond to any messages in the buffer with NotConnected. As soon // as the channel is empty, loop back to the start of this function. loop { match rx.try_recv() { Err(TryRecvError::Empty) => break, Err(TryRecvError::Disconnected) => panic!("main thread disconnected"), Ok(m) => match m { ConnectThreadRequests::Exit => { *response.lock().unwrap() = Some(ConnectThreadResponses::Exiting); cvar.notify_one(); debug!("main thread requested exit"); return; } ConnectThreadRequests::Peek(_addr) => { *response.lock().unwrap() = Some(ConnectThreadResponses::PeekResult(Err( BridgeError::NotConnected, ))); cvar.notify_one(); }, ConnectThreadRequests::Poke(_addr, _val) => { *response.lock().unwrap() = Some(ConnectThreadResponses::PokeResult(Err( BridgeError::NotConnected, ))); cvar.notify_one(); }, ConnectThreadRequests::StartPolling(p, v) => { path = p.clone(); baud = v; } }, } } } } pub fn mutex(&self) -> &Arc<Mutex<()>> { &self.mutex } pub fn connect(&self) -> Result<(), BridgeError> { self.main_tx .send(ConnectThreadRequests::StartPolling( self.path.clone(), self.baudrate, )) .unwrap(); loop { let &(ref lock, ref cvar) = &*self.main_rx; let mut _mtx = lock.lock().unwrap(); *_mtx = None; while _mtx.is_none() { _mtx = cvar.wait(_mtx).unwrap(); } match *_mtx { Some(ConnectThreadResponses::OpenedDevice) => return Ok(()), _ => (), } } } fn do_poke<T: SerialPort>( serial: &mut T, addr: u32, value: u32, ) -> Result<(), BridgeError> { debug!("POKE @ {:08x} -> {:08x}", addr, value); // WRITE, 1 word serial.write(&[0x01, 0x01])?; // LiteX ignores the bottom two Wishbone bits, so shift it by // two when writing the address. serial.write_u32::<BigEndian>(addr >> 2)?; Ok(serial.write_u32::<BigEndian>(value)?) } fn do_peek<T: SerialPort>(serial: &mut T, addr: u32) -> Result<u32, BridgeError> { // READ, 1 word debug!("Peeking @ {:08x}", addr); serial.write(&[0x02, 0x01])?; // LiteX ignores the bottom two Wishbone bits, so shift it by // two when writing the address. serial.write_u32::<BigEndian>(addr >> 2)?; let val = serial.read_u32::<BigEndian>()?; debug!("PEEK @ {:08x} = {:08x}", addr, val); Ok(val) } pub fn poke(&self, addr: u32, value: u32) -> Result<(), BridgeError> { let &(ref lock, ref cvar) = &*self.main_rx; let mut _mtx = lock.lock().unwrap(); self.main_tx .send(ConnectThreadRequests::Poke(addr, value)) .expect("Unable to send poke to connect thread"); *_mtx = None; while _mtx.is_none() { _mtx = cvar.wait(_mtx).unwrap(); } match _mtx.take() { Some(ConnectThreadResponses::PokeResult(r)) => Ok(r?), e => { error!("unexpected bridge poke response: {:?}", e); Err(BridgeError::WrongResponse) } } } pub fn peek(&self, addr: u32) -> Result<u32, BridgeError> { let &(ref lock, ref cvar) = &*self.main_rx; let mut _mtx = lock.lock().unwrap(); self.main_tx .send(ConnectThreadRequests::Peek(addr)) .expect("Unable to send peek to connect thread"); *_mtx = None; while _mtx.is_none() { _mtx = cvar.wait(_mtx).unwrap(); } match _mtx.take() { Some(ConnectThreadResponses::PeekResult(r)) => Ok(r?), e => { error!("unexpected bridge peek response: {:?}", e); Err(BridgeError::WrongResponse) } } } } impl Drop for UartBridge { fn drop(&mut self) { // If this is the last reference to the bridge, tell the control thread // to exit. let sc = Arc::strong_count(&self.mutex); let wc = Arc::weak_count(&self.mutex); debug!("strong count: {} weak count: {}", sc, wc);
let &(ref lock, ref cvar) = &*self.main_rx; let mut mtx = lock.lock().unwrap(); self.main_tx .send(ConnectThreadRequests::Exit) .expect("Unable to send Exit request to thread"); *mtx = None; while mtx.is_none() { mtx = cvar.wait(mtx).unwrap(); } match mtx.take() { Some(ConnectThreadResponses::Exiting) => (), e => { error!("unexpected bridge exit response: {:?}", e); } } if let Some(pt) = self.poll_thread.take() { pt.join().expect("Unable to join polling thread"); } } } }
if (sc + wc) <= 1 {
utils.py
# Copyright (c) 2018-2021, NVIDIA Corporation # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. #
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # python import numpy as np import torch import random import os def set_np_formatting(): """ formats numpy print """ np.set_printoptions(edgeitems=30, infstr='inf', linewidth=4000, nanstr='nan', precision=2, suppress=False, threshold=10000, formatter=None) def set_seed(seed, torch_deterministic=False): """ set seed across modules """ if seed == -1 and torch_deterministic: seed = 42 elif seed == -1: seed = np.random.randint(0, 10000) print("Setting seed: {}".format(seed)) random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) os.environ['PYTHONHASHSEED'] = str(seed) torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) if torch_deterministic: # refer to https://docs.nvidia.com/cuda/cublas/index.html#cublasApi_reproducibility os.environ['CUBLAS_WORKSPACE_CONFIG'] = ':4096:8' torch.backends.cudnn.benchmark = False torch.backends.cudnn.deterministic = True torch.use_deterministic_algorithms(True) else: torch.backends.cudnn.benchmark = True torch.backends.cudnn.deterministic = False return seed # EOF
# 3. Neither the name of the copyright holder nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. #
helpers.py
# coding=UTF-8 '''Helper functions Consists of functions to typically be used within templates, but also available to Controllers. This module is available to templates as 'h'. ''' import email.utils import datetime import logging import re import os import urllib import urlparse import pprint import copy import urlparse from urllib import urlencode from paste.deploy.converters import asbool from webhelpers.html import escape, HTML, literal, url_escape from webhelpers.html.tools import mail_to from webhelpers.html.tags import * from webhelpers.markdown import markdown from webhelpers import paginate from webhelpers.text import truncate import webhelpers.date as date from pylons import url as _pylons_default_url from pylons.decorators.cache import beaker_cache from pylons import config from routes import redirect_to as _redirect_to from routes import url_for as _routes_default_url_for from alphabet_paginate import AlphaPage import i18n import ckan.exceptions import ckan.lib.fanstatic_resources as fanstatic_resources import ckan.model as model import ckan.lib.formatters as formatters import ckan.lib.maintain as maintain import ckan.lib.datapreview as datapreview import ckan.logic as logic import ckan.lib.uploader as uploader import ckan.new_authz as new_authz from ckan.common import ( _, ungettext, g, c, request, session, json, OrderedDict ) get_available_locales = i18n.get_available_locales get_locales_dict = i18n.get_locales_dict log = logging.getLogger(__name__) def _datestamp_to_datetime(datetime_): ''' Converts a datestamp to a datetime. If a datetime is provided it just gets returned. :param datetime_: the timestamp :type datetime_: string or datetime :rtype: datetime ''' if isinstance(datetime_, basestring): try: datetime_ = date_str_to_datetime(datetime_) except TypeError: return None except ValueError: return None # check we are now a datetime if not isinstance(datetime_, datetime.datetime): return None return datetime_ def redirect_to(*args, **kw): '''Issue a redirect: return an HTTP response with a ``302 Moved`` header. This is a wrapper for :py:func:`routes.redirect_to` that maintains the user's selected language when redirecting. The arguments to this function identify the route to redirect to, they're the same arguments as :py:func:`ckan.plugins.toolkit.url_for` accepts, for example:: import ckan.plugins.toolkit as toolkit # Redirect to /dataset/my_dataset. toolkit.redirect_to(controller='package', action='read', id='my_dataset') Or, using a named route:: toolkit.redirect_to('dataset_read', id='changed') ''' kw['__ckan_no_root'] = True if are_there_flash_messages(): kw['__no_cache__'] = True return _redirect_to(url_for(*args, **kw)) def url(*args, **kw): '''Create url adding i18n information if selected wrapper for pylons.url''' locale = kw.pop('locale', None) my_url = _pylons_default_url(*args, **kw) return _add_i18n_to_url(my_url, locale=locale, **kw) def url_for(*args, **kw): '''Return the URL for the given controller, action, id, etc. Usage:: import ckan.plugins.toolkit as toolkit url = toolkit.url_for(controller='package', action='read', id='my_dataset') => returns '/dataset/my_dataset' Or, using a named route:: toolkit.url_for('dataset_read', id='changed') This is a wrapper for :py:func:`routes.url_for` that adds some extra features that CKAN needs. ''' locale = kw.pop('locale', None) # remove __ckan_no_root and add after to not pollute url no_root = kw.pop('__ckan_no_root', False) # routes will get the wrong url for APIs if the ver is not provided if kw.get('controller') == 'api': ver = kw.get('ver') if not ver: raise Exception('api calls must specify the version! e.g. ver=3') # fix ver to include the slash kw['ver'] = '/%s' % ver my_url = _routes_default_url_for(*args, **kw) kw['__ckan_no_root'] = no_root return _add_i18n_to_url(my_url, locale=locale, **kw) def url_for_static(*args, **kw): '''Returns the URL for static content that doesn't get translated (eg CSS) It'll raise CkanUrlException if called with an external URL This is a wrapper for :py:func:`routes.url_for` ''' if args: url = urlparse.urlparse(args[0]) url_is_external = (url.scheme != '' or url.netloc != '') if url_is_external: CkanUrlException = ckan.exceptions.CkanUrlException raise CkanUrlException('External URL passed to url_for_static()') return url_for_static_or_external(*args, **kw) def url_for_static_or_external(*args, **kw): '''Returns the URL for static content that doesn't get translated (eg CSS), or external URLs This is a wrapper for :py:func:`routes.url_for` ''' def fix_arg(arg): url = urlparse.urlparse(str(arg)) url_is_relative = (url.scheme == '' and url.netloc == '' and not url.path.startswith('/')) if url_is_relative: return '/' + url.geturl() return url.geturl() if args: args = (fix_arg(args[0]), ) + args[1:] my_url = _routes_default_url_for(*args, **kw) return my_url def is_url(*args, **kw): ''' Returns True if argument parses as a http, https or ftp URL ''' if not args: return False try: url = urlparse.urlparse(args[0]) except ValueError: return False valid_schemes = ('http', 'https', 'ftp') return url.scheme in valid_schemes def _add_i18n_to_url(url_to_amend, **kw): # If the locale keyword param is provided then the url is rewritten # using that locale .If return_to is provided this is used as the url # (as part of the language changing feature). # A locale of default will not add locale info to the url. default_locale = False locale = kw.pop('locale', None) no_root = kw.pop('__ckan_no_root', False) allowed_locales = ['default'] + i18n.get_locales() if locale and locale not in allowed_locales: locale = None if locale: if locale == 'default': default_locale = True else: try: locale = request.environ.get('CKAN_LANG') default_locale = request.environ.get('CKAN_LANG_IS_DEFAULT', True) except TypeError: default_locale = True try: root = request.environ.get('SCRIPT_NAME', '') except TypeError: root = '' if kw.get('qualified', False): # if qualified is given we want the full url ie http://... root = _routes_default_url_for('/', qualified=True)[:-1] # ckan.root_path is defined when we have none standard language # position in the url root_path = config.get('ckan.root_path', None) if root_path: # FIXME this can be written better once the merge # into the ecportal core is done - Toby # we have a special root specified so use that if default_locale: root = re.sub('/{{LANG}}', '', root_path) else: root = re.sub('{{LANG}}', locale, root_path) # make sure we don't have a trailing / on the root if root[-1] == '/': root = root[:-1] url = url_to_amend[len(re.sub('/{{LANG}}', '', root_path)):] url = '%s%s' % (root, url) root = re.sub('/{{LANG}}', '', root_path) else: if default_locale: url = url_to_amend else: # we need to strip the root from the url and the add it before # the language specification. url = url_to_amend[len(root):] url = '%s/%s%s' % (root, locale, url) # stop the root being added twice in redirects if no_root: url = url_to_amend[len(root):] if not default_locale: url = '/%s%s' % (locale, url) if url == '/packages': error = 'There is a broken url being created %s' % kw raise ckan.exceptions.CkanUrlException(error) return url def url_is_local(url): '''Returns True if url is local''' if not url or url.startswith('//'): return False parsed = urlparse.urlparse(url) if parsed.scheme: domain = urlparse.urlparse(url_for('/', qualified=True)).netloc if domain != parsed.netloc: return False return True def full_current_url(): ''' Returns the fully qualified current url (eg http://...) useful for sharing etc ''' return (url_for(request.environ['CKAN_CURRENT_URL'], qualified=True)) def lang(): ''' Return the language code for the current locale eg `en` ''' return request.environ.get('CKAN_LANG') def lang_native_name(lang=None): ''' Return the langage name currently used in it's localised form either from parameter or current environ setting''' lang = lang or lang() locale = get_locales_dict().get(lang) if locale: return locale.display_name or locale.english_name return lang class Message(object): '''A message returned by ``Flash.pop_messages()``. Converting the message to a string returns the message text. Instances also have the following attributes: * ``message``: the message text. * ``category``: the category specified when the message was created. ''' def __init__(self, category, message, allow_html): self.category = category self.message = message self.allow_html = allow_html def __str__(self): return self.message __unicode__ = __str__ def __html__(self): if self.allow_html: return self.message else: return escape(self.message) class _Flash(object): # List of allowed categories. If None, allow any category. categories = ["", "alert-info", "alert-error", "alert-success"] # Default category if none is specified. default_category = "" def __init__(self, session_key="flash", categories=None, default_category=None): self.session_key = session_key if categories is not None: self.categories = categories if default_category is not None: self.default_category = default_category if self.categories and self.default_category not in self.categories: raise ValueError("unrecognized default category %r" % (self.default_category, )) def __call__(self, message, category=None, ignore_duplicate=False, allow_html=False): if not category: category = self.default_category elif self.categories and category not in self.categories: raise ValueError("unrecognized category %r" % (category, )) # Don't store Message objects in the session, to avoid unpickling # errors in edge cases. new_message_tuple = (category, message, allow_html) messages = session.setdefault(self.session_key, []) # ``messages`` is a mutable list, so changes to the local variable are # reflected in the session. if ignore_duplicate: for i, m in enumerate(messages): if m[1] == message: if m[0] != category: messages[i] = new_message_tuple session.save() return # Original message found, so exit early. messages.append(new_message_tuple) session.save() def pop_messages(self): messages = session.pop(self.session_key, []) # only save session if it has changed if messages: session.save() return [Message(*m) for m in messages] def are_there_messages(self): return bool(session.get(self.session_key)) flash = _Flash() # this is here for backwards compatability _flash = flash def flash_notice(message, allow_html=False): ''' Show a flash message of type notice ''' flash(message, category='alert-info', allow_html=allow_html) def flash_error(message, allow_html=False): ''' Show a flash message of type error ''' flash(message, category='alert-error', allow_html=allow_html) def flash_success(message, allow_html=False): ''' Show a flash message of type success ''' flash(message, category='alert-success', allow_html=allow_html) def are_there_flash_messages(): ''' Returns True if there are flash messages for the current user ''' return flash.are_there_messages() def _link_active(kwargs): ''' creates classes for the link_to calls ''' highlight_actions = kwargs.get('highlight_actions', kwargs.get('action', '')).split(' ') return (c.controller == kwargs.get('controller') and c.action in highlight_actions) def _link_to(text, *args, **kwargs): '''Common link making code for several helper functions''' assert len(args) < 2, 'Too many unnamed arguments' def _link_class(kwargs): ''' creates classes for the link_to calls ''' suppress_active_class = kwargs.pop('suppress_active_class', False) if not suppress_active_class and _link_active(kwargs): active = ' active' else: active = '' kwargs.pop('highlight_actions', '') return kwargs.pop('class_', '') + active or None def _create_link_text(text, **kwargs): ''' Update link text to add a icon or span if specified in the kwargs ''' if kwargs.pop('inner_span', None): text = literal('<span>') + text + literal('</span>') if icon: text = literal('<i class="icon-%s"></i> ' % icon) + text return text icon = kwargs.pop('icon', None) class_ = _link_class(kwargs) return link_to( _create_link_text(text, **kwargs), url_for(*args, **kwargs), class_=class_ ) def nav_link(text, *args, **kwargs): ''' :param class_: pass extra class(es) to add to the ``<a>`` tag :param icon: name of ckan icon to use within the link :param condition: if ``False`` then no link is returned ''' if len(args) > 1: raise Exception('Too many unnamed parameters supplied') if args: kwargs['controller'] = controller log.warning('h.nav_link() please supply controller as a named ' 'parameter not a positional one') named_route = kwargs.pop('named_route', '') if kwargs.pop('condition', True): if named_route: link = _link_to(text, named_route, **kwargs) else: link = _link_to(text, **kwargs) else: link = '' return link @maintain.deprecated('h.nav_named_link is deprecated please ' 'use h.nav_link\nNOTE: you will need to pass the ' 'route_name as a named parameter') def nav_named_link(text, named_route, **kwargs): '''Create a link for a named route. Deprecated in ckan 2.0 ''' return nav_link(text, named_route=named_route, **kwargs) @maintain.deprecated('h.subnav_link is deprecated please ' 'use h.nav_link\nNOTE: if action is passed as the second ' 'parameter make sure it is passed as a named parameter ' 'eg. `action=\'my_action\'') def subnav_link(text, action, **kwargs): '''Create a link for a named route. Deprecated in ckan 2.0 ''' kwargs['action'] = action return nav_link(text, **kwargs) @maintain.deprecated('h.subnav_named_route is deprecated please ' 'use h.nav_link\nNOTE: you will need to pass the ' 'route_name as a named parameter') def subnav_named_route(text, named_route, **kwargs): '''Generate a subnav element based on a named route Deprecated in ckan 2.0 ''' return nav_link(text, named_route=named_route, **kwargs) def build_nav_main(*args): ''' build a set of menu items. args: tuples of (menu type, title) eg ('login', _('Login')) outputs <li><a href="...">title</a></li> ''' output = '' for item in args: menu_item, title = item[:2] if len(item) == 3 and not check_access(item[2]): continue output += _make_menu_item(menu_item, title) return output def build_nav_icon(menu_item, title, **kw): '''Build a navigation item used for example in ``user/read_base.html``. Outputs ``<li><a href="..."><i class="icon.."></i> title</a></li>``. :param menu_item: the name of the defined menu item defined in config/routing as the named route of the same name :type menu_item: string :param title: text used for the link :type title: string :param kw: additional keywords needed for creating url eg ``id=...`` :rtype: HTML literal ''' return _make_menu_item(menu_item, title, **kw) def build_nav(menu_item, title, **kw): '''Build a navigation item used for example breadcrumbs. Outputs ``<li><a href="..."></i> title</a></li>``. :param menu_item: the name of the defined menu item defined in config/routing as the named route of the same name :type menu_item: string :param title: text used for the link :type title: string :param kw: additional keywords needed for creating url eg ``id=...`` :rtype: HTML literal ''' return _make_menu_item(menu_item, title, icon=None, **kw) def _make_menu_item(menu_item, title, **kw): ''' build a navigation item used for example breadcrumbs outputs <li><a href="..."></i> title</a></li> :param menu_item: the name of the defined menu item defined in config/routing as the named route of the same name :type menu_item: string :param title: text used for the link :type title: string :param **kw: additional keywords needed for creating url eg id=... :rtype: HTML literal This function is called by wrapper functions. ''' _menu_items = config['routes.named_routes'] if menu_item not in _menu_items: raise Exception('menu item `%s` cannot be found' % menu_item) item = copy.copy(_menu_items[menu_item]) item.update(kw) active = _link_active(item) needed = item.pop('needed') for need in needed: if need not in kw: raise Exception('menu item `%s` need parameter `%s`' % (menu_item, need)) link = _link_to(title, menu_item, suppress_active_class=True, **item) if active: return literal('<li class="active">') + link + literal('</li>') return literal('<li>') + link + literal('</li>') def default_group_type(): return str(config.get('ckan.default.group_type', 'group')) def get_facet_items_dict(facet, limit=None, exclude_active=False): '''Return the list of unselected facet items for the given facet, sorted by count. Returns the list of unselected facet contraints or facet items (e.g. tag names like "russian" or "tolstoy") for the given search facet (e.g. "tags"), sorted by facet item count (i.e. the number of search results that match each facet item). Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected. Arguments: facet -- the name of the facet to filter. limit -- the max. number of facet items to return. exclude_active -- only return unselected facets. ''' if not c.search_facets or \ not c.search_facets.get(facet) or \ not c.search_facets.get(facet).get('items'): return [] facets = [] for facet_item in c.search_facets.get(facet)['items']: if not len(facet_item['name'].strip()): continue if not (facet, facet_item['name']) in request.params.items(): facets.append(dict(active=False, **facet_item)) elif not exclude_active: facets.append(dict(active=True, **facet_item)) facets = sorted(facets, key=lambda item: item['count'], reverse=True) if c.search_facets_limits and limit is None: limit = c.search_facets_limits.get(facet) # zero treated as infinite for hysterical raisins if limit is not None and limit > 0: return facets[:limit] return facets def has_more_facets(facet, limit=None, exclude_active=False): ''' Returns True if there are more facet items for the given facet than the limit. Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected. Arguments: facet -- the name of the facet to filter. limit -- the max. number of facet items. exclude_active -- only return unselected facets. ''' facets = [] for facet_item in c.search_facets.get(facet)['items']: if not len(facet_item['name'].strip()): continue if not (facet, facet_item['name']) in request.params.items(): facets.append(dict(active=False, **facet_item)) elif not exclude_active: facets.append(dict(active=True, **facet_item)) if c.search_facets_limits and limit is None: limit = c.search_facets_limits.get(facet) if limit is not None and len(facets) > limit: return True return False def unselected_facet_items(facet, limit=10): '''Return the list of unselected facet items for the given facet, sorted by count. Returns the list of unselected facet contraints or facet items (e.g. tag names like "russian" or "tolstoy") for the given search facet (e.g. "tags"), sorted by facet item count (i.e. the number of search results that match each facet item). Reads the complete list of facet items for the given facet from c.search_facets, and filters out the facet items that the user has already selected. Arguments: facet -- the name of the facet to filter. limit -- the max. number of facet items to return. ''' return get_facet_items_dict(facet, limit=limit, exclude_active=True) @maintain.deprecated('h.get_facet_title is deprecated in 2.0 and will be removed.') def get_facet_title(name): '''Deprecated in ckan 2.0 ''' # if this is set in the config use this config_title = config.get('search.facets.%s.title' % name) if config_title: return config_title facet_titles = {'organization': _('Organizations'), 'groups': _('Groups'), 'tags': _('Tags'), 'res_format': _('Formats'), 'license': _('Licenses'), } return facet_titles.get(name, name.capitalize()) def get_param_int(name, default=10): try: return int(request.params.get(name, default)) except ValueError: return default def _url_with_params(url, params): if not params: return url params = [(k, v.encode('utf-8') if isinstance(v, basestring) else str(v)) for k, v in params] return url + u'?' + urlencode(params) def _search_url(params): url = url_for(controller='package', action='search') return _url_with_params(url, params) def sorted_extras(package_extras, auto_clean=False, subs=None, exclude=None): ''' Used for outputting package extras :param package_extras: the package extras :type package_extras: dict :param auto_clean: If true capitalize and replace -_ with spaces :type auto_clean: bool :param subs: substitutes to use instead of given keys :type subs: dict {'key': 'replacement'} :param exclude: keys to exclude :type exclude: list of strings ''' # If exclude is not supplied use values defined in the config if not exclude: exclude = g.package_hide_extras output = [] for extra in sorted(package_extras, key=lambda x: x['key']): if extra.get('state') == 'deleted': continue k, v = extra['key'], extra['value'] if k in exclude: continue if subs and k in subs: k = subs[k] elif auto_clean: k = k.replace('_', ' ').replace('-', ' ').title() if isinstance(v, (list, tuple)): v = ", ".join(map(unicode, v)) output.append((k, v)) return output def check_access(action, data_dict=None): context = {'model': model, 'user': c.user or c.author} if not data_dict: data_dict = {} try: logic.check_access(action, context, data_dict) authorized = True except logic.NotAuthorized: authorized = False return authorized @maintain.deprecated("helpers.get_action() is deprecated and will be removed " "in a future version of CKAN. Instead, please use the " "extra_vars param to render() in your controller to pass " "results from action functions to your templates.") def get_action(action_name, data_dict=None): '''Calls an action function from a template. Deprecated in CKAN 2.3.''' if data_dict is None: data_dict = {} return logic.get_action(action_name)({}, data_dict) def linked_user(user, maxlength=0, avatar=20): if user in [model.PSEUDO_USER__LOGGED_IN, model.PSEUDO_USER__VISITOR]: return user if not isinstance(user, model.User): user_name = unicode(user) user = model.User.get(user_name) if not user: return user_name if user: name = user.name if model.User.VALID_NAME.match(user.name) else user.id icon = gravatar(email_hash=user.email_hash, size=avatar) displayname = user.display_name if maxlength and len(user.display_name) > maxlength: displayname = displayname[:maxlength] + '...' return icon + u' ' + link_to(displayname, url_for(controller='user', action='read', id=name)) def group_name_to_title(name):
def markdown_extract(text, extract_length=190): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If extract_length is 0 then it will not be truncated.''' if (text is None) or (text.strip() == ''): return '' plain = RE_MD_HTML_TAGS.sub('', markdown(text)) if not extract_length or len(plain) < extract_length: return literal(plain) return literal(unicode(truncate(plain, length=extract_length, indicator='...', whole_word=True))) def icon_url(name): return url_for_static('/images/icons/%s.png' % name) def icon_html(url, alt=None, inline=True): classes = '' if inline: classes += 'inline-icon ' return literal(('<img src="%s" height="16px" width="16px" alt="%s" ' + 'class="%s" /> ') % (url, alt, classes)) def icon(name, alt=None, inline=True): return icon_html(icon_url(name), alt, inline) def resource_icon(res): if False: icon_name = 'page_white' # if (res.is_404?): icon_name = 'page_white_error' # also: 'page_white_gear' # also: 'page_white_link' return icon(icon_name) else: return icon(format_icon(res.get('format', ''))) def format_icon(_format): _format = _format.lower() if ('json' in _format): return 'page_white_cup' if ('csv' in _format): return 'page_white_gear' if ('xls' in _format): return 'page_white_excel' if ('zip' in _format): return 'page_white_compressed' if ('api' in _format): return 'page_white_database' if ('plain text' in _format): return 'page_white_text' if ('xml' in _format): return 'page_white_code' return 'page_white' def dict_list_reduce(list_, key, unique=True): ''' Take a list of dicts and create a new one containing just the values for the key with unique values if requested. ''' new_list = [] for item in list_: value = item.get(key) if not value or (unique and value in new_list): continue new_list.append(value) return new_list def linked_gravatar(email_hash, size=100, default=None): return literal( '<a href="https://gravatar.com/" target="_blank" ' + 'title="%s" alt="">' % _('Update your avatar at gravatar.com') + '%s</a>' % gravatar(email_hash, size, default) ) _VALID_GRAVATAR_DEFAULTS = ['404', 'mm', 'identicon', 'monsterid', 'wavatar', 'retro'] def gravatar(email_hash, size=100, default=None): if default is None: default = config.get('ckan.gravatar_default', 'identicon') if not default in _VALID_GRAVATAR_DEFAULTS: # treat the default as a url default = urllib.quote(default, safe='') return literal('''<img src="//gravatar.com/avatar/%s?s=%d&amp;d=%s" class="gravatar" width="%s" height="%s" />''' % (email_hash, size, default, size, size) ) def pager_url(page, partial=None, **kwargs): routes_dict = _pylons_default_url.environ['pylons.routes_dict'] kwargs['controller'] = routes_dict['controller'] kwargs['action'] = routes_dict['action'] if routes_dict.get('id'): kwargs['id'] = routes_dict['id'] kwargs['page'] = page return url(**kwargs) class Page(paginate.Page): # Curry the pager method of the webhelpers.paginate.Page class, so we have # our custom layout set as default. def pager(self, *args, **kwargs): kwargs.update( format=u"<div class='pagination pagination-centered'><ul>$link_previous ~2~ $link_next</ul></div>", symbol_previous=u'«', symbol_next=u'»', curpage_attr={'class': 'active'}, link_attr={} ) return super(Page, self).pager(*args, **kwargs) # Put each page link into a <li> (for Bootstrap to style it) def _pagerlink(self, page, text, extra_attributes=None): anchor = super(Page, self)._pagerlink(page, text) extra_attributes = extra_attributes or {} return HTML.li(anchor, **extra_attributes) # Change 'current page' link from <span> to <li><a> # and '..' into '<li><a>..' # (for Bootstrap to style them properly) def _range(self, regexp_match): html = super(Page, self)._range(regexp_match) # Convert .. dotdot = '<span class="pager_dotdot">..</span>' dotdot_link = HTML.li(HTML.a('...', href='#'), class_='disabled') html = re.sub(dotdot, dotdot_link, html) # Convert current page text = '%s' % self.page current_page_span = str(HTML.span(c=text, **self.curpage_attr)) current_page_link = self._pagerlink(self.page, text, extra_attributes=self.curpage_attr) return re.sub(current_page_span, current_page_link, html) def render_datetime(datetime_, date_format=None, with_hours=False): '''Render a datetime object or timestamp string as a localised date or in the requested format. If timestamp is badly formatted, then a blank string is returned. :param datetime_: the date :type datetime_: datetime or ISO string format :param date_format: a date format :type date_format: string :param with_hours: should the `hours:mins` be shown :type with_hours: bool :rtype: string ''' datetime_ = _datestamp_to_datetime(datetime_) if not datetime_: return '' # if date_format was supplied we use it if date_format: return datetime_.strftime(date_format) # the localised date return formatters.localised_nice_date(datetime_, show_date=True, with_hours=with_hours) def date_str_to_datetime(date_str): '''Convert ISO-like formatted datestring to datetime object. This function converts ISO format date- and datetime-strings into datetime objects. Times may be specified down to the microsecond. UTC offset or timezone information may **not** be included in the string. Note - Although originally documented as parsing ISO date(-times), this function doesn't fully adhere to the format. This function will throw a ValueError if the string contains UTC offset information. So in that sense, it is less liberal than ISO format. On the other hand, it is more liberal of the accepted delimiters between the values in the string. Also, it allows microsecond precision, despite that not being part of the ISO format. ''' time_tuple = re.split('[^\d]+', date_str, maxsplit=5) # Extract seconds and microseconds if len(time_tuple) >= 6: m = re.match('(?P<seconds>\d{2})(\.(?P<microseconds>\d{6}))?$', time_tuple[5]) if not m: raise ValueError('Unable to parse %s as seconds.microseconds' % time_tuple[5]) seconds = int(m.groupdict().get('seconds')) microseconds = int(m.groupdict(0).get('microseconds')) time_tuple = time_tuple[:5] + [seconds, microseconds] return datetime.datetime(*map(int, time_tuple)) def parse_rfc_2822_date(date_str, assume_utc=True): ''' Parse a date string of the form specified in RFC 2822, and return a datetime. RFC 2822 is the date format used in HTTP headers. It should contain timezone information, but that cannot be relied upon. If date_str doesn't contain timezone information, then the 'assume_utc' flag determines whether we assume this string is local (with respect to the server running this code), or UTC. In practice, what this means is that if assume_utc is True, then the returned datetime is 'aware', with an associated tzinfo of offset zero. Otherwise, the returned datetime is 'naive'. If timezone information is available in date_str, then the returned datetime is 'aware', ie - it has an associated tz_info object. Returns None if the string cannot be parsed as a valid datetime. ''' time_tuple = email.utils.parsedate_tz(date_str) # Not parsable if not time_tuple: return None # No timezone information available in the string if time_tuple[-1] is None and not assume_utc: return datetime.datetime.fromtimestamp( email.utils.mktime_tz(time_tuple)) else: offset = 0 if time_tuple[-1] is None else time_tuple[-1] tz_info = _RFC2282TzInfo(offset) return datetime.datetime(*time_tuple[:6], microsecond=0, tzinfo=tz_info) class _RFC2282TzInfo(datetime.tzinfo): ''' A datetime.tzinfo implementation used by parse_rfc_2822_date() function. In order to return timezone information, a concrete implementation of datetime.tzinfo is required. This class represents tzinfo that knows about it's offset from UTC, has no knowledge of daylight savings time, and no knowledge of the timezone name. ''' def __init__(self, offset): ''' offset from UTC in seconds. ''' self.offset = datetime.timedelta(seconds=offset) def utcoffset(self, dt): return self.offset def dst(self, dt): ''' Dates parsed from an RFC 2822 string conflate timezone and dst, and so it's not possible to determine whether we're in DST or not, hence returning None. ''' return None def tzname(self, dt): return None @maintain.deprecated('h.time_ago_in_words_from_str is deprecated in 2.2 ' 'and will be removed. Please use ' 'h.time_ago_from_timestamp instead') def time_ago_in_words_from_str(date_str, granularity='month'): '''Deprecated in 2.2 use time_ago_from_timestamp''' if date_str: return date.time_ago_in_words(date_str_to_datetime(date_str), granularity=granularity) else: return _('Unknown') def time_ago_from_timestamp(timestamp): ''' Returns a string like `5 months ago` for a datetime relative to now :param timestamp: the timestamp or datetime :type timestamp: string or datetime :rtype: string ''' datetime_ = _datestamp_to_datetime(timestamp) if not datetime_: return _('Unknown') # the localised date return formatters.localised_nice_date(datetime_, show_date=False) def button_attr(enable, type='primary'): if enable: return 'class="btn %s"' % type return 'disabled class="btn disabled"' def dataset_display_name(package_or_package_dict): if isinstance(package_or_package_dict, dict): return package_or_package_dict.get('title', '') or \ package_or_package_dict.get('name', '') else: return package_or_package_dict.title or package_or_package_dict.name def dataset_link(package_or_package_dict): if isinstance(package_or_package_dict, dict): name = package_or_package_dict['name'] else: name = package_or_package_dict.name text = dataset_display_name(package_or_package_dict) return link_to( text, url_for(controller='package', action='read', id=name) ) # TODO: (?) support resource objects as well def resource_display_name(resource_dict): name = resource_dict.get('name', None) description = resource_dict.get('description', None) if name: return name elif description: description = description.split('.')[0] max_len = 60 if len(description) > max_len: description = description[:max_len] + '...' return description else: return _("Unnamed resource") def resource_link(resource_dict, package_id): text = resource_display_name(resource_dict) url = url_for(controller='package', action='resource_read', id=package_id, resource_id=resource_dict['id']) return link_to(text, url) def related_item_link(related_item_dict): text = related_item_dict.get('title', '') url = url_for(controller='related', action='read', id=related_item_dict['id']) return link_to(text, url) def tag_link(tag): url = url_for(controller='tag', action='read', id=tag['name']) return link_to(tag.get('title', tag['name']), url) def group_link(group): url = url_for(controller='group', action='read', id=group['name']) return link_to(group['title'], url) def organization_link(organization): url = url_for(controller='organization', action='read', id=organization['name']) return link_to(organization['name'], url) def dump_json(obj, **kw): return json.dumps(obj, **kw) def _get_template_name(): #FIX ME THIS IS BROKEN ''' helper function to get the currently/last rendered template name ''' return c.__debug_info[-1]['template_name'] def auto_log_message(): if (c.action == 'new'): return _('Created new dataset.') elif (c.action == 'editresources'): return _('Edited resources.') elif (c.action == 'edit'): return _('Edited settings.') return '' def activity_div(template, activity, actor, object=None, target=None): actor = '<span class="actor">%s</span>' % actor if object: object = '<span class="object">%s</span>' % object if target: target = '<span class="target">%s</span>' % target rendered_datetime = render_datetime(activity['timestamp']) date = '<span class="date">%s</span>' % rendered_datetime template = template.format(actor=actor, date=date, object=object, target=target) template = '<div class="activity">%s %s</div>' % (template, date) return literal(template) def snippet(template_name, **kw): ''' This function is used to load html snippets into pages. keywords can be used to pass parameters into the snippet rendering ''' import ckan.lib.base as base return base.render_snippet(template_name, **kw) def convert_to_dict(object_type, objs): ''' This is a helper function for converting lists of objects into lists of dicts. It is for backwards compatability only. ''' def dictize_revision_list(revision, context): # conversionof revision lists def process_names(items): array = [] for item in items: array.append(item.name) return array rev = {'id': revision.id, 'state': revision.state, 'timestamp': revision.timestamp, 'author': revision.author, 'packages': process_names(revision.packages), 'groups': process_names(revision.groups), 'message': revision.message, } return rev import ckan.lib.dictization.model_dictize as md converters = {'package': md.package_dictize, 'revisions': dictize_revision_list} converter = converters[object_type] items = [] context = {'model': model} for obj in objs: item = converter(obj, context) items.append(item) return items # these are the types of objects that can be followed _follow_objects = ['dataset', 'user', 'group'] def follow_button(obj_type, obj_id): '''Return a follow button for the given object type and id. If the user is not logged in return an empty string instead. :param obj_type: the type of the object to be followed when the follow button is clicked, e.g. 'user' or 'dataset' :type obj_type: string :param obj_id: the id of the object to be followed when the follow button is clicked :type obj_id: string :returns: a follow button as an HTML snippet :rtype: string ''' obj_type = obj_type.lower() assert obj_type in _follow_objects # If the user is logged in show the follow/unfollow button if c.user: context = {'model': model, 'session': model.Session, 'user': c.user} action = 'am_following_%s' % obj_type following = logic.get_action(action)(context, {'id': obj_id}) return snippet('snippets/follow_button.html', following=following, obj_id=obj_id, obj_type=obj_type) return '' def follow_count(obj_type, obj_id): '''Return the number of followers of an object. :param obj_type: the type of the object, e.g. 'user' or 'dataset' :type obj_type: string :param obj_id: the id of the object :type obj_id: string :returns: the number of followers of the object :rtype: int ''' obj_type = obj_type.lower() assert obj_type in _follow_objects action = '%s_follower_count' % obj_type context = {'model': model, 'session': model.Session, 'user': c.user} return logic.get_action(action)(context, {'id': obj_id}) def _create_url_with_params(params=None, controller=None, action=None, extras=None): ''' internal function for building urls with parameters. ''' if not controller: controller = c.controller if not action: action = c.action if not extras: extras = {} url = url_for(controller=controller, action=action, **extras) return _url_with_params(url, params) def add_url_param(alternative_url=None, controller=None, action=None, extras=None, new_params=None): ''' Adds extra parameters to existing ones controller action & extras (dict) are used to create the base url via :py:func:`~ckan.lib.helpers.url_for` controller & action default to the current ones This can be overriden providing an alternative_url, which will be used instead. ''' params_nopage = [(k, v) for k, v in request.params.items() if k != 'page'] params = set(params_nopage) if new_params: params |= set(new_params.items()) if alternative_url: return _url_with_params(alternative_url, params) return _create_url_with_params(params=params, controller=controller, action=action, extras=extras) def remove_url_param(key, value=None, replace=None, controller=None, action=None, extras=None, alternative_url=None): ''' Remove one or multiple keys from the current parameters. The first parameter can be either a string with the name of the key to remove or a list of keys to remove. A specific key/value pair can be removed by passing a second value argument otherwise all pairs matching the key will be removed. If replace is given then a new param key=replace will be added. Note that the value and replace parameters only apply to the first key provided (or the only one provided if key is a string). controller action & extras (dict) are used to create the base url via :py:func:`~ckan.lib.helpers.url_for` controller & action default to the current ones This can be overriden providing an alternative_url, which will be used instead. ''' if isinstance(key, basestring): keys = [key] else: keys = key params_nopage = [(k, v) for k, v in request.params.items() if k != 'page'] params = list(params_nopage) if value: params.remove((keys[0], value)) else: for key in keys: [params.remove((k, v)) for (k, v) in params[:] if k == key] if replace is not None: params.append((keys[0], replace)) if alternative_url: return _url_with_params(alternative_url, params) return _create_url_with_params(params=params, controller=controller, action=action, extras=extras) def include_resource(resource): r = getattr(fanstatic_resources, resource) r.need() def urls_for_resource(resource): ''' Returns a list of urls for the resource specified. If the resource is a group or has dependencies then there can be multiple urls. NOTE: This is for special situations only and is not the way to generally include resources. It is advised not to use this function.''' r = getattr(fanstatic_resources, resource) resources = list(r.resources) core = fanstatic_resources.fanstatic_extensions.core f = core.get_needed() lib = r.library root_path = f.library_url(lib) resources = core.sort_resources(resources) if f._bundle: resources = core.bundle_resources(resources) out = [] for resource in resources: if isinstance(resource, core.Bundle): paths = [resource.relpath for resource in resource.resources()] relpath = ';'.join(paths) relpath = core.BUNDLE_PREFIX + relpath else: relpath = resource.relpath out.append('%s/%s' % (root_path, relpath)) return out def debug_inspect(arg): ''' Output pprint.pformat view of supplied arg ''' return literal('<pre>') + pprint.pformat(arg) + literal('</pre>') def debug_full_info_as_list(debug_info): ''' This dumps the template variables for debugging purposes only. ''' out = [] ignored_keys = ['c', 'app_globals', 'g', 'h', 'request', 'tmpl_context', 'actions', 'translator', 'session', 'N_', 'ungettext', 'config', 'response', '_'] ignored_context_keys = ['__class__', '__context', '__delattr__', '__dict__', '__doc__', '__format__', '__getattr__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'action', 'environ', 'pylons', 'start_response'] debug_vars = debug_info['vars'] for key in debug_vars.keys(): if not key in ignored_keys: data = pprint.pformat(debug_vars.get(key)) data = data.decode('utf-8') out.append((key, data)) if 'tmpl_context' in debug_vars: for key in debug_info['c_vars']: if not key in ignored_context_keys: data = pprint.pformat(getattr(debug_vars['tmpl_context'], key)) data = data.decode('utf-8') out.append(('c.%s' % key, data)) return out def popular(type_, number, min=1, title=None): ''' display a popular icon. ''' if type_ == 'views': title = ungettext('{number} view', '{number} views', number) elif type_ == 'recent views': title = ungettext('{number} recent view', '{number} recent views', number) elif not title: raise Exception('popular() did not recieve a valid type_ or title') return snippet('snippets/popular.html', title=title, number=number, min=min) def groups_available(am_member=False): '''Return a list of the groups that the user is authorized to edit. :param am_member: if True return only the groups the logged-in user is a member of, otherwise return all groups that the user is authorized to edit (for example, sysadmin users are authorized to edit all groups) (optional, default: False) :type am-member: boolean ''' context = {} data_dict = {'available_only': True, 'am_member': am_member} return logic.get_action('group_list_authz')(context, data_dict) def organizations_available(permission='edit_group'): ''' return a list of available organizations ''' context = {'user': c.user} data_dict = {'permission': permission} return logic.get_action('organization_list_for_user')(context, data_dict) def user_in_org_or_group(group_id): ''' Check if user is in a group or organization ''' # we need a user if not c.userobj: return False # sysadmins can do anything if c.userobj.sysadmin: return True query = model.Session.query(model.Member) \ .filter(model.Member.state == 'active') \ .filter(model.Member.table_name == 'user') \ .filter(model.Member.group_id == group_id) \ .filter(model.Member.table_id == c.userobj.id) return len(query.all()) != 0 def dashboard_activity_stream(user_id, filter_type=None, filter_id=None, offset=0): '''Return the dashboard activity stream of the current user. :param user_id: the id of the user :type user_id: string :param filter_type: the type of thing to filter by :type filter_type: string :param filter_id: the id of item to filter by :type filter_id: string :returns: an activity stream as an HTML snippet :rtype: string ''' context = {'model': model, 'session': model.Session, 'user': c.user} if filter_type: action_functions = { 'dataset': 'package_activity_list_html', 'user': 'user_activity_list_html', 'group': 'group_activity_list_html', 'organization': 'organization_activity_list_html', } action_function = logic.get_action(action_functions.get(filter_type)) return action_function(context, {'id': filter_id, 'offset': offset}) else: return logic.get_action('dashboard_activity_list_html')( context, {'offset': offset}) def recently_changed_packages_activity_stream(limit=None): if limit: data_dict = {'limit': limit} else: data_dict = {} context = {'model': model, 'session': model.Session, 'user': c.user} return logic.get_action('recently_changed_packages_activity_list_html')( context, data_dict) def escape_js(str_to_escape): '''Escapes special characters from a JS string. Useful e.g. when you need to pass JSON to the templates :param str_to_escape: string to be escaped :rtype: string ''' return str_to_escape.replace('\\', '\\\\') \ .replace('\'', '\\\'') \ .replace('"', '\\\"') def get_pkg_dict_extra(pkg_dict, key, default=None): '''Returns the value for the dataset extra with the provided key. If the key is not found, it returns a default value, which is None by default. :param pkg_dict: dictized dataset :key: extra key to lookup :default: default value returned if not found ''' extras = pkg_dict['extras'] if 'extras' in pkg_dict else [] for extra in extras: if extra['key'] == key: return extra['value'] return default def get_request_param(parameter_name, default=None): ''' This function allows templates to access query string parameters from the request. This is useful for things like sort order in searches. ''' return request.params.get(parameter_name, default) # find all inner text of html eg `<b>moo</b>` gets `moo` but not of <a> tags # as this would lead to linkifying links if they are urls. RE_MD_GET_INNER_HTML = re.compile( r'(^|(?:<(?!a\b)[^>]*>))([^<]+)(?=<|$)', flags=re.UNICODE ) # find all `internal links` eg. tag:moo, dataset:1234, tag:"my tag" RE_MD_INTERNAL_LINK = re.compile( r'\b(tag|package|dataset|group):((")?(?(3)[ \w\-.]+|[\w\-.]+)(?(3)"))', flags=re.UNICODE ) # find external links eg http://foo.com, https://bar.org/foobar.html # but ignore trailing punctuation since it is probably not part of the link RE_MD_EXTERNAL_LINK = re.compile( r'(\bhttps?:\/\/[\w\-\.,@?^=%&;:\/~\\+#]*' '[\w\-@?^=%&:\/~\\+#]' # but last character can't be punctuation [.,;] ')', flags=re.UNICODE ) # find all tags but ignore < in the strings so that we can use it correctly # in markdown RE_MD_HTML_TAGS = re.compile('<[^><]*>') def html_auto_link(data): '''Linkifies HTML tag:... converted to a tag link dataset:... converted to a dataset link group:... converted to a group link http://... converted to a link ''' LINK_FNS = { 'tag': tag_link, 'group': group_link, 'dataset': dataset_link, 'package': dataset_link, } def makelink(matchobj): obj = matchobj.group(1) name = matchobj.group(2) title = '%s:%s' % (obj, name) return LINK_FNS[obj]({'name': name.strip('"'), 'title': title}) def link(matchobj): return '<a href="%s" target="_blank" rel="nofollow">%s</a>' \ % (matchobj.group(1), matchobj.group(1)) def process(matchobj): data = matchobj.group(2) data = RE_MD_INTERNAL_LINK.sub(makelink, data) data = RE_MD_EXTERNAL_LINK.sub(link, data) return matchobj.group(1) + data data = RE_MD_GET_INNER_HTML.sub(process, data) return data def render_markdown(data, auto_link=True, allow_html=False): ''' Returns the data as rendered markdown :param auto_link: Should ckan specific links be created e.g. `group:xxx` :type auto_link: bool :param allow_html: If True then html entities in the markdown data. This is dangerous if users have added malicious content. If False all html tags are removed. :type allow_html: bool ''' if not data: return '' if allow_html: data = markdown(data.strip(), safe_mode=False) else: data = RE_MD_HTML_TAGS.sub('', data.strip()) data = markdown(data, safe_mode=True) # tags can be added by tag:... or tag:"...." and a link will be made # from it if auto_link: data = html_auto_link(data) return literal(data) def format_resource_items(items): ''' Take a resource item list and format nicely with blacklisting etc. ''' blacklist = ['name', 'description', 'url', 'tracking_summary'] output = [] # regular expressions for detecting types in strings reg_ex_datetime = '^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{6})?$' reg_ex_int = '^-?\d{1,}$' reg_ex_float = '^-?\d{1,}\.\d{1,}$' for key, value in items: if not value or key in blacklist: continue # size is treated specially as we want to show in MiB etc if key == 'size': try: value = formatters.localised_filesize(int(value)) except ValueError: # Sometimes values that can't be converted to ints can sneak # into the db. In this case, just leave them as they are. pass elif isinstance(value, basestring): # check if strings are actually datetime/number etc if re.search(reg_ex_datetime, value): datetime_ = date_str_to_datetime(value) value = formatters.localised_nice_date(datetime_) elif re.search(reg_ex_float, value): value = formatters.localised_number(float(value)) elif re.search(reg_ex_int, value): value = formatters.localised_number(int(value)) elif isinstance(value, int) or isinstance(value, float): value = formatters.localised_number(value) key = key.replace('_', ' ') output.append((key, value)) return sorted(output, key=lambda x: x[0]) def resource_preview(resource, package): ''' Returns a rendered snippet for a embedded resource preview. Depending on the type, different previews are loaded. This could be an img tag where the image is loaded directly or an iframe that embeds a web page, recline or a pdf preview. ''' if not resource['url']: return False format_lower = datapreview.res_format(resource) directly = False data_dict = {'resource': resource, 'package': package} if datapreview.get_preview_plugin(data_dict, return_first=True): url = url_for(controller='package', action='resource_datapreview', resource_id=resource['id'], id=package['id'], qualified=True) else: return False return snippet("dataviewer/snippets/data_preview.html", embed=directly, resource_url=url, raw_resource_url=resource.get('url')) def get_allowed_view_types(resource, package): data_dict = {'resource': resource, 'package': package} plugins = datapreview.get_allowed_view_plugins(data_dict) allowed_view_types = [] for plugin in plugins: info = plugin.info() allowed_view_types.append((info['name'], info.get('title', info['name']), info.get('icon', 'image'))) allowed_view_types.sort(key=lambda item: item[1]) return allowed_view_types def rendered_resource_view(resource_view, resource, package, embed=False): ''' Returns a rendered resource view snippet. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) context = {} data_dict = {'resource_view': resource_view, 'resource': resource, 'package': package} vars = view_plugin.setup_template_variables(context, data_dict) or {} template = view_plugin.view_template(context, data_dict) data_dict.update(vars) if not resource_view_is_iframed(resource_view) and embed: template = "package/snippets/resource_view_embed.html" import ckan.lib.base as base return literal(base.render(template, extra_vars=data_dict)) def view_resource_url(resource_view, resource, package, **kw): ''' Returns url for resource. made to be overridden by extensions. i.e by resource proxy. ''' return resource['url'] def resource_view_is_filterable(resource_view): ''' Returns True if the given resource view support filters. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) return view_plugin.info().get('filterable', False) def resource_view_get_fields(resource): '''Returns sorted list of text and time fields of a datastore resource.''' if not resource.get('datastore_active'): return [] data = { 'resource_id': resource['id'], 'limit': 0 } result = logic.get_action('datastore_search')({}, data) fields = [field['id'] for field in result.get('fields', [])] return sorted(fields) def resource_view_is_iframed(resource_view): ''' Returns true if the given resource view should be displayed in an iframe. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) return view_plugin.info().get('iframed', True) def resource_view_icon(resource_view): ''' Returns the icon for a particular view type. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) return view_plugin.info().get('icon', 'picture') def resource_view_display_preview(resource_view): ''' Returns if the view should display a preview. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) return view_plugin.info().get('preview_enabled', True) def resource_view_full_page(resource_view): ''' Returns if the edit view page should be full page. ''' view_plugin = datapreview.get_view_plugin(resource_view['view_type']) return view_plugin.info().get('full_page_edit', False) def remove_linebreaks(string): '''Remove linebreaks from string to make it usable in JavaScript''' return str(string).replace('\n', '') def list_dict_filter(list_, search_field, output_field, value): ''' Takes a list of dicts and returns the value of a given key if the item has a matching value for a supplied key :param list_: the list to search through for matching items :type list_: list of dicts :param search_field: the key to use to find matching items :type search_field: string :param output_field: the key to use to output the value :type output_field: string :param value: the value to search for ''' for item in list_: if item.get(search_field) == value: return item.get(output_field, value) return value def SI_number_span(number): ''' outputs a span with the number in SI unit eg 14700 -> 14.7k ''' number = int(number) if number < 1000: output = literal('<span>') else: output = literal('<span title="' + formatters.localised_number(number) + '">') return output + formatters.localised_SI_number(number) + literal('</span>') # add some formatter functions localised_number = formatters.localised_number localised_SI_number = formatters.localised_SI_number localised_nice_date = formatters.localised_nice_date localised_filesize = formatters.localised_filesize def new_activities(): '''Return the number of activities for the current user. See :func:`logic.action.get.dashboard_new_activities_count` for more details. ''' if not c.userobj: return None action = logic.get_action('dashboard_new_activities_count') return action({}, {}) def uploads_enabled(): if uploader.get_storage_path(): return True return False def get_featured_organizations(count=1): '''Returns a list of favourite organization in the form of organization_list action function ''' config_orgs = config.get('ckan.featured_orgs', '').split() orgs = featured_group_org(get_action='organization_show', list_action='organization_list', count=count, items=config_orgs) return orgs def get_featured_groups(count=1): '''Returns a list of favourite group the form of organization_list action function ''' config_groups = config.get('ckan.featured_groups', '').split() groups = featured_group_org(get_action='group_show', list_action='group_list', count=count, items=config_groups) return groups def featured_group_org(items, get_action, list_action, count): def get_group(id): context = {'ignore_auth': True, 'limits': {'packages': 2}, 'for_view': True} data_dict = {'id': id} try: out = logic.get_action(get_action)(context, data_dict) except logic.NotFound: return None return out groups_data = [] extras = logic.get_action(list_action)({}, {}) # list of found ids to prevent duplicates found = [] for group_name in items + extras: group = get_group(group_name) if not group: continue # check if duplicate if group['id'] in found: continue found.append(group['id']) groups_data.append(group) if len(groups_data) == count: break return groups_data def get_site_statistics(): stats = {} stats['dataset_count'] = logic.get_action('package_search')( {}, {"rows": 1})['count'] stats['group_count'] = len(logic.get_action('group_list')({}, {})) stats['organization_count'] = len( logic.get_action('organization_list')({}, {})) result = model.Session.execute( '''select count(*) from related r left join related_dataset rd on r.id = rd.related_id where rd.status = 'active' or rd.id is null''').first()[0] stats['related_count'] = result return stats _RESOURCE_FORMATS = None def resource_formats(): ''' Returns the resource formats as a dict, sourced from the resource format JSON file. key: potential user input value value: [canonical mimetype lowercased, canonical format (lowercase), human readable form] Fuller description of the fields are described in `ckan/config/resource_formats.json`. ''' global _RESOURCE_FORMATS if not _RESOURCE_FORMATS: _RESOURCE_FORMATS = {} format_file_path = config.get('ckan.resource_formats') if not format_file_path: format_file_path = os.path.join( os.path.dirname(os.path.realpath(ckan.config.__file__)), 'resource_formats.json' ) with open(format_file_path) as format_file: try: file_resource_formats = json.loads(format_file.read()) except ValueError, e: # includes simplejson.decoder.JSONDecodeError raise ValueError('Invalid JSON syntax in %s: %s' % (format_file_path, e)) for format_line in file_resource_formats: if format_line[0] == '_comment': continue line = [format_line[2], format_line[0], format_line[1]] alternatives = format_line[3] if len(format_line) == 4 else [] for item in line + alternatives: if item: item = item.lower() if item in _RESOURCE_FORMATS \ and _RESOURCE_FORMATS[item] != line: raise ValueError('Duplicate resource format ' 'identifier in %s: %s' % (format_file_path, item)) _RESOURCE_FORMATS[item] = line return _RESOURCE_FORMATS def unified_resource_format(format): formats = resource_formats() format_clean = format.lower() if format_clean in formats: format_new = formats[format_clean][1] else: format_new = format return format_new def check_config_permission(permission): return new_authz.check_config_permission(permission) def get_organization(org=None, include_datasets=False): if org is None: return {} try: return logic.get_action('organization_show')({}, {'id': org, 'include_datasets': include_datasets}) except (NotFound, ValidationError, NotAuthorized): return {} # these are the functions that will end up in `h` template helpers __allowed_functions__ = [ # functions defined in ckan.lib.helpers 'redirect_to', 'url', 'url_for', 'url_for_static', 'url_for_static_or_external', 'is_url', 'lang', 'flash', 'flash_error', 'flash_notice', 'flash_success', 'nav_link', 'nav_named_link', 'subnav_link', 'subnav_named_route', 'default_group_type', 'check_access', 'get_action', 'linked_user', 'group_name_to_title', 'markdown_extract', 'icon', 'icon_html', 'icon_url', 'resource_icon', 'format_icon', 'linked_gravatar', 'gravatar', 'pager_url', 'render_datetime', 'date_str_to_datetime', 'parse_rfc_2822_date', 'time_ago_in_words_from_str', 'button_attr', 'dataset_display_name', 'dataset_link', 'resource_display_name', 'resource_link', 'related_item_link', 'tag_link', 'group_link', 'dump_json', 'auto_log_message', 'snippet', 'convert_to_dict', 'activity_div', 'lang_native_name', 'get_facet_items_dict', 'unselected_facet_items', 'include_resource', 'urls_for_resource', 'build_nav_main', 'build_nav_icon', 'build_nav', 'debug_inspect', 'dict_list_reduce', 'full_current_url', 'popular', 'debug_full_info_as_list', 'get_facet_title', 'get_param_int', 'sorted_extras', 'follow_button', 'follow_count', 'remove_url_param', 'add_url_param', 'groups_available', 'organizations_available', 'user_in_org_or_group', 'dashboard_activity_stream', 'recently_changed_packages_activity_stream', 'escape_js', 'get_pkg_dict_extra', 'get_request_param', 'render_markdown', 'format_resource_items', 'resource_preview', 'rendered_resource_view', 'resource_view_get_fields', 'resource_view_is_filterable', 'resource_view_is_iframed', 'resource_view_icon', 'resource_view_display_preview', 'resource_view_full_page', 'remove_linebreaks', 'SI_number_span', 'localised_number', 'localised_SI_number', 'localised_nice_date', 'localised_filesize', 'list_dict_filter', 'new_activities', 'time_ago_from_timestamp', 'get_organization', 'has_more_facets', # imported into ckan.lib.helpers 'literal', 'link_to', 'get_available_locales', 'get_locales_dict', 'truncate', 'file', 'mail_to', 'radio', 'submit', 'asbool', 'uploads_enabled', 'get_featured_organizations', 'get_featured_groups', 'get_site_statistics', 'get_allowed_view_types', 'urlencode', 'check_config_permission', 'view_resource_url', ]
group = model.Group.by_name(name) if group is not None: return group.display_name return name
jp.js
(function (translator) { translator.translations["jp"] = { // javascript alerts or messages "testneteditionactivated": "テストネット版が有効になりました。", "paperlabelbitcoinaddress": "MillenniumClubアドレス", "paperlabelprivatekey": "プライベートキー", "paperlabelencryptedkey": "暗号化されたプライベートキー(パスワード必須)", "bulkgeneratingaddresses": "アドレス生成中...", "brainalertpassphrasetooshort": "パスワードが短すぎます \n\n", "brainalertpassphrasewarning": "注意:強いパスワードを選ばないとプライベートキーを安易に当てられてMillenniumClubを盗まれてしまいます。<br>なお、<b>UTF-8の文字も使えるため、キーボードが半角か全角か今一度ご確認下さい。</b>", "brainalertpassphrasedoesnotmatch": "パスワードが一致しません", "detailalertnotvalidprivatekey": "入力された文字列は有効なプライベートキーではありません。", "detailconfirmsha256": "入力された文字列は有効なプライベートキーではありません。\n\n代わりにこの文字列をパスワードとして、SHA256ハッシュを用いプライベートキーを生成しますか?\n\n注意: 強いパスワードを選ばないとプライベートキーを安易に当てられてMillenniumClubを盗まれてしまいます。", "bip38alertincorrectpassphrase": "暗号化されたプライベートキーに一致しないパスワードです。", "bip38alertpassphraserequired": "BIP38キーを生成するにはパスワードをかける必要があります。", "vanityinvalidinputcouldnotcombinekeys": "不正入力です。キーを結合できませんでした。", "vanityalertinvalidinputpublickeysmatch": "不正入力です。両方のパブリックキーが同じです。2つの異なるキーをお使い下さい。", "vanityalertinvalidinputcannotmultiple": "不正入力です。2つのパブリックキーを掛け合わせることはできません。「足し算」を選択し、2つのパブリックキーを足し合わせてアドレスを生成して下さい。", "vanityprivatekeyonlyavailable": "2つのプライベートキーを掛け合わせた時だけ有効です。", "vanityalertinvalidinputprivatekeysmatch": "不正入力両方のプライベートキーがチケットに一致します。2つの異なるキーをお使い下さい。", // header and menu html "tagline": "クライエント側MillenniumClubアドレス生成(JavaScript使用)", "generatelabelbitcoinaddress": "MillenniumClubアドレスを生成中...", "generatelabelmovemouse": "マウスを動かして、ランダム要素を追加してください。", "generatelabelkeypress": "もしくはこちらの入力欄にランダムな文字を打って下さい。", "singlewallet": "シングルウォレット", "paperwallet": "ペーパーウォレット", "bulkwallet": "大量ウォレット", "brainwallet": "暗記ウォレット", "vanitywallet": "カスタムウォレット", "splitwallet": "Split Wallet", //TODO: please translate "detailwallet": "ウォレットの詳細", // footer html "footerlabeldonations": "プロジェクト寄付先", "footerlabeltranslatedby": "日本語訳寄付先 1o3EBhxPhGn8cGCL6Wzi5F5kTPuBofdMf", "footerlabelpgp": "PGP", "footerlabelversion": "バージョン履歴", "footerlabelgithub": "GitHubリポジトリ", "footerlabelgithubzip": "zip", "footerlabelsig": "sig", "footerlabelcopyright1": "Copyright bitaddress.org, The MillenniumClub Developers.", "footerlabelcopyright2": "JavaScriptのコピーライト情報はソースに含まれています。", "footerlabelnowarranty": "保障はありません。", // status html "statuslabelcryptogood": "&#10004; Good!", //TODO: please translate "statuslabelcryptogood1": "Your browser can generate cryptographically random keys using window.crypto.getRandomValues", //TODO: please translate "statusokcryptogood": "OK", //TODO: please translate "statuslabelcryptobad": "&times; Oh no!", //TODO: please translate "statuslabelcryptobad1": "Your browser does NOT support window.crypto.getRandomValues. You should use a more modern browser with this generator to increase the security of the keys generated.", "statusokcryptobad": "OK", //TODO: please translate "statuslabelunittestsgood": "&#10004; Good!", //TODO: please translate "statuslabelunittestsgood1": "All synchronous unit tests passed.", //TODO: please translate "statusokunittestsgood": "OK", //TODO: please translate "statuslabelunittestsbad": "&times; Oh no!", //TODO: please translate "statuslabelunittestsbad1": "Some synchronous unit tests DID NOT pass. You should find another browser to use with this generator.", //TODO: please translate "statusokunittestsbad": "OK", //TODO: please translate "statuslabelprotocolgood": "&#10004; Good!", //TODO: please translate "statuslabelprotocolgood1": "You are running this generator from your local computer. <br />Tip: Double check you are offline by trying ", //TODO: please translate "statusokprotocolgood": "OK", //TODO: please translate "statuslabelprotocolbad": "&#9888; Think twice!", //TODO: please translate "statuslabelprotocolbad1": "You appear to be running this generator online from a live website. For valuable wallets it is recommended to", //TODO: please translate "statuslabelprotocolbad2": "download", //TODO: please translate "statuslabelprotocolbad3": "the zip file from GitHub and run this generator offline as a local html file.", //TODO: please translate "statusokprotocolbad": "OK", //TODO: please translate "statuslabelkeypool1": "This is a log of all the MillenniumClub Addresses and Private Keys you generated during your current session. Reloading the page will create a new session.", //TODO: please translate "statuskeypoolrefresh": "Refresh", //TODO: please translate "statusokkeypool": "OK", //TODO: please translate
"singleprint": "印刷", "singlelabelbitcoinaddress": "MillenniumClubアドレス", "singlelabelprivatekey": "プライベートキー (WIF形式)", "singletip1": "<b>MillenniumClubウォレットとは</b> MillenniumClubのアドレスと対応するプライベートキーを組み合わせたものです。新しいアドレスがブラウザー上で生成され、上記に表示されています。", "singletip2": "<b>このウォレットを守るためには</b> MillenniumClubアドレスとMillenniumClubプライベートキーを印刷するなどの手段で記録しなければいけません。プライベートキーが無いとペアになっているアドレスに送られたMillenniumClubが使えないので、人に晒されないような方法でプライベートキーのコピーを取り、大事に保管して下さい。このサイトはこのプライベートキーの保存はしません。PGPをご存知の方は、このサイトを1つのhtmlファイルで落とすことができるので、このサイトのhtmlファイルのSHA256ハッシュとサイトのフッターにデジタル署名されたメッセージに入ったハッシュを比べて不正にいじられていないかをお確かめいただけます。このページを閉じたり、離れたり、”新アドレス生成”を押すと現在表示されているプライベートキーは消え、新規アドレスが生成されるので、ご使用の場合は必ず何らかの手段で記録しておいて下さい。プライベートキーは秘密にしてください。共有されますと、対応するMillenniumClubアドレスに存在するコインが全て共有者間で利用可能となります。ウォレット情報を印刷したら、濡れないようにジップロックに入れましょう。紙幣と同様に扱うよう心がけてください。", "singletip3": "<b>このウォレットにコインを追加 : </b> 他の人から自分のMillenniumClubアドレスに送ってもらう。", "singletip4": "<b>残高照会は</b> explorer.millenniumclub.caに行き、MillenniumClubアドレスを入力してお調べ下さい。", "singletip5": "<b>MillenniumClubを使おう。</b> 送金するには、このページで生成したプライベートキーをパソコン・スマホ端末にあるウォレットアプリなどに取り込んで使えます。しかし、その時点でそのアドレスが取り込んだウォレットの他のアドレスと融合してしまい、この一つのアドレスのバックアップだけじゃビットコインを保管することはできなくなります。取り込み先のウォレットを強いパスワードで暗号化し、バックアップして、安全に扱って下さい。ビットコインの考案者「サトシさん」曰く、「一度作ったウォレットを、空にしたとしても、削除しない方が良い。」(メールアドレスと同じく、いつ昔の友達や親戚から古いアドレス宛にビットコインを送ってくるかわかりませんから。)", // paper wallet html "paperlabelhideart": "デザイン非表示", "paperlabeladdressesperpage": "1ページごとのアドレス数", "paperlabeladdressestogenerate": "生成するアドレス数", "papergenerate": "生成", "paperprint": "印刷", "paperlabelBIPpassphrase": "パスワード", "paperlabelencrypt": "BIP38で暗号化?", // bulk wallet html "bulklabelstartindex": "開始番号", "bulklabelrowstogenerate": "生成する行数", "bulklabelcompressed": "アドレスを短縮?", "bulkgenerate": "生成", "bulkprint": "印刷", "bulklabelcsv": "カンマ区切り値", "bulklabelformat": "番号、アドレス、プライベートキー(WIF形式)", "bulklabelq1": "ウェブサイトでMillenniumClubを受け付ける時、何故大量のアドレスを生成しておいた方がいいのか?", "bulka1": "以前はMillenniumClubをサイトで受け付けたかったら、「millenniumclubd」というMillenniumClubのシステムサービスをサーバーにアップロードし、サーバー上で実行しなければいけませんでした。しかし、このやり方だとサーバーがハッキングされてしまった場合、プライベートキーも全て持って行かれてしまいます。大量に生成しておいて、MillenniumClubアドレスだけをサーバーにアップしておけば、プライベートキーを安全な場所に保管できます。", "bulklabelq2": "どうやって大量生成を使ってサイトでMillenniumClubを受け付けられるようにできるのか?", "bulklabela2li1": "大量生成タブで大量のMillenniumClubを生成(10,000+でも可)。出てくるCSVテキストをコピーして、安全なテキストエディターで貼り付けて、安全な場所に保存しておいて下さい。一つバックアップを取り、別の場所で保管しておく(強いパスワードのかかったzipなどで)", "bulklabela2li2": "MillenniumClubアドレスをウェブサーバーにアップロード。プライベートキーはアップロードしないで下さい。ユーザーに見せたい宛先用のアドレスのみをアップロードして下さい。", "bulklabela2li3": "サイトのショッピングカート機能にMillenniumClubのリンクを追加して下さい。クリックされた時、お値段と先ほどアップしたMillenniumClubアドレスが順番に出てくるようにしておいて下さい(1取引1アドレス)。注文の情報と一緒に、このアドレスも一緒に保存して、後で紐付けられるようにしておいて下さい。", "bulklabela2li4": "接下来你需要一个收款通知,联系相关服务的供应商(谷歌搜索“MillenniumClub payment notification”),它们可以监视指定地址的资金变动,并通过WebAPI、短信、电邮或者其他方式来提醒你,你也可以通过编程使一切自动化。在http://explorer.millenniumclub.ca/address/地址 或者 查看交易确认。通常情况下,你能够在30秒之内看见交易,而根据你对安全的要求不同,你可能需要10分钟到1小时的时间等待交易确认。", "bulklabela2li5": "送られたMillenniumClubはブロックチェーンにて安全に保管されます。送金するには1番で作成したウォレットを何らかのMillenniumClubソフトに取り込んでご利用下さい。", // brain wallet html "brainlabelenterpassphrase": "パスワード", "brainlabelshow": "表示", "brainprint": "印刷", "brainlabelconfirm": "パスワードをもう一度", "brainview": "アドレスを見せる", "brainalgorithm": "アルゴリズム SHA256 (パスワード)", "brainlabelbitcoinaddress": "MillenniumClubアドレス", "brainlabelprivatekey": "プライベートキー(WIF形式)", // vanity wallet html "vanitylabelstep1": "ステップ1「ステップ1キーペア」を生成", "vanitynewkeypair": "生成", "vanitylabelstep1publickey": "ステップ1パブリックキー", "vanitylabelstep1pubnotes": "上記のものをカスタムアドレス生成業者の注文フォームに貼り付けて下さい。", "vanitylabelstep1privatekey": "ステップ1プライベートキー", "vanitylabelstep1privnotes": "上記のものを安全なテキストファイルに貼り付け、大事に保管しておいて下さい。パスワードで暗号化することをオススメします。カスタムアドレス生成業者からアドレスプレフィックスをもらった時にこれが必要となります。", "vanitylabelstep2calculateyourvanitywallet": "ステップ2カスタムアドレスを計算", "vanitylabelenteryourpart": "ステップ1で保存したプライベートキーを入力", "vanitylabelenteryourpoolpart": "カスタムアドレス生成業者からもらったプライベートキーを入力", "vanitylabelnote1": "[メモ: この欄はパブリックキーでもプライベートキーでも可能です。]", "vanitylabelnote2": "[メモ: この欄はパブリックキーでもプライベートキーでも可能です。]", "vanitylabelradioadd": "足し算", "vanitylabelradiomultiply": "掛け算", "vanitycalc": "カスタムアドレスを計算", "vanitylabelbitcoinaddress": "カスタムMillenniumClubアドレス", "vanitylabelnotesbitcoinaddress": "ご希望された頭文字を持ったアドレスになっています。", "vanitylabelpublickeyhex": "カスタムパブリックキー(HEX)", "vanitylabelnotespublickeyhex": "パブリックキーを16進で表したものです。", "vanitylabelprivatekey": "カスタムプライベートキー(WIF形式)", "vanitylabelnotesprivatekey": "上記のアドレスに送られたMillenniumClubを使うためのプライベートキーです。", // split wallet html "splitwallet": "分散ウォレット", "splitlabelthreshold": "復元に必要なシェア数", "splitlabelshares": "全シェア数", "splitview": "生成", "combinelabelentershares": "お持ちのシェアを入力 (空白区切り)", "combineview": "シェア合わせて復元", "combinelabelprivatekey": "復元された秘密鍵", // detail wallet html "detaillabelenterprivatekey": "プライベートキーを入力", "detailkeyformats": "受け付けるキーの形式 WIF, WIFC, HEX, B64, B6, MINI, BIP38", "detailview": "詳細を表示", "detailprint": "印刷", "detaillabelnote1": "MillenniumClubプライベートキーはあなたにしか分からない秘密の鍵。色々な形式で表示することができ、下記で表示しているのはMillenniumClubアドレス、パブリックキー、プライベートキー、そして複数の形式でプライベートキーを表示します。(WIF, WIFC, HEX, B64)", "detaillabelnote2": "MillenniumClub v0.6より圧縮したパブリックキーを保存している。なお、importprivkey / dumpprivkeyのコマンドを用いてプライベートキーのインポートとエクスポートもできる。エクスポートされるプライベートキーの形式はウォレットの作成時期とバージョンによって異なってくる。", "detaillabelbitcoinaddress": "MillenniumClubアドレス", "detaillabelbitcoinaddresscomp": "MillenniumClubアドレス(圧縮)", "detaillabelpublickey": "パブリックキー (130文字[0-9A-F])", "detaillabelpublickeycomp": "パブリックキー (圧縮、66文字[0-9A-F])", "detaillabelprivwif": "プライベートキー (WIF)<br>(base58コード51文字) 頭文字が", "detaillabelprivwifcomp": "プライベートキー (WIF)<br>(圧縮、base58コード52文字) 頭文字が", "detaillabelprivhex": "プライベートキー(16進) (64文字[0-9A-F])", "detaillabelprivb64": "プライベートキー(base64コード) (44文字)", "detaillabelpassphrase": "BIP38パスワード", "detailbip38decryptbutton": "BIP38暗号を解除", "detailbip38encryptbutton": "Encrypt BIP38", //TODO: please translate "detaillabelq1": "サイコロを使ってどうやってアドレス作るのか?「B6」とは何か?", "detaila1": "MillenniumClubのアドレスの生成には一番大事なことが、アドレス生成に使われている乱数が本当にランダムなのかというところです。自然界に起きる物理的なランダムさはパソコンが生成する(似非)ランダムさよりは優れている。物理的なランダムさを作る一番簡単な方法はサイコロを振ることです。MillenniumClubのプライベートキーを生成するには、6面のサイコロを99回振って、毎回結果を記載していきます。規則として1⇒1, 2⇒2, 3⇒3, 4⇒4, 5⇒5, 6⇒0というように、6が出る度に「0」と記載して下さい。99桁の6進数字列ができたら、上記の入力欄に入れて、「詳細を表示」ボタンを押して下さい。これでWIF形式のプライベートキーやそれと紐づくMillenniumClubアドレスが表示されます。これらを記載し、通常生成されたMillenniumClubアドレスと同じように保管しておいて下さい。", }; })(ninja.translator);
// single wallet html "newaddress": "新アドレス生成",
modules-routing.module.ts
import { NgModule } from '@angular/core'; import { RouterModule, Routes } from '@angular/router'; import { ChannelComponent } from './modules-detail/channels/channel.component'; import { ChannelsListComponent } from './modules-detail/channels/channels-list/channels-list.component'; import { ChatBotCreateComponent } from './modules-detail/channels/chat-bots/chat-bot-create/chat-bot-create.component'; import { ChatBotGettingStartedComponent } from './modules-detail/channels/chat-bots/chat-bot-getting-started/chat-bot-getting-started.component'; import { ChatBotsDetailComponent } from './modules-detail/channels/chat-bots/chat-bots-detail/chat-bots-detail.component'; import { ChatBotsMasterComponent } from './modules-detail/channels/chat-bots/chat-bots-master/chat-bots-master.component'; import { ChatChannelsMasterComponent } from './modules-detail/channels/chat-widgets/chat-channels-master/chat-channels-master.component'; import { ChatGettingStartedComponent } from './modules-detail/channels/chat-widgets/chat-getting-started/chat-getting-started.component'; import { ChatPromptMasterComponent } from './modules-detail/channels/chat-widgets/chat-prompt-master/chat-prompt-master.component'; import { EmailDetailComponent } from './modules-detail/channels/email-detail/email-detail.component'; import { FacebookDetailComponent } from './modules-detail/channels/facebook-detail/facebook-detail.component'; import { FieldCreatorComponent } from './modules-detail/fields/field-creator/field-creator.component'; import { FieldMasterComponent } from './modules-detail/fields/field-master/field-master.component'; import { FieldViewComponent } from './modules-detail/fields/field-view/field-view.component'; import { FormsDetailComponent } from './modules-detail/forms/forms-detail/forms-detail.component'; import { FormsMasterComponent } from './modules-detail/forms/forms-master/forms-master.component'; import { DetailLayoutComponent } from './modules-detail/layouts/detail-layout/detail-layout.component'; import { LayoutsMasterComponent } from './modules-detail/layouts/layouts-master/layouts-master.component'; import { LayoutsComponent } from './modules-detail/layouts/layouts.component'; import { ListLayoutComponent } from './modules-detail/layouts/list-layout/list-layout.component'; import { MobileDetailLayoutComponent } from './modules-detail/layouts/mobile-detail-layout/mobile-detail-layout.component'; import { MobileListLayoutComponent } from './modules-detail/layouts/mobile-list-layout/mobile-list-layout.component'; import { ModulesDetailComponent } from './modules-detail/modules-detail.component'; import { SlaDetailComponent } from './modules-detail/slas/sla-detail/sla-detail.component'; import { SlaMasterComponent } from './modules-detail/slas/sla-master/sla-master.component'; import { PdfDetailComponent } from './modules-detail/pdf/pdf-detail/pdf-detail.component'; import { PdfMasterComponent } from './modules-detail/pdf/pdf-master/pdf-master.component'; import { TriggersDetailComponent } from './modules-detail/triggers/triggers-detail/triggers-detail.component'; import { TriggersMasterComponent } from './modules-detail/triggers/triggers-master/triggers-master.component'; import { ValidationsDetailComponent } from './modules-detail/validations/validations-detail/validations-detail.component'; import { ValidationsMasterComponent } from './modules-detail/validations/validations-master/validations-master.component'; import { ModulesMasterComponent } from './modules-master/modules-master.component'; import { TriggersDetailNewComponent } from './modules-detail/triggers/triggers-detail-new/triggers-detail-new.component'; import { WorkflowCreateComponent } from './modules-detail/triggers/workflow-create/workflow-create.component'; import { TaskMasterComponent } from './modules-detail/task/task-master/task-master.component'; import { TaskDetailComponent } from './modules-detail/task/task-detail/task-detail.component'; import { FormsComponent } from './modules-detail/forms/forms.component'; import { ServiceCatalogueComponent } from './modules-detail/forms/service-catalogue/service-catalogue.component'; import { ServiceCatalogueDetailComponent } from './modules-detail/forms/service-catalogue-detail/service-catalogue-detail.component'; const routes: Routes = [ { path: '', component: ModulesMasterComponent }, { path: ':moduleId', component: ModulesDetailComponent }, { path: ':moduleId/chatbots', component: ChatBotCreateComponent, }, { path: ':moduleId/chatbots/create', component: ChatBotGettingStartedComponent, }, { path: ':moduleId/chatbots/templates', component: ChatBotsMasterComponent, }, { path: ':moduleId/fields', component: FieldMasterComponent }, { path: ':moduleId/field/field-creator/:dataType', component: FieldCreatorComponent, }, { path: ':moduleId/field/field-creator', component: FieldCreatorComponent }, { path: ':moduleId/field/:fieldId', component: FieldViewComponent }, { path: ':moduleId/channels', component: ChannelComponent }, { path: ':moduleId/layouts', component: LayoutsComponent }, { path: ':moduleId/workflows', component: TriggersMasterComponent }, { path: ':moduleId/slas', component: SlaMasterComponent }, { path: ':moduleId/pdf', component: PdfMasterComponent }, { path: ':moduleId/validations', component: ValidationsMasterComponent }, { path: ':moduleId/forms', component: FormsComponent }, { path: ':moduleId/forms/external', component: FormsMasterComponent }, { path: ':moduleId/service-catalogue', component: ServiceCatalogueComponent }, { path: ':moduleId/service-catalogue/:serviceCatalogueId', component: ServiceCatalogueDetailComponent, }, { path: ':moduleId/forms/:formId', component: FormsDetailComponent }, { path: ':moduleId/task', component: TaskMasterComponent }, { path: ':moduleId/task/:taskId', component: TaskDetailComponent }, { path: ':moduleId/:layoutType', component: LayoutsMasterComponent }, { path: ':moduleId/workflows/create-new', component: WorkflowCreateComponent, }, { path: ':moduleId/workflows/:moduleWorkflowId', component: TriggersDetailNewComponent, }, { path: ':moduleId/:layoutType/mobile', component: LayoutsMasterComponent, }, { path: ':moduleId/list_layouts/:listLayoutId', component: ListLayoutComponent, }, { path: ':moduleId/list_mobile_layouts/:listMobileLayoutId', component: MobileListLayoutComponent, }, { path: ':moduleId/slas/:slaId', component: SlaDetailComponent }, { path: ':moduleId/pdf/:pdfId', component: PdfDetailComponent }, { path: ':moduleId/validations/:validationId', component: ValidationsDetailComponent, }, { path: `:moduleId/channels/chat-widgets/:chatName/prompt/:promptId`, component: ChatPromptMasterComponent, }, { path: ':moduleId/chatbots/:chatBotId', component: ChatBotsDetailComponent, }, { path: ':moduleId/channels/chat-widgets/:chatName', component: ChatGettingStartedComponent, }, { path: ':moduleId/channels/facebook/facebook-detail', component: FacebookDetailComponent, }, { path: ':moduleId/channels/chat-widgets', component: ChatChannelsMasterComponent, }, { path: ':moduleId/channels/:channelType', component: ChannelsListComponent, }, { path: ':moduleId/edit_mobile_layouts/:mobileLayoutId', component: MobileDetailLayoutComponent, }, { path: ':moduleId/create_mobile_layouts/:mobileLayoutId', component: MobileDetailLayoutComponent, }, { path: ':moduleId/detail_mobile_layouts/:mobileLayoutId', component: MobileDetailLayoutComponent, }, { path: ':moduleId/:layoutType/:layoutId', component: DetailLayoutComponent }, { path: ':moduleId/channels/email/:emailId', component: EmailDetailComponent, }, ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule], }) export class
{}
ModulesRoutingModule
mod.rs
// Copyright 2016 Joe Wilm, The Alacritty Project Contributors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::collections::HashMap; use std::fs::File; use std::hash::BuildHasherDefault; use std::io::{self, Read}; use std::mem::size_of; use std::path::PathBuf; use std::ptr; use std::sync::mpsc; use std::time::Duration; use cgmath; use fnv::FnvHasher; use glutin::dpi::PhysicalSize; use font::{self, FontDesc, FontKey, GlyphKey, Rasterize, RasterizedGlyph, Rasterizer}; use notify::{watcher, DebouncedEvent, RecursiveMode, Watcher}; use crate::gl::types::*; use crate::gl; use crate::index::{Column, Line, RangeInclusive}; use crate::Rgb; use crate::config::{self, Config, Delta}; use crate::term::{self, cell, RenderableCell}; use crate::renderer::lines::Lines; pub mod lines; // Shader paths for live reload static TEXT_SHADER_F_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/res/text.f.glsl"); static TEXT_SHADER_V_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/res/text.v.glsl"); static RECT_SHADER_F_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/res/rect.f.glsl"); static RECT_SHADER_V_PATH: &'static str = concat!(env!("CARGO_MANIFEST_DIR"), "/res/rect.v.glsl"); // Shader source which is used when live-shader-reload feature is disable static TEXT_SHADER_F: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/res/text.f.glsl")); static TEXT_SHADER_V: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/res/text.v.glsl")); static RECT_SHADER_F: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/res/rect.f.glsl")); static RECT_SHADER_V: &'static str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"), "/res/rect.v.glsl")); /// `LoadGlyph` allows for copying a rasterized glyph into graphics memory pub trait LoadGlyph { /// Load the rasterized glyph into GPU memory fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph; /// Clear any state accumulated from previous loaded glyphs /// /// This can, for instance, be used to reset the texture Atlas. fn clear(&mut self); } enum Msg { ShaderReload, } #[derive(Debug)] pub enum Error { ShaderCreation(ShaderCreationError), } impl ::std::error::Error for Error { fn cause(&self) -> Option<&dyn (::std::error::Error)> { match *self { Error::ShaderCreation(ref err) => Some(err), } } fn description(&self) -> &str { match *self { Error::ShaderCreation(ref err) => err.description(), } } } impl ::std::fmt::Display for Error { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { Error::ShaderCreation(ref err) => { write!(f, "There was an error initializing the shaders: {}", err) } } } } impl From<ShaderCreationError> for Error { fn from(val: ShaderCreationError) -> Error { Error::ShaderCreation(val) } } /// Text drawing program /// /// Uniforms are prefixed with "u", and vertex attributes are prefixed with "a". #[derive(Debug)] pub struct TextShaderProgram { // Program id id: GLuint, /// projection matrix uniform u_projection: GLint, /// Terminal dimensions (pixels) u_term_dim: GLint, /// Cell dimensions (pixels) u_cell_dim: GLint, /// Background pass flag /// /// Rendering is split into two passes; 1 for backgrounds, and one for text u_background: GLint, } /// Rectangle drawing program /// /// Uniforms are prefixed with "u" #[derive(Debug)] pub struct RectShaderProgram { // Program id id: GLuint, /// Rectangle color u_col: GLint, } #[derive(Copy, Debug, Clone)] pub struct Glyph { tex_id: GLuint, top: f32, left: f32, width: f32, height: f32, uv_bot: f32, uv_left: f32, uv_width: f32, uv_height: f32, } /// Naïve glyph cache /// /// Currently only keyed by `char`, and thus not possible to hold different /// representations of the same code point. pub struct GlyphCache { /// Cache of buffered glyphs cache: HashMap<GlyphKey, Glyph, BuildHasherDefault<FnvHasher>>, /// Rasterizer for loading new glyphs rasterizer: Rasterizer, /// regular font font_key: FontKey, /// italic font italic_key: FontKey, /// bold font bold_key: FontKey, /// font size font_size: font::Size, /// glyph offset glyph_offset: Delta<i8>, metrics: ::font::Metrics, } impl GlyphCache { pub fn new<L>( mut rasterizer: Rasterizer, font: &config::Font, loader: &mut L, ) -> Result<GlyphCache, font::Error> where L: LoadGlyph, { let (regular, bold, italic) = Self::compute_font_keys(font, &mut rasterizer)?; // Need to load at least one glyph for the face before calling metrics. // The glyph requested here ('m' at the time of writing) has no special // meaning. rasterizer.get_glyph(GlyphKey { font_key: regular, c: 'm', size: font.size() })?; let metrics = rasterizer.metrics(regular, font.size())?; let mut cache = GlyphCache { cache: HashMap::default(), rasterizer, font_size: font.size(), font_key: regular, bold_key: bold, italic_key: italic, glyph_offset: *font.glyph_offset(), metrics, }; cache.load_glyphs_for_font(regular, loader); cache.load_glyphs_for_font(bold, loader); cache.load_glyphs_for_font(italic, loader); Ok(cache) } fn load_glyphs_for_font<L: LoadGlyph>(&mut self, font: FontKey, loader: &mut L) { let size = self.font_size; for i in RangeInclusive::new(32u8, 128u8) { self.get(GlyphKey { font_key: font, c: i as char, size, }, loader); } } /// Computes font keys for (Regular, Bold, Italic) fn compute_font_keys( font: &config::Font, rasterizer: &mut Rasterizer, ) -> Result<(FontKey, FontKey, FontKey), font::Error> { let size = font.size(); // Load regular font let regular_desc = Self::make_desc(&font.normal(), font::Slant::Normal, font::Weight::Normal); let regular = rasterizer.load_font(&regular_desc, size)?; // helper to load a description if it is not the regular_desc let mut load_or_regular = |desc: FontDesc| { if desc == regular_desc { regular } else { rasterizer .load_font(&desc, size) .unwrap_or_else(|_| regular) } }; // Load bold font let bold_desc = Self::make_desc(&font.bold(), font::Slant::Normal, font::Weight::Bold); let bold = load_or_regular(bold_desc); // Load italic font let italic_desc = Self::make_desc(&font.italic(), font::Slant::Italic, font::Weight::Normal); let italic = load_or_regular(italic_desc); Ok((regular, bold, italic)) } fn make_desc( desc: &config::FontDescription, slant: font::Slant, weight: font::Weight, ) -> FontDesc { let style = if let Some(ref spec) = desc.style { font::Style::Specific(spec.to_owned()) } else { font::Style::Description { slant, weight } }; FontDesc::new(desc.family.clone(), style) } pub fn font_metrics(&self) -> font::Metrics { self.rasterizer .metrics(self.font_key, self.font_size) .expect("metrics load since font is loaded at glyph cache creation") } pub fn get<'a, L>(&'a mut self, glyph_key: GlyphKey, loader: &mut L) -> &'a Glyph where L: LoadGlyph { let glyph_offset = self.glyph_offset; let rasterizer = &mut self.rasterizer; let metrics = &self.metrics; self.cache .entry(glyph_key) .or_insert_with(|| { let mut rasterized = rasterizer.get_glyph(glyph_key) .unwrap_or_else(|_| Default::default()); rasterized.left += i32::from(glyph_offset.x); rasterized.top += i32::from(glyph_offset.y); rasterized.top -= metrics.descent as i32; loader.load_glyph(&rasterized) }) } pub fn update_font_size<L: LoadGlyph>( &mut self, font: &config::Font, size: font::Size, dpr: f64, loader: &mut L ) -> Result<(), font::Error> { // Clear currently cached data in both GL and the registry loader.clear(); self.cache = HashMap::default(); // Update dpi scaling self.rasterizer.update_dpr(dpr as f32); // Recompute font keys let font = font.to_owned().with_size(size); let (regular, bold, italic) = Self::compute_font_keys(&font, &mut self.rasterizer)?; self.rasterizer.get_glyph(GlyphKey { font_key: regular, c: 'm', size: font.size() })?; let metrics = self.rasterizer.metrics(regular, size)?; info!("Font size changed to {:?} with DPR of {}", font.size, dpr); self.font_size = font.size; self.font_key = regular; self.bold_key = bold; self.italic_key = italic; self.metrics = metrics; self.load_glyphs_for_font(regular, loader); self.load_glyphs_for_font(bold, loader); self.load_glyphs_for_font(italic, loader); Ok(()) } } #[derive(Debug)] #[repr(C)] struct InstanceData { // coords col: f32, row: f32, // glyph offset left: f32, top: f32, // glyph scale width: f32, height: f32, // uv offset uv_left: f32, uv_bot: f32, // uv scale uv_width: f32, uv_height: f32, // color r: f32, g: f32, b: f32, // background color bg_r: f32, bg_g: f32, bg_b: f32, bg_a: f32, } #[derive(Debug)] pub struct QuadRenderer { program: TextShaderProgram, rect_program: RectShaderProgram, vao: GLuint, ebo: GLuint, vbo_instance: GLuint, rect_vao: GLuint, rect_vbo: GLuint, atlas: Vec<Atlas>, current_atlas: usize, active_tex: GLuint, batch: Batch, rx: mpsc::Receiver<Msg>, } #[derive(Debug)] pub struct RenderApi<'a> { active_tex: &'a mut GLuint, batch: &'a mut Batch, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, program: &'a mut TextShaderProgram, config: &'a Config, } #[derive(Debug)] pub struct LoaderApi<'a> { active_tex: &'a mut GLuint, atlas: &'a mut Vec<Atlas>, current_atlas: &'a mut usize, } #[derive(Debug)] pub struct PackedVertex { x: f32, y: f32, } #[derive(Debug, Default)] pub struct Batch { tex: GLuint, instances: Vec<InstanceData>, } impl Batch { #[inline] pub fn new() -> Batch { Batch { tex: 0, instances: Vec::with_capacity(BATCH_MAX), } } pub fn add_item(&mut self, cell: &RenderableCell, glyph: &Glyph) { if self.is_empty() { self.tex = glyph.tex_id; } self.instances.push(InstanceData { col: cell.column.0 as f32, row: cell.line.0 as f32, top: glyph.top, left: glyph.left, width: glyph.width, height: glyph.height, uv_bot: glyph.uv_bot, uv_left: glyph.uv_left, uv_width: glyph.uv_width, uv_height: glyph.uv_height, r: f32::from(cell.fg.r), g: f32::from(cell.fg.g), b: f32::from(cell.fg.b), bg_r: f32::from(cell.bg.r), bg_g: f32::from(cell.bg.g), bg_b: f32::from(cell.bg.b), bg_a: cell.bg_alpha, }); } #[inline] pub fn full(&self) -> bool { self.capacity() == self.len() } #[inline] pub fn len(&self) -> usize { self.instances.len() } #[inline] pub fn capacity(&self) -> usize { BATCH_MAX } #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } #[inline] pub fn size(&self) -> usize { self.len() * size_of::<InstanceData>() } pub fn clear(&mut self) { self.tex = 0; self.instances.clear(); } } /// Maximum items to be drawn in a batch. const BATCH_MAX: usize = 0x1_0000; const ATLAS_SIZE: i32 = 1024; impl QuadRenderer { // TODO should probably hand this a transform instead of width/height pub fn n
size: PhysicalSize) -> Result<QuadRenderer, Error> { let program = TextShaderProgram::new(size)?; let rect_program = RectShaderProgram::new()?; let mut vao: GLuint = 0; let mut vbo: GLuint = 0; let mut ebo: GLuint = 0; let mut vbo_instance: GLuint = 0; let mut rect_vao: GLuint = 0; let mut rect_vbo: GLuint = 0; let mut rect_ebo: GLuint = 0; unsafe { gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); gl::Enable(gl::MULTISAMPLE); gl::GenVertexArrays(1, &mut vao); gl::GenBuffers(1, &mut vbo); gl::GenBuffers(1, &mut ebo); gl::GenBuffers(1, &mut vbo_instance); gl::BindVertexArray(vao); // ---------------------------- // setup vertex position buffer // ---------------------------- // Top right, Bottom right, Bottom left, Top left let vertices = [ PackedVertex { x: 1.0, y: 1.0 }, PackedVertex { x: 1.0, y: 0.0 }, PackedVertex { x: 0.0, y: 0.0 }, PackedVertex { x: 0.0, y: 1.0 }, ]; gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::VertexAttribPointer( 0, 2, gl::FLOAT, gl::FALSE, size_of::<PackedVertex>() as i32, ptr::null(), ); gl::EnableVertexAttribArray(0); gl::BufferData( gl::ARRAY_BUFFER, (size_of::<PackedVertex>() * vertices.len()) as GLsizeiptr, vertices.as_ptr() as *const _, gl::STATIC_DRAW, ); // --------------------- // Set up element buffer // --------------------- let indices: [u32; 6] = [0, 1, 3, 1, 2, 3]; gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (6 * size_of::<u32>()) as isize, indices.as_ptr() as *const _, gl::STATIC_DRAW, ); // ---------------------------- // Setup vertex instance buffer // ---------------------------- gl::BindBuffer(gl::ARRAY_BUFFER, vbo_instance); gl::BufferData( gl::ARRAY_BUFFER, (BATCH_MAX * size_of::<InstanceData>()) as isize, ptr::null(), gl::STREAM_DRAW, ); // coords gl::VertexAttribPointer( 1, 2, gl::FLOAT, gl::FALSE, size_of::<InstanceData>() as i32, ptr::null(), ); gl::EnableVertexAttribArray(1); gl::VertexAttribDivisor(1, 1); // glyphoffset gl::VertexAttribPointer( 2, 4, gl::FLOAT, gl::FALSE, size_of::<InstanceData>() as i32, (2 * size_of::<f32>()) as *const _, ); gl::EnableVertexAttribArray(2); gl::VertexAttribDivisor(2, 1); // uv gl::VertexAttribPointer( 3, 4, gl::FLOAT, gl::FALSE, size_of::<InstanceData>() as i32, (6 * size_of::<f32>()) as *const _, ); gl::EnableVertexAttribArray(3); gl::VertexAttribDivisor(3, 1); // color gl::VertexAttribPointer( 4, 3, gl::FLOAT, gl::FALSE, size_of::<InstanceData>() as i32, (10 * size_of::<f32>()) as *const _, ); gl::EnableVertexAttribArray(4); gl::VertexAttribDivisor(4, 1); // color gl::VertexAttribPointer( 5, 4, gl::FLOAT, gl::FALSE, size_of::<InstanceData>() as i32, (13 * size_of::<f32>()) as *const _, ); gl::EnableVertexAttribArray(5); gl::VertexAttribDivisor(5, 1); // Rectangle setup gl::GenVertexArrays(1, &mut rect_vao); gl::GenBuffers(1, &mut rect_vbo); gl::GenBuffers(1, &mut rect_ebo); gl::BindVertexArray(rect_vao); let indices: [i32; 6] = [ 0, 1, 3, 1, 2, 3, ]; gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, rect_ebo); gl::BufferData( gl::ELEMENT_ARRAY_BUFFER, (size_of::<i32>() * indices.len()) as _, indices.as_ptr() as *const _, gl::STATIC_DRAW ); // Cleanup gl::BindVertexArray(0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); } let (msg_tx, msg_rx) = mpsc::channel(); if cfg!(feature = "live-shader-reload") { ::std::thread::spawn(move || { let (tx, rx) = ::std::sync::mpsc::channel(); // The Duration argument is a debouncing period. let mut watcher = watcher(tx, Duration::from_millis(10)).expect("create file watcher"); watcher .watch(TEXT_SHADER_F_PATH, RecursiveMode::NonRecursive) .expect("watch fragment shader"); watcher .watch(TEXT_SHADER_V_PATH, RecursiveMode::NonRecursive) .expect("watch vertex shader"); loop { let event = rx.recv().expect("watcher event"); match event { DebouncedEvent::Rename(_, _) => continue, DebouncedEvent::Create(_) | DebouncedEvent::Write(_) | DebouncedEvent::Chmod(_) => { msg_tx.send(Msg::ShaderReload).expect("msg send ok"); } _ => {} } } }); } let mut renderer = QuadRenderer { program, rect_program, vao, ebo, vbo_instance, rect_vao, rect_vbo, atlas: Vec::new(), current_atlas: 0, active_tex: 0, batch: Batch::new(), rx: msg_rx, }; let atlas = Atlas::new(ATLAS_SIZE); renderer.atlas.push(atlas); Ok(renderer) } // Draw all rectangles simultaneously to prevent excessive program swaps pub fn draw_rects( &mut self, config: &Config, props: &term::SizeInfo, visual_bell_intensity: f64, cell_line_rects: Lines, ) { // Swap to rectangle rendering program unsafe { // Swap program gl::UseProgram(self.rect_program.id); // Remove padding from viewport gl::Viewport(0, 0, props.width as i32, props.height as i32); // Change blending strategy gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); // Setup data and buffers gl::BindVertexArray(self.rect_vao); gl::BindBuffer(gl::ARRAY_BUFFER, self.rect_vbo); // Position gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, (size_of::<f32>() * 3) as _, ptr::null()); gl::EnableVertexAttribArray(0); } // Draw visual bell let color = config.visual_bell().color(); let rect = Rect::new(0., 0., props.width, props.height); self.render_rect(&rect, color, visual_bell_intensity as f32, props); // Draw underlines and strikeouts for cell_line_rect in cell_line_rects.rects() { self.render_rect(&cell_line_rect.0, cell_line_rect.1, 255., props); } // Deactivate rectangle program again unsafe { // Reset blending strategy gl::BlendFunc(gl::SRC1_COLOR, gl::ONE_MINUS_SRC1_COLOR); // Reset data and buffers gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); let padding_x = props.padding_x as i32; let padding_y = props.padding_y as i32; let width = props.width as i32; let height = props.height as i32; gl::Viewport(padding_x, padding_y, width - 2 * padding_x, height - 2 * padding_y); // Disable program gl::UseProgram(0); } } pub fn with_api<F, T>( &mut self, config: &Config, props: &term::SizeInfo, func: F, ) -> T where F: FnOnce(RenderApi<'_>) -> T, { // Flush message queue if let Ok(Msg::ShaderReload) = self.rx.try_recv() { let size = PhysicalSize::new(f64::from(props.width), f64::from(props.height)); self.reload_shaders(size); } while let Ok(_) = self.rx.try_recv() {} unsafe { gl::UseProgram(self.program.id); self.program.set_term_uniforms(props); gl::BindVertexArray(self.vao); gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, self.ebo); gl::BindBuffer(gl::ARRAY_BUFFER, self.vbo_instance); gl::ActiveTexture(gl::TEXTURE0); } let res = func(RenderApi { active_tex: &mut self.active_tex, batch: &mut self.batch, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, program: &mut self.program, config, }); unsafe { gl::BindBuffer(gl::ELEMENT_ARRAY_BUFFER, 0); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); gl::UseProgram(0); } res } pub fn with_loader<F, T>(&mut self, func: F) -> T where F: FnOnce(LoaderApi<'_>) -> T, { unsafe { gl::ActiveTexture(gl::TEXTURE0); } func(LoaderApi { active_tex: &mut self.active_tex, atlas: &mut self.atlas, current_atlas: &mut self.current_atlas, }) } pub fn reload_shaders(&mut self, size: PhysicalSize) { warn!("Reloading shaders..."); let result = (TextShaderProgram::new(size), RectShaderProgram::new()); let (program, rect_program) = match result { (Ok(program), Ok(rect_program)) => { info!("... successfully reloaded shaders"); (program, rect_program) } (Err(err), _) | (_, Err(err)) => { error!("{}", err); return; } }; self.active_tex = 0; self.program = program; self.rect_program = rect_program; } pub fn resize(&mut self, size: PhysicalSize, padding_x: f32, padding_y: f32) { let (width, height): (u32, u32) = size.into(); // viewport unsafe { let width = width as i32; let height = height as i32; let padding_x = padding_x as i32; let padding_y = padding_y as i32; gl::Viewport(padding_x, padding_y, width - 2 * padding_x, height - 2 * padding_y); // update projection gl::UseProgram(self.program.id); self.program.update_projection( width as f32, height as f32, padding_x as f32, padding_y as f32, ); gl::UseProgram(0); } } // Render a rectangle // // This requires the rectangle program to be activated fn render_rect(&mut self, rect: &Rect<f32>, color: Rgb, alpha: f32, size: &term::SizeInfo) { // Do nothing when alpha is fully transparent if alpha == 0. { return; } // Calculate rectangle position let center_x = size.width / 2.; let center_y = size.height / 2.; let x = (rect.x - center_x) / center_x; let y = -(rect.y - center_y) / center_y; let width = rect.width / center_x; let height = rect.height / center_y; unsafe { // Setup vertices let vertices: [f32; 12] = [ x + width, y , 0.0, x + width, y - height, 0.0, x , y - height, 0.0, x , y , 0.0, ]; // Load vertex data into array buffer gl::BufferData( gl::ARRAY_BUFFER, (size_of::<f32>() * vertices.len()) as _, vertices.as_ptr() as *const _, gl::STATIC_DRAW ); // Color self.rect_program.set_color(color, alpha); // Draw the rectangle gl::DrawElements(gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null()); } } } #[derive(Debug, Copy, Clone)] pub struct Rect<T> { x: T, y: T, width: T, height: T, } impl<T> Rect<T> { pub fn new(x: T, y: T, width: T, height: T) -> Self { Rect { x, y, width, height } } } impl<'a> RenderApi<'a> { pub fn clear(&self, color: Rgb) { let alpha = self.config.background_opacity().get(); unsafe { gl::ClearColor( (f32::from(color.r) / 255.0).min(1.0) * alpha, (f32::from(color.g) / 255.0).min(1.0) * alpha, (f32::from(color.b) / 255.0).min(1.0) * alpha, alpha, ); gl::Clear(gl::COLOR_BUFFER_BIT); } } fn render_batch(&mut self) { unsafe { gl::BufferSubData( gl::ARRAY_BUFFER, 0, self.batch.size() as isize, self.batch.instances.as_ptr() as *const _, ); } // Bind texture if necessary if *self.active_tex != self.batch.tex { unsafe { gl::BindTexture(gl::TEXTURE_2D, self.batch.tex); } *self.active_tex = self.batch.tex; } unsafe { self.program.set_background_pass(true); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); self.program.set_background_pass(false); gl::DrawElementsInstanced( gl::TRIANGLES, 6, gl::UNSIGNED_INT, ptr::null(), self.batch.len() as GLsizei, ); } self.batch.clear(); } /// Render a string in a variable location. Used for printing the render timer, warnings and /// errors. pub fn render_string( &mut self, string: &str, line: Line, glyph_cache: &mut GlyphCache, color: Rgb ) { let col = Column(0); let cells = string .chars() .enumerate() .map(|(i, c)| RenderableCell { line, column: col + i, chars: { let mut chars = [' '; cell::MAX_ZEROWIDTH_CHARS + 1]; chars[0] = c; chars }, bg: color, fg: Rgb { r: 0, g: 0, b: 0 }, flags: cell::Flags::empty(), bg_alpha: 1.0, }) .collect::<Vec<_>>(); for cell in cells { self.render_cell(cell, glyph_cache); } } #[inline] fn add_render_item(&mut self, cell: &RenderableCell, glyph: &Glyph) { // Flush batch if tex changing if !self.batch.is_empty() && self.batch.tex != glyph.tex_id { self.render_batch(); } self.batch.add_item(cell, glyph); // Render batch and clear if it's full if self.batch.full() { self.render_batch(); } } pub fn render_cell(&mut self, cell: RenderableCell, glyph_cache: &mut GlyphCache) { // Get font key for cell // FIXME this is super inefficient. let font_key = if cell.flags.contains(cell::Flags::BOLD) { glyph_cache.bold_key } else if cell.flags.contains(cell::Flags::ITALIC) { glyph_cache.italic_key } else { glyph_cache.font_key }; // Don't render text of HIDDEN cells let mut chars = if cell.flags.contains(cell::Flags::HIDDEN) { [' '; cell::MAX_ZEROWIDTH_CHARS + 1] } else { cell.chars }; // Render tabs as spaces in case the font doesn't support it if chars[0] == '\t' { chars[0] = ' '; } let mut glyph_key = GlyphKey { font_key, size: glyph_cache.font_size, c: chars[0], }; // Add cell to batch let glyph = glyph_cache.get(glyph_key, self); self.add_render_item(&cell, glyph); // Render zero-width characters for c in (&chars[1..]).iter().filter(|c| **c != ' ') { glyph_key.c = *c; let mut glyph = *glyph_cache.get(glyph_key, self); // The metrics of zero-width characters are based on rendering // the character after the current cell, with the anchor at the // right side of the preceding character. Since we render the // zero-width characters inside the preceding character, the // anchor has been moved to the right by one cell. glyph.left += glyph_cache.metrics.average_advance as f32; self.add_render_item(&cell, &glyph); } } } /// Load a glyph into a texture atlas /// /// If the current atlas is full, a new one will be created. #[inline] fn load_glyph( active_tex: &mut GLuint, atlas: &mut Vec<Atlas>, current_atlas: &mut usize, rasterized: &RasterizedGlyph ) -> Glyph { // At least one atlas is guaranteed to be in the `self.atlas` list; thus // the unwrap. match atlas[*current_atlas].insert(rasterized, active_tex) { Ok(glyph) => glyph, Err(AtlasInsertError::Full) => { *current_atlas += 1; if *current_atlas == atlas.len() { let new = Atlas::new(ATLAS_SIZE); *active_tex = 0; // Atlas::new binds a texture. Ugh this is sloppy. atlas.push(new); } load_glyph(active_tex, atlas, current_atlas, rasterized) } Err(AtlasInsertError::GlyphTooLarge) => { Glyph { tex_id: atlas[*current_atlas].id, top: 0.0, left: 0.0, width: 0.0, height: 0.0, uv_bot: 0.0, uv_left: 0.0, uv_width: 0.0, uv_height: 0.0, } } } } #[inline] fn clear_atlas(atlas: &mut Vec<Atlas>, current_atlas: &mut usize) { for atlas in atlas.iter_mut() { atlas.clear(); } *current_atlas = 0; } impl<'a> LoadGlyph for LoaderApi<'a> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { clear_atlas(self.atlas, self.current_atlas) } } impl<'a> LoadGlyph for RenderApi<'a> { fn load_glyph(&mut self, rasterized: &RasterizedGlyph) -> Glyph { load_glyph(self.active_tex, self.atlas, self.current_atlas, rasterized) } fn clear(&mut self) { clear_atlas(self.atlas, self.current_atlas) } } impl<'a> Drop for RenderApi<'a> { fn drop(&mut self) { if !self.batch.is_empty() { self.render_batch(); } } } impl TextShaderProgram { pub fn new(size: PhysicalSize) -> Result<TextShaderProgram, ShaderCreationError> { let (vertex_src, fragment_src) = if cfg!(feature = "live-shader-reload") { (None, None) } else { (Some(TEXT_SHADER_V), Some(TEXT_SHADER_F)) }; let vertex_shader = create_shader(TEXT_SHADER_V_PATH, gl::VERTEX_SHADER, vertex_src)?; let fragment_shader = create_shader(TEXT_SHADER_F_PATH, gl::FRAGMENT_SHADER, fragment_src)?; let program = create_program(vertex_shader, fragment_shader)?; unsafe { gl::DeleteShader(fragment_shader); gl::DeleteShader(vertex_shader); gl::UseProgram(program); } macro_rules! cptr { ($thing:expr) => { $thing.as_ptr() as *const _ } } macro_rules! assert_uniform_valid { ($uniform:expr) => { assert!($uniform != gl::INVALID_VALUE as i32); assert!($uniform != gl::INVALID_OPERATION as i32); }; ( $( $uniform:expr ),* ) => { $( assert_uniform_valid!($uniform); )* }; } // get uniform locations let (projection, term_dim, cell_dim, background) = unsafe { ( gl::GetUniformLocation(program, cptr!(b"projection\0")), gl::GetUniformLocation(program, cptr!(b"termDim\0")), gl::GetUniformLocation(program, cptr!(b"cellDim\0")), gl::GetUniformLocation(program, cptr!(b"backgroundPass\0")), ) }; assert_uniform_valid!(projection, term_dim, cell_dim); let shader = TextShaderProgram { id: program, u_projection: projection, u_term_dim: term_dim, u_cell_dim: cell_dim, u_background: background, }; shader.update_projection(size.width as f32, size.height as f32, 0., 0.); unsafe { gl::UseProgram(0); } Ok(shader) } fn update_projection(&self, width: f32, height: f32, padding_x: f32, padding_y: f32) { // Bounds check if (width as u32) < (2 * padding_x as u32) || (height as u32) < (2 * padding_y as u32) { return; } // set projection uniform // // NB Not sure why padding change only requires changing the vertical // translation in the projection, but this makes everything work // correctly. let ortho = cgmath::ortho( 0., width - (2. * padding_x), 2. * padding_y, height, -1., 1., ); let projection: [[f32; 4]; 4] = ortho.into(); info!("Width: {}, Height: {}", width, height); unsafe { gl::UniformMatrix4fv( self.u_projection, 1, gl::FALSE, projection.as_ptr() as *const _, ); } } fn set_term_uniforms(&self, props: &term::SizeInfo) { unsafe { gl::Uniform2f(self.u_term_dim, props.width, props.height); gl::Uniform2f(self.u_cell_dim, props.cell_width, props.cell_height); } } fn set_background_pass(&self, background_pass: bool) { let value = if background_pass { 1 } else { 0 }; unsafe { gl::Uniform1i(self.u_background, value); } } } impl Drop for TextShaderProgram { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.id); } } } impl RectShaderProgram { pub fn new() -> Result<Self, ShaderCreationError> { let (vertex_src, fragment_src) = if cfg!(feature = "live-shader-reload") { (None, None) } else { (Some(RECT_SHADER_V), Some(RECT_SHADER_F)) }; let vertex_shader = create_shader( RECT_SHADER_V_PATH, gl::VERTEX_SHADER, vertex_src )?; let fragment_shader = create_shader( RECT_SHADER_F_PATH, gl::FRAGMENT_SHADER, fragment_src )?; let program = create_program(vertex_shader, fragment_shader)?; unsafe { gl::DeleteShader(fragment_shader); gl::DeleteShader(vertex_shader); gl::UseProgram(program); } // get uniform locations let u_col = unsafe { gl::GetUniformLocation(program, b"col\0".as_ptr() as *const _) }; let shader = RectShaderProgram { id: program, u_col, }; unsafe { gl::UseProgram(0) } Ok(shader) } fn set_color(&self, color: Rgb, alpha: f32) { unsafe { gl::Uniform4f( self.u_col, f32::from(color.r) / 255., f32::from(color.g) / 255., f32::from(color.b) / 255., alpha, ); } } } impl Drop for RectShaderProgram { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.id); } } } fn create_program(vertex: GLuint, fragment: GLuint) -> Result<GLuint, ShaderCreationError> { unsafe { let program = gl::CreateProgram(); gl::AttachShader(program, vertex); gl::AttachShader(program, fragment); gl::LinkProgram(program); let mut success: GLint = 0; gl::GetProgramiv(program, gl::LINK_STATUS, &mut success); if success == i32::from(gl::TRUE) { Ok(program) } else { Err(ShaderCreationError::Link(get_program_info_log(program))) } } } fn create_shader(path: &str, kind: GLenum, source: Option<&'static str>) -> Result<GLuint, ShaderCreationError> { let from_disk; let source = if let Some(src) = source { src } else { from_disk = read_file(path)?; &from_disk[..] }; let len: [GLint; 1] = [source.len() as GLint]; let shader = unsafe { let shader = gl::CreateShader(kind); gl::ShaderSource(shader, 1, &(source.as_ptr() as *const _), len.as_ptr()); gl::CompileShader(shader); shader }; let mut success: GLint = 0; unsafe { gl::GetShaderiv(shader, gl::COMPILE_STATUS, &mut success); } if success == GLint::from(gl::TRUE) { Ok(shader) } else { // Read log let log = get_shader_info_log(shader); // Cleanup unsafe { gl::DeleteShader(shader); } Err(ShaderCreationError::Compile(PathBuf::from(path), log)) } } fn get_program_info_log(program: GLuint) -> String { // Get expected log length let mut max_length: GLint = 0; unsafe { gl::GetProgramiv(program, gl::INFO_LOG_LENGTH, &mut max_length); } // Read the info log let mut actual_length: GLint = 0; let mut buf: Vec<u8> = Vec::with_capacity(max_length as usize); unsafe { gl::GetProgramInfoLog( program, max_length, &mut actual_length, buf.as_mut_ptr() as *mut _, ); } // Build a string unsafe { buf.set_len(actual_length as usize); } // XXX should we expect opengl to return garbage? String::from_utf8(buf).unwrap() } fn get_shader_info_log(shader: GLuint) -> String { // Get expected log length let mut max_length: GLint = 0; unsafe { gl::GetShaderiv(shader, gl::INFO_LOG_LENGTH, &mut max_length); } // Read the info log let mut actual_length: GLint = 0; let mut buf: Vec<u8> = Vec::with_capacity(max_length as usize); unsafe { gl::GetShaderInfoLog( shader, max_length, &mut actual_length, buf.as_mut_ptr() as *mut _, ); } // Build a string unsafe { buf.set_len(actual_length as usize); } // XXX should we expect opengl to return garbage? String::from_utf8(buf).unwrap() } fn read_file(path: &str) -> Result<String, io::Error> { let mut f = File::open(path)?; let mut buf = String::new(); f.read_to_string(&mut buf)?; Ok(buf) } #[derive(Debug)] pub enum ShaderCreationError { /// Error reading file Io(io::Error), /// Error compiling shader Compile(PathBuf, String), /// Problem linking Link(String), } impl ::std::error::Error for ShaderCreationError { fn cause(&self) -> Option<&dyn (::std::error::Error)> { match *self { ShaderCreationError::Io(ref err) => Some(err), _ => None, } } fn description(&self) -> &str { match *self { ShaderCreationError::Io(ref err) => err.description(), ShaderCreationError::Compile(ref _path, ref s) => s.as_str(), ShaderCreationError::Link(ref s) => s.as_str(), } } } impl ::std::fmt::Display for ShaderCreationError { fn fmt(&self, f: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { match *self { ShaderCreationError::Io(ref err) => { write!(f, "Couldn't read shader: {}", err) }, ShaderCreationError::Compile(ref path, ref log) => { write!(f, "Failed compiling shader at {}: {}", path.display(), log) }, ShaderCreationError::Link(ref log) => { write!(f, "Failed linking shader: {}", log) }, } } } impl From<io::Error> for ShaderCreationError { fn from(val: io::Error) -> ShaderCreationError { ShaderCreationError::Io(val) } } /// Manages a single texture atlas /// /// The strategy for filling an atlas looks roughly like this: /// /// ```ignore /// (width, height) /// ┌─────┬─────┬─────┬─────┬─────┐ /// │ 10 │ │ │ │ │ <- Empty spaces; can be filled while /// │ │ │ │ │ │ glyph_height < height - row_baseline /// ├⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┤ /// │ 5 │ 6 │ 7 │ 8 │ 9 │ /// │ │ │ │ │ │ /// ├⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┼⎼⎼⎼⎼⎼┴⎼⎼⎼⎼⎼┤ <- Row height is tallest glyph in row; this is /// │ 1 │ 2 │ 3 │ 4 │ used as the baseline for the following row. /// │ │ │ │ │ <- Row considered full when next glyph doesn't /// └─────┴─────┴─────┴───────────┘ fit in the row. /// (0, 0) x-> /// ``` #[derive(Debug)] struct Atlas { /// Texture id for this atlas id: GLuint, /// Width of atlas width: i32, /// Height of atlas height: i32, /// Left-most free pixel in a row. /// /// This is called the extent because it is the upper bound of used pixels /// in a row. row_extent: i32, /// Baseline for glyphs in the current row row_baseline: i32, /// Tallest glyph in current row /// /// This is used as the advance when end of row is reached row_tallest: i32, } /// Error that can happen when inserting a texture to the Atlas enum AtlasInsertError { /// Texture atlas is full Full, /// The glyph cannot fit within a single texture GlyphTooLarge, } impl Atlas { fn new(size: i32) -> Atlas { let mut id: GLuint = 0; unsafe { gl::PixelStorei(gl::UNPACK_ALIGNMENT, 1); gl::GenTextures(1, &mut id); gl::BindTexture(gl::TEXTURE_2D, id); gl::TexImage2D( gl::TEXTURE_2D, 0, gl::RGB as i32, size, size, 0, gl::RGB, gl::UNSIGNED_BYTE, ptr::null(), ); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_S, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_WRAP_T, gl::CLAMP_TO_EDGE as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::LINEAR as i32); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::LINEAR as i32); gl::BindTexture(gl::TEXTURE_2D, 0); } Atlas { id, width: size, height: size, row_extent: 0, row_baseline: 0, row_tallest: 0, } } pub fn clear(&mut self) { self.row_extent = 0; self.row_baseline = 0; self.row_tallest = 0; } /// Insert a RasterizedGlyph into the texture atlas pub fn insert( &mut self, glyph: &RasterizedGlyph, active_tex: &mut u32 ) -> Result<Glyph, AtlasInsertError> { if glyph.width > self.width || glyph.height > self.height { return Err(AtlasInsertError::GlyphTooLarge); } // If there's not enough room in current row, go onto next one if !self.room_in_row(glyph) { self.advance_row()?; } // If there's still not room, there's nothing that can be done here. if !self.room_in_row(glyph) { return Err(AtlasInsertError::Full); } // There appears to be room; load the glyph. Ok(self.insert_inner(glyph, active_tex)) } /// Insert the glyph without checking for room /// /// Internal function for use once atlas has been checked for space. GL /// errors could still occur at this point if we were checking for them; /// hence, the Result. fn insert_inner(&mut self, glyph: &RasterizedGlyph, active_tex: &mut u32) -> Glyph { let offset_y = self.row_baseline; let offset_x = self.row_extent; let height = glyph.height as i32; let width = glyph.width as i32; unsafe { gl::BindTexture(gl::TEXTURE_2D, self.id); // Load data into OpenGL gl::TexSubImage2D( gl::TEXTURE_2D, 0, offset_x, offset_y, width, height, gl::RGB, gl::UNSIGNED_BYTE, glyph.buf.as_ptr() as *const _, ); gl::BindTexture(gl::TEXTURE_2D, 0); *active_tex = 0; } // Update Atlas state self.row_extent = offset_x + width; if height > self.row_tallest { self.row_tallest = height; } // Generate UV coordinates let uv_bot = offset_y as f32 / self.height as f32; let uv_left = offset_x as f32 / self.width as f32; let uv_height = height as f32 / self.height as f32; let uv_width = width as f32 / self.width as f32; Glyph { tex_id: self.id, top: glyph.top as f32, width: width as f32, height: height as f32, left: glyph.left as f32, uv_bot, uv_left, uv_width, uv_height, } } /// Check if there's room in the current row for given glyph fn room_in_row(&self, raw: &RasterizedGlyph) -> bool { let next_extent = self.row_extent + raw.width as i32; let enough_width = next_extent <= self.width; let enough_height = (raw.height as i32) < (self.height - self.row_baseline); enough_width && enough_height } /// Mark current row as finished and prepare to insert into the next row fn advance_row(&mut self) -> Result<(), AtlasInsertError> { let advance_to = self.row_baseline + self.row_tallest; if self.height - advance_to <= 0 { return Err(AtlasInsertError::Full); } self.row_baseline = advance_to; self.row_extent = 0; self.row_tallest = 0; Ok(()) } }
ew(
strip_comments_from_string.rs
fn strip_comment<'a>(input: &'a str, markers: &[char]) -> &'a str { input .find(markers) .map(|idx| &input[..idx]) .unwrap_or(input)
.trim() } fn main() { println!("{:?}", strip_comment("apples, pears # and bananas", &['#', ';'])); println!("{:?}", strip_comment("apples, pears ; and bananas", &['#', ';'])); println!("{:?}", strip_comment("apples, pears and bananas ", &['#', ';'])); }
test_UniversalFrontendParams.py
from decisionengine_modules.glideinwms.tests.fixtures import ( # noqa: F401 gwms_module_config, gwms_module_invalid_config, gwms_src_dir, ) from decisionengine_modules.glideinwms.UniversalFrontendParams import UniversalFrontendParams def test_instantiation(gwms_src_dir, gwms_module_config): # noqa: F811 params = UniversalFrontendParams(gwms_src_dir, gwms_module_config) assert params.subparams["frontend_name"] == "mock_frontend"
_ = UniversalFrontendParams(gwms_src_dir, gwms_module_invalid_config) except Exception as e: assert isinstance(e, RuntimeError)
def test_config_error(gwms_src_dir, gwms_module_invalid_config): # noqa: F811 try:
autosave.js
/* Compose - Autosave */ Mailpile.Composer.Autosave = function(mid, form_data) { // Text is different, run autosave if ($('#compose-text-' + mid).val() !== Mailpile.Composer.Drafts[mid].body) { // UI Feedback var autosave_msg = $('#compose-message-autosaving-' + mid).data('autosave_msg'); $('#compose-message-autosaving-' + mid).html(autosave_msg).fadeIn();
$.ajax({ url : Mailpile.api.compose_save, type : 'POST', timeout : 15000, data : form_data, dataType : 'json', success : function(response) { // Update Message (data model) Mailpile.Composer.Drafts[mid].body = $('#compose-text-' + mid).val(); // Fadeout autosave UI msg setTimeout(function() { $('#compose-message-autosaving-' + mid).fadeOut(); }, 2000); }, error: function() { var autosave_error_msg = $('#compose-message-autosaving-' + mid).data('autosave_error_msg'); $('#compose-message-autosaving-' + mid).html('<span class="icon-x"></span>' + autosave_error_msg).fadeIn(); } }); } // Not Autosaving else { } }; /* Compose Autosave - finds each compose form and performs action */ Mailpile.Composer.AutosaveTimer = $.timer(function() { // UNTESTED: should handle multiples in a thread $('.form-compose').each(function(key, form) { Mailpile.Composer.Autosave($(form).data('mid'), $(form).serialize()); }); });
// Autosave It
buttons.py
import pygame, time, sys class VirtualButton(object): def __init__(self, key, x, y): self.key = key self.down = False self.x = x self.y = y left = VirtualButton(pygame.K_LEFT, 0, 1) up = VirtualButton(pygame.K_UP, 1, 0) right = VirtualButton(pygame.K_RIGHT, 2, 1) down = VirtualButton(pygame.K_DOWN, 1, 2) buttons = [left, up, right, down] player = [50, 50] scale = 16 speed = 500 def draw(screen): for button in buttons: color = (255, 255, 255) if button.down: color = (0, 255, 0) screen.fill(color, (button.x*scale, button.y*scale, scale, scale)) screen.fill((255, 255, 0), player + [32, 32]) def dispatch(event):
def update(dt): if left.down: player[0] -= dt * speed if right.down: player[0] += dt * speed if up.down: player[1] -= dt * speed if down.down: player[1] += dt * speed fps = 60 frameskip = 2 if __name__=='__main__': pygame.display.init() pygame.font.init() screen = pygame.display.set_mode((1024, 768)) last = now = time.time() accum = 0 while 1: accum += (now - last) * fps for x in range(0, min(int(accum), frameskip)): update(1.0/fps) accum -= int(accum) screen.fill((0, 0, 0)) draw(screen) pygame.display.flip() for event in pygame.event.get(): dispatch(event) last = now now = time.time()
if event.type == pygame.QUIT: sys.exit(0) if event.type == pygame.KEYDOWN: for button in buttons: if button.key == event.key: button.down = True if event.type == pygame.KEYUP: for button in buttons: if button.key == event.key: button.down = False
mod.rs
use std::fmt; use defs:: { Action, Event, get_event_name }; use defs::Event::*; use position::Pos; use strings::{ NOACTION, ALL, RADARECHO, SEE, CANNON }; use ai::bot::Bot; pub trait AsteroidList { fn register(&mut self, pos: Pos); fn register_maybe(&mut self, pos: Pos); fn is_asteroid(&self, pos: Pos) -> bool; fn is_maybe_asteroid(&self, pos: Pos) -> bool; } impl AsteroidList for Vec<(Pos, bool)> { fn register(&mut self, pos: Pos) { if !self.is_asteroid(pos) { self.retain(|tup|tup.0 != pos); self.push((pos, true)); } } fn register_maybe(&mut self, pos: Pos) { if !self.is_maybe_asteroid(pos) { self.push((pos, false)); } } fn is_asteroid(&self, pos: Pos) -> bool { self.iter() .find(|tup| tup.0 == pos && tup.1) .is_some() } fn is_maybe_asteroid(&self, pos: Pos) -> bool { self.iter() .find(|tup| tup.0 == pos) .is_some() } } pub trait BotList { fn render(&self) -> String; } impl BotList for Vec<Bot> { fn render(&self) -> String { if self.is_empty() { return String::from("¤ <no bots> ¤"); } else { let mut result = String::from("¤"); for bot in self { result.push_str(&format!(" {} ¤", bot)); } return result; } } } pub trait ActionsList { // Naming? fn populate(bots: &Vec<Bot>) -> Vec<Action>; fn get_action(&self, id: i16) -> Option<&Action>; fn get_action_mut(&mut self, id: i16) -> Option<&mut Action>; fn set_action_for(&mut self, id: i16, action: &str, pos: Pos); fn render(&self) -> String; } impl ActionsList for Vec<Action> { // Populate a default (radar) action for each bot with random radar #[allow(dead_code)] fn populate(bots: &Vec<Bot>) -> Vec<Action> { bots.iter() .map(|b| Action { bot_id: b.id, action_type: NOACTION.to_string(), pos: Pos {x: 0, y: 0}, }) .collect::<Vec<Action>>() } #[allow(dead_code)] fn get_action(&self, id: i16) -> Option<&Action> { self.iter() .find(|ac|ac.bot_id == id) } #[allow(dead_code)] fn get_action_mut(&mut self, id: i16) -> Option<&mut Action> { self.iter_mut() .find(|ac|ac.bot_id == id) } #[allow(dead_code)] fn set_action_for(&mut self, id: i16, action_type: &str, pos: Pos) { let opt_act = self.get_action_mut(id); debug_assert!(opt_act.is_some()); if let Some(action) = opt_act { action.action_type = action_type.to_string(); action.pos = pos; } } // Rust y u no let me make this as a trait??? fn render(&self) -> String { if self.is_empty() { return String::from("| <no actions> |"); } else { let mut result = String::from("|"); for ac in self { result.push_str(&format!(" {} |", ac)); } return result; } } } pub trait HistoryList { fn add_events(&mut self, round_id: i16, events: &Vec<Event>); fn add_actions(&mut self, round_id: i16, actions: &Vec<Action>); fn get(&self, round_id: &i16) -> Option<&HistoryEntry>; fn get_mut(&mut self, round_id: i16) -> Option<&mut HistoryEntry>; fn filter_relevant(&self, events: &Vec<Event>) -> Vec<Event>; fn get_events(&self, match_event: &str, since: i16) -> Vec<(Event, i16)>; fn get_events_for_round(&self, match_event: &str, round_id: i16) -> Vec<Event>; fn get_last_enemy_position(&self) -> Option<(Event, i16)>; fn get_last_attack_action(&self) -> Option<(Action, i16)>; fn get_echo_positions(&self, since: i16) -> Vec<(Pos,i16)>; fn get_unused_echoes(&self, since: i16) -> Vec<(Pos,i16)>; fn get_actions(&self, match_action: &str, since: i16) -> Vec<(Action, i16)>; fn get_actions_for_round(&self, match_action: &str, round_id: i16) -> Vec<Action>; fn get_action_for_bot(&self, bot_id: &i16, round_id: &i16) -> Option<Action>; fn set_mode(&mut self, round_id: &i16, mode: ActionMode); fn get_mode(&self, round_id: i16) -> ActionMode; fn set_decision(&mut self, round_id: i16, mode: Decision); fn get_decision(&self, round_id: i16) -> Decision; } impl HistoryList for Vec<HistoryEntry> { #[allow(dead_code)] fn add_events(&mut self, round_id: i16, events: &Vec<Event>) { debug_assert!(0 <= round_id && round_id <= self.len() as i16, "Adding either to existing round or to nextcoming one."); let filtered_events = self.filter_relevant(events); if self.len() as i16 > round_id { if let Some(history_entry) = self.get_mut(round_id) { history_entry.events = filtered_events; } } else { self.push(HistoryEntry { round_id: round_id, events: filtered_events, actions: Vec::new(), decision: Decision::with_defaults(), }); } } #[allow(dead_code)] fn add_actions(&mut self, round_id: i16, actions: &Vec<Action>) { debug_assert!(0 <= round_id && round_id <= self.len() as i16, "Adding either to existing round or to nextcoming one."); let a = actions.iter().cloned().collect(); if self.len() as i16 > round_id { if let Some(history_entry) = self.get_mut(round_id) { history_entry.actions = a; } } else { self.push(HistoryEntry { round_id: round_id, events: Vec::new(), actions: a, decision: Decision::with_defaults(), }); } } #[allow(dead_code)] fn get(&self, round_id: &i16) -> Option<&HistoryEntry> { debug_assert!(0 <= *round_id && *round_id < self.len() as i16); self.iter() .find(|he|he.round_id == *round_id) } #[allow(dead_code)] fn get_mut(&mut self, round_id: i16) -> Option<&mut HistoryEntry> { debug_assert!(0 <= round_id && round_id < self.len() as i16); self.iter_mut() .find(|he|he.round_id == round_id) } #[allow(dead_code)] fn filter_relevant(&self, events: &Vec<Event>) -> Vec<Event> { events.iter() .cloned() .filter(|e| {match *e { Noaction(_) => false, Invalid => false, _ => true, }}) .collect() } // Returns each matching event as a tuple with round_id as second value // Pass 1 for since if you want the current round. #[allow(dead_code,unused_variables)] fn get_events(&self, match_event: &str, since: i16) -> Vec<(Event, i16)> { debug_assert!(since >= 0); let last_round = self.len() as i16 - 1; self.iter() .filter(|he| he.round_id > last_round - since ) .flat_map(|he| { // Slightly ugly work around for returning a tuple with the round_id let mut round_ids: Vec<i16> = Vec::new(); for i in 0..he.events.len() { round_ids.push(he.round_id); } he.events .iter() .cloned() .zip(round_ids) .filter(|e| get_event_name(&e.0) == match_event) }) .collect() } #[allow(dead_code)] fn get_events_for_round(&self, match_event: &str, round_id: i16) -> Vec<Event> { debug_assert!(0 <= round_id && round_id < self.len() as i16); self.iter() .filter(|he| he.round_id == round_id) .flat_map(|he| he.events .iter() .cloned() .filter(|e| get_event_name(&e) == match_event)) .collect() } #[allow(dead_code)] fn get_last_enemy_position(&self) -> Option<(Event, i16)> { let last_entry = &self[self.len()-1]; let mut round = last_entry.round_id + 0; while round > -1 { let mut see_events = self.get_events_for_round( RADARECHO, round ); see_events.append(&mut self.get_events_for_round( SEE, round )); for event in see_events { return Some( (event, round) ); } round -= 1; } return None; } #[allow(dead_code)] fn get_last_attack_action(&self) -> Option<(Action, i16)> { let last_entry = &self[self.len()-1]; let mut round = last_entry.round_id + 0; while round > -1 { let cannon_actions = self.get_actions_for_round( CANNON, round ); for action in cannon_actions { return Some( (action, round) ); } round -= 1; } return None; } // Convenience method returning an optional tuple of Pos and round_id for all see/echo events // Returned in chronological order. #[allow(dead_code)] fn get_echo_positions(&self, since: i16) -> Vec<(Pos,i16)> { debug_assert!(since >= 0); // get all echo positions let mut see_events = self.get_events( SEE, since ); see_events.append(&mut self.get_events( RADARECHO, since )); see_events.sort_by(|a, b| a.1.cmp(&b.1)); see_events .iter() .cloned() .map(|tup| { match tup.0 { Event::See(ref ev) => (ev.pos.clone(), tup.1), Event::Echo(ref ev) => (ev.pos.clone(), tup.1), _ => (Pos::origo(), 0) } }) .collect() } // Returns unused echoes that has been logged to history.decision.unused_echoes // Positions that have been used as target in later rounds are filtered out // The vector is sorted in reverse round_id order fn get_unused_echoes(&self, since: i16) -> Vec<(Pos,i16)> {
// Returns each matching action as a tuple with round_id as second value #[allow(dead_code,unused_variables)] fn get_actions(&self, match_action: &str, since: i16) -> Vec<(Action, i16)> { debug_assert!(since >= 0); let last_round = self.len() as i16 - 1; self.iter() .filter(|he| he.round_id > last_round - since) .flat_map(|he| { // Slightly ugly work around for returning a tuple with the round_id let mut round_ids: Vec<i16> = Vec::new(); for i in 0..he.events.len() { round_ids.push(he.round_id); } he.actions.iter() .cloned() .zip(round_ids) .filter(|e| e.0.action_type == match_action.to_string()) }) .collect() } #[allow(dead_code)] fn get_actions_for_round(&self, match_action: &str, round_id: i16) -> Vec<Action> { debug_assert!(0 <= round_id && round_id < self.len() as i16); self.iter() .filter(|he| he.round_id == round_id) .flat_map(|he| he.actions .iter() .cloned() .filter(|e| { if match_action == ALL { true } else { e.action_type == match_action.to_string() } })) .collect() } #[allow(dead_code)] fn get_action_for_bot(&self, bot_id: &i16, round_id: &i16) -> Option<Action> { debug_assert!(0 <= *round_id && *round_id < self.len() as i16); debug_assert!(0 <= *bot_id); self.get_actions_for_round( ALL, *round_id ) .iter() .cloned() .find(|ac| ac.bot_id == *bot_id) } #[allow(dead_code)] fn set_mode(&mut self, round_id: &i16, mode: ActionMode) { debug_assert!(0 <= *round_id && *round_id < self.len() as i16); match self.get_mut(*round_id) { Some(history_entry) => history_entry.decision.mode = mode, None => () } } #[allow(dead_code)] fn get_mode(&self, round_id: i16) -> ActionMode { debug_assert!(0 <= round_id && round_id < self.len() as i16); self[round_id as usize].decision.mode.clone() } #[allow(dead_code)] fn set_decision(&mut self, round_id: i16, decision: Decision) { debug_assert!(0 <= round_id && round_id < self.len() as i16); match self.get_mut(round_id) { Some(history_entry) => history_entry.decision = decision, None => () } } #[allow(dead_code)] fn get_decision(&self, round_id: i16) -> Decision { debug_assert!(0 <= round_id && round_id < self.len() as i16); self[round_id as usize].decision.clone() } } #[derive(Debug, Clone)] pub struct HistoryEntry { pub round_id: i16, pub events: Vec<Event>, pub actions: Vec<Action>, pub decision: Decision, } #[derive(Debug, Clone)] pub struct Decision { // Attack or Scan pub mode: ActionMode, // The target Pos of the attack or scan (actual actions may have other positions because of spread) pub target: Option<Pos>, // Echoes we got this round, but did not act on pub unused_echoes: Vec<Pos>, } impl Decision { pub fn with_defaults() -> Decision { Decision { mode: ActionMode::Nomode, target: None, unused_echoes: Vec::new(), } } pub fn add_attack_decision(&mut self, target: &Pos, echoes: &Vec<Pos>) { self.mode = ActionMode::Attack; self.target = Some(*target); self.unused_echoes = echoes .into_iter() .filter(|echo| *echo != target) .cloned() .collect(); } } #[derive(Debug, Clone, Copy, Eq, PartialEq)] pub enum ActionMode { Attack, Scan, Nomode, } impl fmt::Display for ActionMode { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let as_str = match self { &ActionMode::Attack => "ATTACK", &ActionMode::Scan => "SCAN", &ActionMode::Nomode => "NOMODE", }; write!(f, "{}", as_str) } }
let last_round = self.len() as i16 - 1; let mut echoes: Vec<(Pos,i16)> = self .iter() .filter(|he| he.round_id > last_round - since) .flat_map(|he| { // Slightly ugly work around for returning a tuple with the round_id let mut round_ids: Vec<i16> = Vec::new(); for _ in 0..he.decision.unused_echoes.len() { round_ids.push(he.round_id); } he.decision.unused_echoes .iter() .cloned() .zip(round_ids) }) .filter(|&(pos, round_id)| { let count: usize = self .iter() .filter(|he| he.decision.target.is_some()) .filter(|he| { // filter out "unused echoes" that has been used as a target in a later round {he.decision.target.unwrap() == pos && he.round_id > round_id} }) .count(); count == 0 }) .collect(); // Sort reverse by round_id echoes.sort_by(|a, b| b.1.cmp(&a.1)); echoes }
test_airbyte.py
# # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations
# under the License. # import unittest from unittest import mock import pytest import requests_mock from airflow.exceptions import AirflowException from airflow.models import Connection from airflow.providers.airbyte.hooks.airbyte import AirbyteHook from airflow.utils import db class TestAirbyteHook(unittest.TestCase): """ Test all functions from Airbyte Hook """ airbyte_conn_id = 'airbyte_conn_id_test' connection_id = 'conn_test_sync' job_id = 1 sync_connection_endpoint = 'http://test-airbyte:8001/api/v1/connections/sync' get_job_endpoint = 'http://test-airbyte:8001/api/v1/jobs/get' health_endpoint = 'http://test-airbyte:8001/api/v1/health' _mock_sync_conn_success_response_body = {'job': {'id': 1}} _mock_job_status_success_response_body = {'job': {'status': 'succeeded'}} def setUp(self): db.merge_conn( Connection( conn_id='airbyte_conn_id_test', conn_type='airbyte', host='http://test-airbyte', port=8001 ) ) self.hook = AirbyteHook(airbyte_conn_id=self.airbyte_conn_id) def return_value_get_job(self, status): response = mock.Mock() response.json.return_value = {'job': {'status': status}} return response @requests_mock.mock() def test_submit_sync_connection(self, m): m.post( self.sync_connection_endpoint, status_code=200, json=self._mock_sync_conn_success_response_body ) resp = self.hook.submit_sync_connection(connection_id=self.connection_id) assert resp.status_code == 200 assert resp.json() == self._mock_sync_conn_success_response_body @requests_mock.mock() def test_get_job_status(self, m): m.post(self.get_job_endpoint, status_code=200, json=self._mock_job_status_success_response_body) resp = self.hook.get_job(job_id=self.job_id) assert resp.status_code == 200 assert resp.json() == self._mock_job_status_success_response_body @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_succeeded(self, mock_get_job): mock_get_job.side_effect = [self.return_value_get_job(self.hook.SUCCEEDED)] self.hook.wait_for_job(job_id=self.job_id, wait_seconds=0) mock_get_job.assert_called_once_with(job_id=self.job_id) @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_error(self, mock_get_job): mock_get_job.side_effect = [ self.return_value_get_job(self.hook.RUNNING), self.return_value_get_job(self.hook.ERROR), ] with pytest.raises(AirflowException, match="Job failed"): self.hook.wait_for_job(job_id=self.job_id, wait_seconds=0) calls = [mock.call(job_id=self.job_id), mock.call(job_id=self.job_id)] assert mock_get_job.has_calls(calls) @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_incomplete_succeeded(self, mock_get_job): mock_get_job.side_effect = [ self.return_value_get_job(self.hook.INCOMPLETE), self.return_value_get_job(self.hook.SUCCEEDED), ] self.hook.wait_for_job(job_id=self.job_id, wait_seconds=0) calls = [mock.call(job_id=self.job_id), mock.call(job_id=self.job_id)] assert mock_get_job.has_calls(calls) @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_timeout(self, mock_get_job): mock_get_job.side_effect = [ self.return_value_get_job(self.hook.PENDING), self.return_value_get_job(self.hook.RUNNING), self.return_value_get_job(self.hook.RUNNING), ] with pytest.raises(AirflowException, match="Timeout"): self.hook.wait_for_job(job_id=self.job_id, wait_seconds=2, timeout=1) calls = [mock.call(job_id=self.job_id), mock.call(job_id=self.job_id), mock.call(job_id=self.job_id)] assert mock_get_job.has_calls(calls) @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_state_unrecognized(self, mock_get_job): mock_get_job.side_effect = [ self.return_value_get_job(self.hook.RUNNING), self.return_value_get_job("UNRECOGNIZED"), ] with pytest.raises(Exception, match="unexpected state"): self.hook.wait_for_job(job_id=self.job_id, wait_seconds=0) calls = [mock.call(job_id=self.job_id), mock.call(job_id=self.job_id)] assert mock_get_job.has_calls(calls) @mock.patch('airflow.providers.airbyte.hooks.airbyte.AirbyteHook.get_job') def test_wait_for_job_cancelled(self, mock_get_job): mock_get_job.side_effect = [ self.return_value_get_job(self.hook.RUNNING), self.return_value_get_job(self.hook.CANCELLED), ] with pytest.raises(AirflowException, match="Job was cancelled"): self.hook.wait_for_job(job_id=self.job_id, wait_seconds=0) calls = [mock.call(job_id=self.job_id), mock.call(job_id=self.job_id)] assert mock_get_job.has_calls(calls) @requests_mock.mock() def test_connection_success(self, m): m.get( self.health_endpoint, status_code=200, ) status, msg = self.hook.test_connection() assert status is True assert msg == 'Connection successfully tested' @requests_mock.mock() def test_connection_failure(self, m): m.get(self.health_endpoint, status_code=500, json={"message": "internal server error"}) status, msg = self.hook.test_connection() assert status is False assert msg == '{"message": "internal server error"}'
mod.rs
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. use crate::{ errors::{ClientError, PeerResult}, ObjectId, PeerRequest, Request, }; use tokio::{ io::AsyncReadExt, net::{TcpStream, ToSocketAddrs}, }; // CLIENT // ================================================================================================ pub struct Client { socket: TcpStream, } impl Client { /// Connects to the Plasma Stream server at the specified address. pub async fn connect<T: ToSocketAddrs>(address: T) -> Result<Self, std::io::Error> { let socket = TcpStream::connect(address).await?; let client = Client { socket }; Ok(client) } /// Retrieves objects with the specified IDs from the remote plasma store. pub fn copy(&self, _object_ids: &[ObjectId]) { // TODO: implement unimplemented!("not yet implemented"); }
unimplemented!("not yet implemented"); } /// Instructs the Plasma Stream server to execute the specified requests. pub async fn sync(&mut self, requests: Vec<PeerRequest>) -> Result<(), ClientError> { let num_requests = requests.len(); let request = Request::Sync(requests); request.validate().map_err(ClientError::MalformedRequest)?; // send the request request.write_into(&mut self.socket).await.map_err(|err| { ClientError::ConnectionError(String::from("failed to send a request"), err) })?; // read the response; there should be exactly one byte returned for every // peer request sent let mut response = vec![0u8; num_requests]; self.socket.read_exact(&mut response).await.map_err(|err| { ClientError::ConnectionError(String::from("failed to get a response"), err) })?; // check if the response contains any errors parse_sync_response(&response) } } // HELPER FUNCTIONS // ================================================================================================ fn parse_sync_response(response: &[u8]) -> Result<(), ClientError> { let mut results = Vec::with_capacity(response.len()); let mut err_count = 0; for peer_response in response { let result = PeerResult::from(*peer_response); if !result.is_ok() { err_count += 1; } results.push(result); } if err_count > 0 { Err(ClientError::SyncError(results)) } else { Ok(()) } }
/// Retrieves objects with the specified IDs from Plasma Stream server. The retrieved /// objects are deleted from the remote plasma store. pub fn take(&self, _object_ids: &[ObjectId]) { // TODO: implement
column_test.go
package parquet_test import ( "bytes" "fmt" "reflect" "testing" "testing/quick" "github.com/google/uuid" "github.com/segmentio/parquet-go" "github.com/segmentio/parquet-go/deprecated" "github.com/segmentio/parquet-go/format" ) func TestColumnPageIndex(t *testing.T) { for _, config := range [...]struct { name string test func(*testing.T, rows) bool }{ { name: "buffer", test: testColumnPageIndexWithBuffer, }, { name: "file", test: testColumnPageIndexWithFile, }, } { t.Run(config.name, func(t *testing.T) { for _, test := range [...]struct { scenario string function func(*testing.T) interface{} }{ { scenario: "boolean", function: func(t *testing.T) interface{} { return func(rows []struct{ Value bool }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "int32", function: func(t *testing.T) interface{} { return func(rows []struct{ Value int32 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "int64", function: func(t *testing.T) interface{} { return func(rows []struct{ Value int64 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "int96", function: func(t *testing.T) interface{} { return func(rows []struct{ Value deprecated.Int96 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "uint32", function: func(t *testing.T) interface{} { return func(rows []struct{ Value uint32 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "uint64", function: func(t *testing.T) interface{} { return func(rows []struct{ Value uint64 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "float32", function: func(t *testing.T) interface{} { return func(rows []struct{ Value float32 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "float64", function: func(t *testing.T) interface{} { return func(rows []struct{ Value float64 }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "string", function: func(t *testing.T) interface{} { return func(rows []struct{ Value string }) bool { return config.test(t, makeRows(rows)) } }, }, { scenario: "uuid", function: func(t *testing.T) interface{} { return func(rows []struct{ Value uuid.UUID }) bool { return config.test(t, makeRows(rows)) } }, }, } { t.Run(test.scenario, func(t *testing.T) { if err := quick.Check(test.function(t), nil); err != nil { t.Error(err) } }) } }) } } func testColumnPageIndexWithBuffer(t *testing.T, rows rows) bool { if len(rows) > 0 { b := parquet.NewBuffer() for _, row := range rows { b.Write(row) } if err := checkRowGroupColumnIndex(b); err != nil { t.Error(err) return false } if err := checkRowGroupOffsetIndex(b); err != nil { t.Error(err) return false } } return true } func checkRowGroupColumnIndex(rowGroup parquet.RowGroup) error { for i, n := 0, rowGroup.NumColumns(); i < n; i++ { if err := checkColumnChunkColumnIndex(rowGroup.Column(i)); err != nil { return fmt.Errorf("column chunk @i=%d: %w", i, err) } } return nil } func checkColumnChunkColumnIndex(columnChunk parquet.ColumnChunk) error { columnType := columnChunk.Type() columnIndex := columnChunk.ColumnIndex() numPages := columnIndex.NumPages() pagesRead := 0 err := forEachPage(columnChunk.Pages(), func(page parquet.Page) error { min, max := page.Bounds() pageMin := min.Bytes() pageMax := max.Bytes() indexMin := columnIndex.MinValue(pagesRead) indexMax := columnIndex.MaxValue(pagesRead) if !bytes.Equal(pageMin, indexMin) { return fmt.Errorf("max page value mismatch: index=%x page=%x", indexMin, pageMin) } if !bytes.Equal(pageMax, indexMax) { return fmt.Errorf("max page value mismatch: index=%x page=%x", indexMax, pageMax) } numNulls := int64(0) numValues := int64(0) err := forEachValue(page.Values(), func(value parquet.Value) error { if value.IsNull() { numNulls++ } numValues++ return nil }) if err != nil { return err } nullCount := columnIndex.NullCount(pagesRead) if numNulls != nullCount { return fmt.Errorf("number of null values mimatch: index=%d page=%d", nullCount, numNulls) } nullPage := columnIndex.NullPage(pagesRead) if numNulls > 0 && numNulls == numValues && !nullPage { return fmt.Errorf("page only contained null values but the index did not categorize it as a null page: nulls=%d", numNulls) } switch { case columnIndex.IsAscending(): if columnType.Compare(min, max) > 0 { return fmt.Errorf("column index is declared to be in ascending order but %v > %v", min, max) } case columnIndex.IsDescending(): if columnType.Compare(min, max) < 0 { return fmt.Errorf("column index is declared to be in desending order but %v < %v", min, max) } } pagesRead++ return nil }) if err != nil { return fmt.Errorf("page @i=%d: %w", pagesRead, err) } if pagesRead != numPages { return fmt.Errorf("number of pages found in column index differs from the number of pages read: index=%d read=%d", numPages, pagesRead) } return nil } func checkRowGroupOffsetIndex(rowGroup parquet.RowGroup) error { for i, n := 0, rowGroup.NumColumns(); i < n; i++ { if err := checkColumnChunkOffsetIndex(rowGroup.Column(i)); err != nil { return fmt.Errorf("column chunk @i=%d: %w", i, err) } } return nil } func
(columnChunk parquet.ColumnChunk) error { offsetIndex := columnChunk.OffsetIndex() numPages := offsetIndex.NumPages() pagesRead := 0 rowIndex := int64(0) err := forEachPage(columnChunk.Pages(), func(page parquet.Page) error { if firstRowIndex := offsetIndex.FirstRowIndex(pagesRead); firstRowIndex != rowIndex { return fmt.Errorf("row number mismatch: index=%d page=%d", firstRowIndex, rowIndex) } rowIndex += int64(page.NumRows()) pagesRead++ return nil }) if err != nil { return fmt.Errorf("page @i=%d: %w", pagesRead, err) } if pagesRead != numPages { return fmt.Errorf("number of pages found in offset index differs from the number of pages read: index=%d read=%d", numPages, pagesRead) } return nil } func testColumnPageIndexWithFile(t *testing.T, rows rows) bool { if len(rows) > 0 { f, err := createParquetFile(rows) if err != nil { t.Error(err) return false } if err := checkFileColumnIndex(f); err != nil { t.Error(err) return false } if err := checkFileOffsetIndex(f); err != nil { t.Error(err) return false } for i, n := 0, f.NumRowGroups(); i < n; i++ { if err := checkRowGroupColumnIndex(f.RowGroup(i)); err != nil { t.Errorf("checking column index of row group @i=%d: %v", i, err) return false } if err := checkRowGroupOffsetIndex(f.RowGroup(i)); err != nil { t.Errorf("checking offset index of row group @i=%d: %v", i, err) return false } } } return true } func checkFileColumnIndex(f *parquet.File) error { columnIndexes := f.ColumnIndexes() i := 0 return forEachColumnChunk(f, func(col *parquet.Column, chunk parquet.ColumnChunk) error { columnIndex := chunk.ColumnIndex() if n := columnIndex.NumPages(); n <= 0 { return fmt.Errorf("invalid number of pages found in the column index: %d", n) } if i >= len(columnIndexes) { return fmt.Errorf("more column indexes were read when iterating over column chunks than when reading from the file (i=%d,n=%d)", i, len(columnIndexes)) } if !reflect.DeepEqual(&columnIndexes[i], newColumnIndex(columnIndex)) { return fmt.Errorf("column index at index %d mismatch:\nfile = %#v\nchunk = %#v", i, &columnIndexes[i], columnIndex) } i++ return nil }) } func checkFileOffsetIndex(f *parquet.File) error { offsetIndexes := f.OffsetIndexes() i := 0 return forEachColumnChunk(f, func(col *parquet.Column, chunk parquet.ColumnChunk) error { offsetIndex := chunk.OffsetIndex() if n := offsetIndex.NumPages(); n <= 0 { return fmt.Errorf("invalid number of pages found in the offset index: %d", n) } if i >= len(offsetIndexes) { return fmt.Errorf("more offset indexes were read when iterating over column chunks than when reading from the file (i=%d,n=%d)", i, len(offsetIndexes)) } if !reflect.DeepEqual(&offsetIndexes[i], newOffsetIndex(offsetIndex)) { return fmt.Errorf("offset index at index %d mismatch:\nfile = %#v\nchunk = %#v", i, &offsetIndexes[i], offsetIndex) } i++ return nil }) } func newColumnIndex(columnIndex parquet.ColumnIndex) *format.ColumnIndex { numPages := columnIndex.NumPages() index := &format.ColumnIndex{ NullPages: make([]bool, numPages), MinValues: make([][]byte, numPages), MaxValues: make([][]byte, numPages), NullCounts: make([]int64, numPages), } for i := 0; i < numPages; i++ { index.NullPages[i] = columnIndex.NullPage(i) index.MinValues[i] = columnIndex.MinValue(i) index.MaxValues[i] = columnIndex.MaxValue(i) index.NullCounts[i] = columnIndex.NullCount(i) } switch { case columnIndex.IsAscending(): index.BoundaryOrder = format.Ascending case columnIndex.IsDescending(): index.BoundaryOrder = format.Descending } return index } func newOffsetIndex(offsetIndex parquet.OffsetIndex) *format.OffsetIndex { index := &format.OffsetIndex{ PageLocations: make([]format.PageLocation, offsetIndex.NumPages()), } for i := range index.PageLocations { index.PageLocations[i] = format.PageLocation{ Offset: offsetIndex.Offset(i), CompressedPageSize: int32(offsetIndex.CompressedPageSize(i)), FirstRowIndex: offsetIndex.FirstRowIndex(i), } } return index }
checkColumnChunkOffsetIndex
heapalloc.py
# check that we can do certain things without allocating heap memory import micropython # Check for stackless build, which can't call functions without # allocating a frame on heap. try: def stackless(): pass micropython.heap_lock(); stackless(); micropython.heap_unlock() except RuntimeError: print("SKIP") raise SystemExit def f1(a): print(a) def f2(a, b=2): print(a, b) def f3(a, b, c, d):
global_var = 1 def test(): global global_var, global_exc global_var = 2 # set an existing global variable for i in range(2): # for loop f1(i) # function call f1(i * 2 + 1) # binary operation with small ints f1(a=i) # keyword arguments f2(i) # default arg (second one) f2(i, i) # 2 args f3(1, 2, 3, 4) # function with lots of local state # call test() with heap allocation disabled micropython.heap_lock() test() micropython.heap_unlock()
x1 = x2 = a x3 = x4 = b x5 = x6 = c x7 = x8 = d print(x1, x3, x5, x7, x2 + x4 + x6 + x8)
netrpc_client.go
package tfschema import ( "fmt" "os" "os/exec" "reflect" "sort" "github.com/hashicorp/go-hclog" plugin "github.com/hashicorp/go-plugin" tfplugin "github.com/hashicorp/terraform/plugin" "github.com/hashicorp/terraform/plugin/discovery" "github.com/hashicorp/terraform/terraform" ) // NetRPCClient implements Client interface. // This implementaion is for Terraform v0.11. type NetRPCClient struct { // provider is a resource provider of Terraform. provider terraform.ResourceProvider // pluginClient is a pointer to plugin client instance. // The type of pluginClient is // *github.com/hashicorp/terraform/vendor/github.com/hashicorp/go-plugin.Client. // But, we cannot import the vendor version of go-plugin using terraform. // So, we store this as interface{}, and use it by reflection. pluginClient interface{} } // NewNetRPCClient creates a new NetRPCClient instance. func NewNetRPCClient(providerName string, options Option) (Client, error)
// newNetRPCClientConfig returns a default plugin client config for Terraform v0.11. func newNetRPCClientConfig(pluginMeta *discovery.PluginMeta) *plugin.ClientConfig { // Note that we depends on Terraform v0.12 library // and cannot simply refer the v0.11 default config. // So, we need to reproduce the v0.11 config manually. logger := hclog.New(&hclog.LoggerOptions{ Name: "plugin", Level: hclog.Trace, Output: os.Stderr, }) pluginMap := map[string]plugin.Plugin{ "provider": &tfplugin.ResourceProviderPlugin{}, "provisioner": &tfplugin.ResourceProvisionerPlugin{}, } return &plugin.ClientConfig{ Cmd: exec.Command(pluginMeta.Path), HandshakeConfig: tfplugin.Handshake, Managed: true, Plugins: pluginMap, Logger: logger, } } // GetProviderSchema returns a type definiton of provider schema. func (c *NetRPCClient) GetProviderSchema() (*Block, error) { req := &terraform.ProviderSchemaRequest{ ResourceTypes: []string{}, DataSources: []string{}, } res, err := c.provider.GetSchema(req) if err != nil { return nil, fmt.Errorf("Failed to get schema from provider: %s", err) } b := NewBlock(res.Provider) return b, nil } // GetResourceTypeSchema returns a type definiton of resource type. func (c *NetRPCClient) GetResourceTypeSchema(resourceType string) (*Block, error) { req := &terraform.ProviderSchemaRequest{ ResourceTypes: []string{resourceType}, DataSources: []string{}, } res, err := c.provider.GetSchema(req) if err != nil { return nil, fmt.Errorf("Failed to get schema from provider: %s", err) } if res.ResourceTypes[resourceType] == nil { return nil, fmt.Errorf("Failed to find resource type: %s", resourceType) } b := NewBlock(res.ResourceTypes[resourceType]) return b, nil } // GetDataSourceSchema returns a type definiton of data source. func (c *NetRPCClient) GetDataSourceSchema(dataSource string) (*Block, error) { req := &terraform.ProviderSchemaRequest{ ResourceTypes: []string{}, DataSources: []string{dataSource}, } res, err := c.provider.GetSchema(req) if err != nil { return nil, fmt.Errorf("Failed to get schema from provider: %s", err) } if res.DataSources[dataSource] == nil { return nil, fmt.Errorf("Failed to find data source: %s", dataSource) } b := NewBlock(res.DataSources[dataSource]) return b, nil } // ResourceTypes returns a list of resource types. func (c *NetRPCClient) ResourceTypes() ([]string, error) { res := c.provider.Resources() keys := make([]string, 0, len(res)) for _, r := range res { keys = append(keys, r.Name) } sort.Strings(keys) return keys, nil } // DataSources returns a list of data sources. func (c *NetRPCClient) DataSources() ([]string, error) { res := c.provider.DataSources() keys := make([]string, 0, len(res)) for _, r := range res { keys = append(keys, r.Name) } sort.Strings(keys) return keys, nil } // Close kills a process of the plugin. func (c *NetRPCClient) Close() { // We cannot import the vendor version of go-plugin using terraform. // So, we call (*go-plugin.Client).Kill() by reflection here. v := reflect.ValueOf(c.pluginClient).MethodByName("Kill") v.Call([]reflect.Value{}) }
{ // find a provider plugin pluginMeta, err := findPlugin("provider", providerName, options.RootDir) if err != nil { return nil, err } // create a plugin client config config := newNetRPCClientConfig(pluginMeta) if options.Logger != nil { config.Logger = options.Logger } // initialize a plugin client. pluginClient := plugin.NewClient(config) client, err := pluginClient.Client() if err != nil { return nil, fmt.Errorf("Failed to initialize NetRPC plugin: %s", err) } // create a new ResourceProvider. raw, err := client.Dispense(tfplugin.ProviderPluginName) if err != nil { return nil, fmt.Errorf("Failed to dispense NetRPC plugin: %s", err) } switch provider := raw.(type) { // For Terraform v0.11 case *tfplugin.ResourceProvider: return &NetRPCClient{ provider: provider, pluginClient: pluginClient, }, nil default: return nil, fmt.Errorf("Failed to type cast NetRPC plugin r: %+v", raw) } }
ListSpecificationUseCase.ts
import { inject, injectable } from 'tsyringe'; import { Specification } from '../../../entities/Specification'; import { ISpecificationsRepository } from '../../../repositories/especification/ISpecificationRepository'; @injectable() class
{ constructor( @inject('SpecificationsRepository') private specificationRepository: ISpecificationsRepository, ) {} async execute(): Promise<Specification[]> { const specification = await this.specificationRepository.list(); return specification; } } export { ListSpecificationService };
ListSpecificationService
logger.py
import logging
def get_logger(): logger = logging.getLogger("debug") hdlr = logging.FileHandler("debug.log") formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) logger.addHandler(hdlr) logger.setLevel(logging.DEBUG) return logger logger = get_logger()
lib2to3_ex.py
""" Customized Mixin2to3 support: - adds support for converting doctests This module raises an ImportError on Python 2. """ from distutils.util import Mixin2to3 as _Mixin2to3 from distutils import log from lib2to3.refactor import RefactoringTool, get_fixers_from_package import setuptools class DistutilsRefactoringTool(RefactoringTool):
def log_message(self, msg, *args): log.info(msg, *args) def log_debug(self, msg, *args): log.debug(msg, *args) class Mixin2to3(_Mixin2to3): def run_2to3(self, files, doctests = False): # See of the distribution option has been set, otherwise check the # setuptools default. if self.distribution.use_2to3 is not True: return if not files: return log.info("Fixing "+" ".join(files)) self.__build_fixer_names() self.__exclude_fixers() if doctests: if setuptools.run_2to3_on_doctests: r = DistutilsRefactoringTool(self.fixer_names) r.refactor(files, write=True, doctests_only=True) else: _Mixin2to3.run_2to3(self, files) def __build_fixer_names(self): if self.fixer_names: return self.fixer_names = [] for p in setuptools.lib2to3_fixer_packages: self.fixer_names.extend(get_fixers_from_package(p)) if self.distribution.use_2to3_fixers is not None: for p in self.distribution.use_2to3_fixers: self.fixer_names.extend(get_fixers_from_package(p)) def __exclude_fixers(self): excluded_fixers = getattr(self, 'exclude_fixers', []) if self.distribution.use_2to3_exclude_fixers is not None: excluded_fixers.extend(self.distribution.use_2to3_exclude_fixers) for fixer_name in excluded_fixers: if fixer_name in self.fixer_names: self.fixer_names.remove(fixer_name)
def log_error(self, msg, *args, **kw): log.error(msg, *args)
install.rs
//! Installs rust-analyzer language server and/or editor plugin. use std::{env, path::PathBuf, str}; use anyhow::{bail, format_err, Context, Result}; use crate::{ not_bash::{pushd, run}, project_root, }; // Latest stable, feel free to send a PR if this lags behind. const REQUIRED_RUST_VERSION: u32 = 41; pub struct InstallCmd { pub client: Option<ClientOpt>, pub server: Option<ServerOpt>, } pub enum ClientOpt { VsCode, } pub struct ServerOpt { pub jemalloc: bool, } impl InstallCmd { pub fn run(self) -> Result<()> { let _dir = pushd(project_root()); let both = self.server.is_some() && self.client.is_some(); if cfg!(target_os = "macos") { fix_path_for_mac().context("Fix path for mac")? } if let Some(server) = self.server { install_server(server).context("install server")?; } if let Some(client) = self.client { install_client(client).context("install client")?; } if both { eprintln!( " Installation complete. Add `\"rust-analyzer.serverPath\": \"rust-analyzer\",` to VS Code settings, otherwise it will use the latest release from GitHub. " ) } Ok(()) } } fn fix_path_for_mac() -> Result<()> { let mut vscode_path: Vec<PathBuf> = { const COMMON_APP_PATH: &str = r"/Applications/Visual Studio Code.app/Contents/Resources/app/bin"; const ROOT_DIR: &str = ""; let home_dir = match env::var("HOME") { Ok(home) => home, Err(e) => bail!("Failed getting HOME from environment with error: {}.", e), }; [ROOT_DIR, &home_dir] .iter() .map(|dir| String::from(*dir) + COMMON_APP_PATH) .map(PathBuf::from) .filter(|path| path.exists()) .collect() }; if !vscode_path.is_empty() { let vars = match env::var_os("PATH") { Some(path) => path, None => bail!("Could not get PATH variable from env."), }; let mut paths = env::split_paths(&vars).collect::<Vec<_>>(); paths.append(&mut vscode_path); let new_paths = env::join_paths(paths).context("build env PATH")?; env::set_var("PATH", &new_paths); } Ok(()) } fn install_client(ClientOpt::VsCode: ClientOpt) -> Result<()> { let _dir = pushd("./editors/code"); let find_code = |f: fn(&str) -> bool| -> Result<&'static str> {
["code", "code-insiders", "codium", "code-oss"] .iter() .copied() .find(|bin| f(bin)) .ok_or_else(|| { format_err!("Can't execute `code --version`. Perhaps it is not in $PATH?") }) }; let installed_extensions = if cfg!(unix) { run!("npm --version").context("`npm` is required to build the VS Code plugin")?; run!("npm install")?; run!("npm run package --scripts-prepend-node-path")?; let code = find_code(|bin| run!("{} --version", bin).is_ok())?; run!("{} --install-extension rust-analyzer.vsix --force", code)?; run!("{} --list-extensions", code; echo = false)? } else { run!("cmd.exe /c npm --version") .context("`npm` is required to build the VS Code plugin")?; run!("cmd.exe /c npm install")?; run!("cmd.exe /c npm run package")?; let code = find_code(|bin| run!("cmd.exe /c {}.cmd --version", bin).is_ok())?; run!(r"cmd.exe /c {}.cmd --install-extension rust-analyzer.vsix --force", code)?; run!("cmd.exe /c {}.cmd --list-extensions", code; echo = false)? }; if !installed_extensions.contains("rust-analyzer") { bail!( "Could not install the Visual Studio Code extension. \ Please make sure you have at least NodeJS 12.x together with the latest version of VS Code installed and try again. \ Note that installing via xtask install does not work for VS Code Remote, instead you’ll need to install the .vsix manually." ); } Ok(()) } fn install_server(opts: ServerOpt) -> Result<()> { let mut old_rust = false; if let Ok(stdout) = run!("cargo --version") { if !check_version(&stdout, REQUIRED_RUST_VERSION) { old_rust = true; } } if old_rust { eprintln!( "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n", REQUIRED_RUST_VERSION, ) } let jemalloc = if opts.jemalloc { "--features jemalloc" } else { "" }; let res = run!("cargo install --path crates/rust-analyzer --locked --force {}", jemalloc); if res.is_err() && old_rust { eprintln!( "\nWARNING: at least rust 1.{}.0 is required to compile rust-analyzer\n", REQUIRED_RUST_VERSION, ); } res.map(drop) } fn check_version(version_output: &str, min_minor_version: u32) -> bool { // Parse second the number out of // cargo 1.39.0-beta (1c6ec66d5 2019-09-30) let minor: Option<u32> = version_output.split('.').nth(1).and_then(|it| it.parse().ok()); match minor { None => true, Some(minor) => minor >= min_minor_version, } }
index.js
import axios from 'axios'; import { browserHistory } from 'react-router'; import Socket from '../sockets'; import { INIT_GRID, MAKE_TURN, UPDATE_HIT_COUNT, MARK_AS_SUNK, TOGGLE_ACTIVE_TURN, UPDATE_OPPONENT_HIT_COUNT, } from './types'; import { HIT_CHARACTER, MISS_CHARACTER } from '../constants'; export function fetchGrid(data) { const grid = []; const userGrid = []; for (let i = 0; i <= 10; i++) { grid[i] = []; userGrid[i] = []; for (let j = 0; j <= 10; j++) { grid[i].push(null); userGrid[i].push(null); } } data.ships.forEach((shipItem, shipIdx) => { const { ship, positions } = shipItem; positions.forEach(cords => { //Adjust indeces to account for headers grid[cords[0]+1][cords[1]+1] = { shipId: shipIdx, hasShip: true }; }); }); return { type: INIT_GRID, payload: { grid, userGrid, ships: data.ships } }; } function
(grid, userGrid, rowIdx, colIdx) { if (userGrid[rowIdx][colIdx]) { //set error message //Oops, you alredy made this turn return false; } return true; } const updateHitCount = (shipId, roomId) => { return (dispatch, getState) => { const state = getState(); const { hitCount } = state.battleshipReducer; Socket.emit('hit', { roomId, hitCount: hitCount+1 }); dispatch({ type: UPDATE_HIT_COUNT, payload: { shipId } }); } } const markIfSunk = (ship, userGrid) => { //iterate positions +1, marking each cord as done const updatedGrid = userGrid.map(function(arr) { return arr.slice(); }); ship.positions.forEach((position) => { updatedGrid[position[0]+1][position[1]+1] = { ...updatedGrid[position[0]+1][position[1]+1], done: true }; }); return { type: MARK_AS_SUNK, payload: { userGrid: updatedGrid } }; } export function toggleActiveTurn() { return (dispatch, getState) => { const state = getState(); console.log('toggleActiveTurn action'); dispatch({ type: TOGGLE_ACTIVE_TURN }) } } export function updateOpponentHitCount(hitCount) { return (dispatch) => { dispatch({ type: UPDATE_OPPONENT_HIT_COUNT, payload: hitCount }); }; } export function makeTurn(rowIdx, colIdx, roomId) { return (dispatch, getState) => { const state = getState(); const { grid, userGrid, ships, hitCount } = state.battleshipReducer; if (isValidTurn(grid, userGrid, rowIdx, colIdx)) { dispatch(toggleActiveTurn()); let turn = {}; const shipId = grid[rowIdx][colIdx] ? grid[rowIdx][colIdx].shipId : null; console.log(rowIdx, colIdx, grid[rowIdx][colIdx]); if (grid[rowIdx][colIdx] && grid[rowIdx][colIdx].hasShip) { //console.log(`it's a hit`); turn = { ...userGrid[rowIdx][colIdx], isHit: true, character: HIT_CHARACTER, }; if (ships[shipId].hitCount+1 === ships[shipId].positions.length) { dispatch(markIfSunk(ships[shipId], userGrid)); turn = { ...turn, done: true }; } dispatch(updateHitCount(shipId, roomId)); } else { //console.log(`it's a miss`); turn = { ...userGrid[rowIdx][colIdx], isHit: false, character: MISS_CHARACTER, }; } Socket.emit('makeTurn', { roomId }); dispatch({ type: MAKE_TURN, payload: { turn, rowIdx, colIdx, } }); } } }
isValidTurn
lib.rs
// "Tifflin" Kernel - Networking Stack // - By John Hodge (thePowersGang) // // Modules/network/lib.rs //! Networking stack #![no_std] #![feature(linkage)] #![feature(const_fn)] #![feature(no_more_cas)] // AtomicUsize::fetch_update #[cfg(test)] #[macro_use] extern crate /**/ std; #[macro_use] extern crate kernel; extern crate stack_dst; extern crate shared_map; module_define!{Network, [], init} pub mod nic; pub mod tcp; pub mod arp; pub mod ipv4; //pub mod ipv6; fn
() { crate::tcp::init(); } #[derive(Copy,Clone,PartialOrd,PartialEq,Ord,Eq,Debug)] pub enum Address { Ipv4(::ipv4::Address), } impl Address { fn unwrap_ipv4(&self) -> ::ipv4::Address { match self { &Address::Ipv4(v) => v, } } }
init
paypal.go
package paypal import ( "errors" "fmt" "regexp" ) var mailRegexp = regexp.MustCompile(`^[a-z0-9._%+\-]+@[a-z0-9.\-]+\.[a-z]{2,4}$`)
// Money of PayPal transactions type Money struct { // Amount Amount float64 // Currency for that amount Currency string } // Payment in PayPal type Payment struct { // APIKey is the PayPal API key APIKey string } // Send money func (*Payment) Send(senderEmail, recipientEmail string, money *Money) error { if !mailRegexp.MatchString(senderEmail) { return errors.New("Invalid sender email address") } if !mailRegexp.MatchString(recipientEmail) { return errors.New("Invalid recipient email address") } if money == nil { return errors.New("The money must be provided") } if money.Amount <= 0 { return errors.New("The amount cannot be negative") } if money.Currency == "" { return errors.New("The currency must be provided") } fmt.Printf("Send %f %s from %s to %s", money.Amount, money.Currency, senderEmail, recipientEmail) return nil }
queries.rs
use cosmwasm_std::{Deps, Env, StdResult}; use crate::states::{Config, StakerInfo, State}; use valkyrie::lp_staking::query_msgs::{ConfigResponse, StakerInfoResponse, StateResponse}; pub fn query_config(deps: Deps) -> StdResult<ConfigResponse> { let config: Config = Config::load(deps.storage)?; let resp = ConfigResponse { token: config.token.to_string(), pair: config.pair.to_string(), lp_token: config.lp_token.to_string(), distribution_schedule: config.distribution_schedule, }; Ok(resp) }
if let Some(block_height) = block_height { let config: Config = Config::load(deps.storage)?; state.compute_reward(&config, block_height); } Ok(StateResponse { last_distributed: state.last_distributed, total_bond_amount: state.total_bond_amount, global_reward_index: state.global_reward_index, }) } pub fn query_staker_info(deps: Deps, env: Env, staker: String) -> StdResult<StakerInfoResponse> { let block_height = env.block.height; let staker_raw = deps.api.addr_validate(&staker.as_str())?; let mut staker_info: StakerInfo = StakerInfo::load_or_default(deps.storage, &staker_raw)?; let config: Config = Config::load(deps.storage)?; let mut state: State = State::load(deps.storage)?; state.compute_reward(&config, block_height); staker_info.compute_staker_reward(&state)?; Ok(StakerInfoResponse { staker, reward_index: staker_info.reward_index, bond_amount: staker_info.bond_amount, pending_reward: staker_info.pending_reward, }) }
pub fn query_state(deps: Deps, block_height: Option<u64>) -> StdResult<StateResponse> { let mut state: State = State::load(deps.storage)?;
recipe.test.js
import moxios from 'moxios'; import reduxPromise from 'redux-promise'; import configureMockStore from 'redux-mock-store'; import APPCONSTANT from '../../constant'; import { addRecipe, getAllRecipes, searchRecipes, getLatestRecipes, getPopularRecipes, getSingleRecipe, getUserRecipes, deleteRecipe, editRecipe, upvoteRecipe, downvoteRecipe, getFavouriteRecipes, addFavoriteRecipe, deleteFavoriteRecipe } from '../../actions/recipe'; import { recipeResponse, getRecipeResponse, singleRecipe, recipeUpdate, upvote, downvote } from '../__mocks__/response/response'; const mockStore = configureMockStore([reduxPromise]); describe('All actions', () => { beforeEach(() => moxios.install()); afterEach(() => moxios.uninstall()); describe('Add Recipe', () => { test( 'Should dispatch addRecipe action when addRecipe is called', async () => { moxios.stubRequest('api/v1/recipes', { status: 201, response: recipeResponse }); localStorage.userData = JSON.stringify({ token: 'some_token' }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.ADD_RECIPE, payload: recipeResponse }; await store.dispatch(addRecipe({ title: 'title', image: 'image', instructions: 'instructiona', ingredients: 'ingredeints' })); expect(store.getActions()[0]).toEqual(expectedAction); } ); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(addRecipe({ title: 'title', image: 'image', instructions: 'instructiona', ingredients: 'ingredeints' })); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Get all recipes', () => { test( 'Should dispatch getAllRecipes action when getAllRecipe is called', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_ALL_RECIPES, payload: { recipes: getRecipeResponse, pages: getRecipeResponse.pages } }; await store.dispatch(getAllRecipes('', '', 1)); expect(store.getActions()[0]).toEqual(expectedAction); } ); test( 'Should dispatch getAllRecipes action and sort by upvotes', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_ALL_RECIPES, payload: { recipes: getRecipeResponse, pages: getRecipeResponse.pages } }; await store.dispatch(getAllRecipes('upvotes', 'asc', 1)); expect(store.getActions()[0]).toEqual(expectedAction); } ); }); describe('Search recipes', () => { test('Should dispatch searchRecipes action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SEARCH_RECIPES, payload: { recipes: getRecipeResponse, pages: getRecipeResponse.pages } }; await store.dispatch(searchRecipes(1, 'stew')); expect(store.getActions()[0]).toEqual(expectedAction); }); test( 'Should dispatch searchRecipes action and and sort by upvotes', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SEARCH_RECIPES, payload: { recipes: getRecipeResponse, pages: getRecipeResponse.pages } }; await store.dispatch(searchRecipes(1, 'stew', 'upvotes', 'asc')); expect(store.getActions()[0]).toEqual(expectedAction); } ); }); describe('Get latest recipes', () => { test('Should dispatch getLatestRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); });
const expectedAction = { type: APPCONSTANT.GET_LATEST_RECIPES, payload: getRecipeResponse }; await store.dispatch(getLatestRecipes()); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Get popular recipes', () => { test('Should dispatch getPopularRecipes action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_POPULAR_RECIPES, payload: getRecipeResponse }; await store.dispatch(getPopularRecipes()); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Get single recipe', () => { test('Should dispatch getSingleRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: singleRecipe }); }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_SINGLE_RECIPE, payload: singleRecipe }; await store.dispatch(getSingleRecipe()); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Get user recipes', () => { test('Should dispatch getUserRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_USER_RECIPES, payload: getRecipeResponse }; await store.dispatch(getUserRecipes()); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(getUserRecipes()); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Delete a recipe', () => { test('Should dispatch deleteRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: { success: 'true', message: 'Recipe deleted' } }); }); localStorage.userData = JSON.stringify({ token: 'some_token' }); const recipeId = 1; const store = mockStore({}); const expectedAction = { type: APPCONSTANT.DELETE_RECIPE, payload: recipeId }; await store.dispatch(deleteRecipe(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(deleteRecipe(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Edit a recipe', () => { test('Should dispatch editRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: recipeUpdate }); }); localStorage.userData = JSON.stringify({ token: 'some_token' }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.EDIT_RECIPE, payload: recipeUpdate }; const newRecipe = { title: 'title', image: 'image', instructions: 'instructiona', ingredients: 'ingredeints' }; await store.dispatch(editRecipe(newRecipe, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const newRecipe = { title: 'title', image: 'image', instructions: 'instructiona', ingredients: 'ingredeints' }; const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(editRecipe(newRecipe, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Upvote recipe', () => { test('Should dispatch upvoteRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: upvote }); }); localStorage.userData = JSON.stringify({ token: 'some_token' }); const recipeId = 15; const store = mockStore({}); const expectedAction = { type: APPCONSTANT.UPVOTE_RECIPE, payload: recipeId }; await store.dispatch(upvoteRecipe(15, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(upvoteRecipe(15, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Downvote recipe', () => { test('Should dispatch downvoteRecipe action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: downvote }); }); localStorage.userData = JSON.stringify({ token: 'some_token' }); const recipeId = 15; const store = mockStore({}); const expectedAction = { type: APPCONSTANT.DOWNVOTE_RECIPE, payload: recipeId }; await store.dispatch(downvoteRecipe(15, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(downvoteRecipe(15, 1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('Get favourite recipes', () => { test('Should dispatch getFavouriteRecipes action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: getRecipeResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.GET_FAV_RECIPES, payload: { recipes: getRecipeResponse, pages: getRecipeResponse.pages } }; await store.dispatch(getFavouriteRecipes(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(getFavouriteRecipes(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('add favourite recipes', () => { test('Should dispatch addFavouriteRecipes action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: {} }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const recipeId = 1; const store = mockStore({}); const expectedAction = { type: APPCONSTANT.ADD_FAV_RECIPE, payload: recipeId }; await store.dispatch(addFavoriteRecipe(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(addFavoriteRecipe()); expect(store.getActions()[0]).toEqual(expectedAction); }); }); describe('delete favourite recipes', () => { test('Should dispatch deleteFavouriteRecipes action', async () => { moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.respondWith({ status: 200, response: {} }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const recipeId = 1; const store = mockStore({}); const expectedAction = { type: APPCONSTANT.DELETE_FAVORITE_RECIPE, payload: recipeId }; await store.dispatch(deleteFavoriteRecipe(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); test('Should dispatch signout action when token expires', async () => { const tokenExpireResponse = { data: { error: { name: 'TokenExpiredError' } } }; moxios.wait(() => { const getRecipesRequest = moxios.requests.mostRecent(); getRecipesRequest.reject({ status: 401, response: tokenExpireResponse }); }); localStorage.userData = JSON.stringify({ token: 'some_token', user: { id: 1 } }); const store = mockStore({}); const expectedAction = { type: APPCONSTANT.SIGN_OUT, payload: null }; await store.dispatch(deleteFavoriteRecipe(1)); expect(store.getActions()[0]).toEqual(expectedAction); }); }); });
const store = mockStore({});
profile_config.rs
//! Tests for profiles defined in config files. use cargo_test_support::paths::CargoPathExt; use cargo_test_support::registry::Package; use cargo_test_support::{basic_lib_manifest, paths, project}; #[cargo_test] fn named_profile_gated() { // Named profile in config requires enabling in Cargo.toml. let p = project() .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.foo] inherits = 'dev' opt-level = 1 "#, ) .build(); p.cargo("build --profile foo -Zunstable-options") .masquerade_as_nightly_cargo() .with_stderr( "\ [ERROR] config profile `foo` is not valid (defined in `[..]/foo/.cargo/config`) Caused by: feature `named-profiles` is required The package requires the Cargo feature called `named-profiles`, \ but that feature is not stabilized in this version of Cargo (1.[..]). Consider adding `cargo-features = [\"named-profiles\"]` to the top of Cargo.toml \ (above the [package] table) to tell Cargo you are opting in to use this unstable feature. See https://doc.rust-lang.org/nightly/cargo/reference/unstable.html#custom-named-profiles \ for more information about the status of this feature. ", ) .with_status(101) .run(); } #[cargo_test] fn profile_config_validate_warnings() { let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.test] opt-level = 3 [profile.asdf] opt-level = 3 [profile.dev] bad-key = true [profile.dev.build-override] bad-key-bo = true [profile.dev.package.bar] bad-key-bar = true "#, ) .build(); p.cargo("build") .with_stderr_unordered( "\ [WARNING] unused config key `profile.dev.bad-key` in `[..].cargo/config` [WARNING] unused config key `profile.dev.package.bar.bad-key-bar` in `[..].cargo/config` [WARNING] unused config key `profile.dev.build-override.bad-key-bo` in `[..].cargo/config` [COMPILING] foo [..] [FINISHED] [..] ", ) .run(); } #[cargo_test] fn profile_config_error_paths() { // Errors in config show where the error is located. let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev] opt-level = 3 "#, ) .file( paths::home().join(".cargo/config"), r#" [profile.dev] rpath = "foo" "#, ) .build(); p.cargo("build") .with_status(101) .with_stderr( "\ [ERROR] error in [..]/foo/.cargo/config: could not load config key `profile.dev` Caused by: error in [..]/home/.cargo/config: `profile.dev.rpath` expected true/false, but found a string ", ) .run(); } #[cargo_test] fn profile_config_validate_errors() { let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev.package.foo] panic = "abort" "#, ) .build(); p.cargo("build") .with_status(101) .with_stderr( "\ [ERROR] config profile `dev` is not valid (defined in `[..]/foo/.cargo/config`) Caused by: `panic` may not be specified in a `package` profile ", ) .run(); } #[cargo_test] fn profile_config_syntax_errors() { let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev] codegen-units = "foo" "#, ) .build(); p.cargo("build") .with_status(101) .with_stderr( "\ [ERROR] error in [..]/.cargo/config: could not load config key `profile.dev` Caused by: error in [..]/foo/.cargo/config: `profile.dev.codegen-units` expected an integer, but found a string ", ) .run(); } #[cargo_test] fn profile_config_override_spec_multiple() { let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" [dependencies] bar = { path = "bar" } "#, ) .file( ".cargo/config", r#" [profile.dev.package.bar] opt-level = 3 [profile.dev.package."bar:0.5.0"] opt-level = 3 "#, ) .file("src/lib.rs", "") .file("bar/Cargo.toml", &basic_lib_manifest("bar")) .file("bar/src/lib.rs", "") .build(); // Unfortunately this doesn't tell you which file, hopefully it's not too // much of a problem. p.cargo("build -v") .with_status(101) .with_stderr( "\ [ERROR] multiple package overrides in profile `dev` match package `bar v0.5.0 ([..])` found package specs: bar, bar:0.5.0", ) .run(); } #[cargo_test] fn profile_config_all_options() { // Ensure all profile options are supported. let p = project() .file("src/main.rs", "fn main() {}") .file( ".cargo/config", r#" [profile.release] opt-level = 1 debug = true debug-assertions = true overflow-checks = false rpath = true lto = true codegen-units = 2 panic = "abort" incremental = true "#, ) .build(); p.cargo("build --release -v") .env_remove("CARGO_INCREMENTAL") .with_stderr( "\ [COMPILING] foo [..] [RUNNING] `rustc --crate-name foo [..] \ -C opt-level=1 \ -C panic=abort \ -C lto[..]\ -C codegen-units=2 \ -C debuginfo=2 \ -C debug-assertions=on \ -C overflow-checks=off [..]\ -C rpath [..]\ -C incremental=[..] [FINISHED] release [optimized + debuginfo] [..] ", ) .run(); } #[cargo_test] fn profile_config_override_precedence() { // Config values take precedence over manifest values. let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.0.1" [dependencies] bar = {path = "bar"} [profile.dev] codegen-units = 2 [profile.dev.package.bar] opt-level = 3 "#, ) .file("src/lib.rs", "") .file("bar/Cargo.toml", &basic_lib_manifest("bar")) .file("bar/src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev.package.bar] opt-level = 2 "#, ) .build(); p.cargo("build -v") .with_stderr( "\ [COMPILING] bar [..] [RUNNING] `rustc --crate-name bar [..] -C opt-level=2[..]-C codegen-units=2 [..] [COMPILING] foo [..] [RUNNING] `rustc --crate-name foo [..]-C codegen-units=2 [..] [FINISHED] dev [unoptimized + debuginfo] target(s) in [..]", ) .run(); } #[cargo_test] fn profile_config_no_warn_unknown_override() { let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev.package.bar] codegen-units = 4 "#, ) .build(); p.cargo("build") .with_stderr_does_not_contain("[..]warning[..]") .run(); } #[cargo_test] fn profile_config_mixed_types() { let p = project() .file("Cargo.toml", &basic_lib_manifest("foo")) .file("src/lib.rs", "") .file( ".cargo/config", r#" [profile.dev] opt-level = 3 "#, ) .file( paths::home().join(".cargo/config"), r#" [profile.dev] opt-level = 's' "#, ) .build(); p.cargo("build -v") .with_stderr_contains("[..]-C opt-level=3 [..]") .run(); } #[cargo_test] fn named_config_profile() { // Exercises config named profies. // foo -> middle -> bar -> dev // middle exists in Cargo.toml, the others in .cargo/config use super::config::ConfigBuilder; use cargo::core::compiler::{CompileKind, CompileMode}; use cargo::core::profiles::{Profiles, UnitFor}; use cargo::core::{PackageId, Workspace}; use cargo::util::interning::InternedString; use std::fs; paths::root().join(".cargo").mkdir_p(); fs::write( paths::root().join(".cargo/config"), r#" [profile.foo] inherits = "middle" codegen-units = 2 [profile.foo.build-override] codegen-units = 6 [profile.foo.package.dep] codegen-units = 7 [profile.middle] inherits = "bar" codegen-units = 3 [profile.bar] inherits = "dev" codegen-units = 4 debug = 1 "#, ) .unwrap(); fs::write( paths::root().join("Cargo.toml"), r#" cargo-features = ['named-profiles'] [workspace] [profile.middle] inherits = "bar" codegen-units = 1 opt-level = 1 [profile.middle.package.dep] overflow-checks = false [profile.foo.build-override] codegen-units = 5 debug-assertions = false [profile.foo.package.dep] codegen-units = 8 "#, ) .unwrap(); let config = ConfigBuilder::new().nightly_features_allowed(true).build(); let profile_name = InternedString::new("foo"); let ws = Workspace::new(&paths::root().join("Cargo.toml"), &config).unwrap(); let profiles = Profiles::new(&ws, profile_name).unwrap(); let crates_io = cargo::core::source::SourceId::crates_io(&config).unwrap(); let a_pkg = PackageId::new("a", "0.1.0", crates_io).unwrap(); let dep_pkg = PackageId::new("dep", "0.1.0", crates_io).unwrap(); // normal package let mode = CompileMode::Build; let kind = CompileKind::Host; let p = profiles.get_profile(a_pkg, true, true, UnitFor::new_normal(), mode, kind); assert_eq!(p.name, "foo"); assert_eq!(p.codegen_units, Some(2)); // "foo" from config assert_eq!(p.opt_level, "1"); // "middle" from manifest assert_eq!(p.debuginfo, Some(1)); // "bar" from config assert_eq!(p.debug_assertions, true); // "dev" built-in (ignore build-override) assert_eq!(p.overflow_checks, true); // "dev" built-in (ignore package override) // build-override let bo = profiles.get_profile(a_pkg, true, true, UnitFor::new_host(false), mode, kind); assert_eq!(bo.name, "foo"); assert_eq!(bo.codegen_units, Some(6)); // "foo" build override from config assert_eq!(bo.opt_level, "0"); // default to zero assert_eq!(bo.debuginfo, Some(1)); // SAME as normal assert_eq!(bo.debug_assertions, false); // "foo" build override from manifest assert_eq!(bo.overflow_checks, true); // SAME as normal // package overrides let po = profiles.get_profile(dep_pkg, false, true, UnitFor::new_normal(), mode, kind); assert_eq!(po.name, "foo"); assert_eq!(po.codegen_units, Some(7)); // "foo" package override from config assert_eq!(po.opt_level, "1"); // SAME as normal assert_eq!(po.debuginfo, Some(1)); // SAME as normal assert_eq!(po.debug_assertions, true); // SAME as normal assert_eq!(po.overflow_checks, false); // "middle" package override from manifest } #[cargo_test] fn named_env_profile() { // Environment variables used to define a named profile. let p = project() .file( "Cargo.toml", r#" cargo-features = ["named-profiles"] [package] name = "foo" version = "0.1.0" "#, ) .file("src/lib.rs", "") .build(); p.cargo("build -v -Zunstable-options --profile=other") .masquerade_as_nightly_cargo() .env("CARGO_PROFILE_OTHER_CODEGEN_UNITS", "1") .env("CARGO_PROFILE_OTHER_INHERITS", "dev") .with_stderr_contains("[..]-C codegen-units=1 [..]") .run(); } #[cargo_test] fn test_with_dev_profile() { // `cargo test` uses "dev" profile for dependencies. Package::new("somedep", "1.0.0").publish(); let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [dependencies] somedep = "1.0" "#, ) .file("src/lib.rs", "") .build(); p.cargo("test --lib --no-run -v") .env("CARGO_PROFILE_DEV_DEBUG", "0")
"\ [UPDATING] [..] [DOWNLOADING] [..] [DOWNLOADED] [..] [COMPILING] somedep v1.0.0 [RUNNING] `rustc --crate-name somedep [..]-C debuginfo=0[..] [COMPILING] foo v0.1.0 [..] [RUNNING] `rustc --crate-name foo [..]-C debuginfo=2[..] [FINISHED] [..] ", ) .run(); }
.with_stderr(
Job.js
const Database = require("../db/config"); /* let data = [ { id: 1, name: "Pizzaria Guloso", "daily-hours": 2, "total-hours": 1, created_at: Date.now(), }, { id: 2, name: "OneTwo Project", "daily-hours": 3, "total-hours": 47, created_at: Date.now(),
*/ module.exports = { async get() { const db = await Database(); // db.all traz todos os dados const jobs = await db.all(`SELECT * FROM jobs`); await db.close(); // usando o map para normalizar todos os dados do array que veio dos jobs return jobs.map((job) => ({ id: job.id, name: job.name, "daily-hours": job.daily_hours, "total-hours": job.total_hours, created_at: job.created_at, })); }, async create(newJob) { // data.push(newJob); const db = await Database(); // inserindo o novo job no db await db.run(`INSERT INTO jobs ( name, daily_hours, total_hours, created_at ) VALUES ( "${newJob.name}", ${newJob["daily-hours"]}, ${newJob["total-hours"]}, ${newJob.created_at} )`); await db.close(); }, async update(updatedJob, jobId) { // data = newJob; const db = await Database(); await db.run(`UPDATE jobs SET name = "${updatedJob.name}", daily_hours = ${updatedJob["daily-hours"]}, total_hours = ${updatedJob["total-hours"]} WHERE id = ${jobId} `); await db.close(); }, async delete(id) { // data = data.filter((job) => Number(job.id) !== Number(id)); const db = await Database(); // excluindo o job que tiver o mesmo id que veio como parâmetro para função await db.run(`DELETE FROM jobs WHERE id = ${id}`); await db.close(); }, };
}, ];
test_licm.rs
//! Test command for testing the LICM pass. //! //! The `licm` test command runs each function through the LICM pass after ensuring //! that all instructions are legal for the target. //! //! The resulting function is sent to `filecheck`. use cretonne::ir::Function; use cretonne; use cretonne::print_errors::pretty_error; use cton_reader::TestCommand; use subtest::{SubTest, Context, Result, run_filecheck}; use std::borrow::Cow; use std::fmt::Write; struct
; pub fn subtest(parsed: &TestCommand) -> Result<Box<SubTest>> { assert_eq!(parsed.command, "licm"); if !parsed.options.is_empty() { Err(format!("No options allowed on {}", parsed)) } else { Ok(Box::new(TestLICM)) } } impl SubTest for TestLICM { fn name(&self) -> Cow<str> { Cow::from("licm") } fn is_mutating(&self) -> bool { true } fn run(&self, func: Cow<Function>, context: &Context) -> Result<()> { // Create a compilation context, and drop in the function. let mut comp_ctx = cretonne::Context::new(); comp_ctx.func = func.into_owned(); comp_ctx.flowgraph(); comp_ctx.compute_loop_analysis(); comp_ctx.licm(context.flags_or_isa()).map_err(|e| { pretty_error(&comp_ctx.func, context.isa, Into::into(e)) })?; let mut text = String::new(); write!(&mut text, "{}", &comp_ctx.func).map_err( |e| e.to_string(), )?; run_filecheck(&text, context) } }
TestLICM
jk.py
# a Python object (dict): x = { "name": "John", "age": 30, "city": "New York" } # convert into JSON: y = json.dumps(x) # the result is a JSON string: print(y)
import json
register.go
// Copyright 2013 The lime Authors. // Use of this source code is governed by a 2-clause // BSD-style license that can be found in the LICENSE file. package commands import ( "code.google.com/p/log4go" "github.com/limetext/lime/backend" ) type cmd struct { name string cmd backend.Command } func register(cmds []cmd) { e := backend.GetEditor() for i := range cmds { if err := e.CommandHandler().Register(cmds[i].name, cmds[i].cmd); err != nil {
log4go.Error("Failed to register command %s: %s", cmds[i].name, err) } } }
py_io.rs
use crate::builtins::bytes::PyBytes; use crate::builtins::pystr::PyStr; use crate::exceptions::PyBaseExceptionRef; use crate::VirtualMachine; use crate::{PyObjectRef, PyResult}; use std::{fmt, io, ops}; pub trait Write { type Error; fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), Self::Error>; } #[repr(transparent)] pub struct IoWriter<T>(pub T); impl<T> IoWriter<T> { pub fn from_ref(x: &mut T) -> &mut Self { // SAFETY: IoWriter is repr(transparent) over T unsafe { &mut *(x as *mut T as *mut Self) } } } impl<T> ops::Deref for IoWriter<T> { type Target = T; fn deref(&self) -> &T { &self.0 } } impl<T> ops::DerefMut for IoWriter<T> { fn deref_mut(&mut self) -> &mut T { &mut self.0 } } impl<W> Write for IoWriter<W> where W: io::Write, { type Error = io::Error; fn write_fmt(&mut self, args: fmt::Arguments) -> io::Result<()> { <W as io::Write>::write_fmt(&mut self.0, args) } } impl Write for String { type Error = fmt::Error; fn write_fmt(&mut self, args: fmt::Arguments) -> fmt::Result { <String as fmt::Write>::write_fmt(self, args) } } pub struct
<'vm>(pub PyObjectRef, pub &'vm VirtualMachine); impl Write for PyWriter<'_> { type Error = PyBaseExceptionRef; fn write_fmt(&mut self, args: fmt::Arguments) -> Result<(), Self::Error> { let PyWriter(obj, vm) = self; vm.call_method(obj, "write", (args.to_string(),)).map(drop) } } pub fn file_readline(obj: &PyObjectRef, size: Option<usize>, vm: &VirtualMachine) -> PyResult { let args = size.map_or_else(Vec::new, |size| vec![vm.ctx.new_int(size)]); let ret = vm.call_method(obj, "readline", args)?; let eof_err = || { vm.new_exception( vm.ctx.exceptions.eof_error.clone(), vec![vm.ctx.new_ascii_str(b"EOF when reading a line")], ) }; let ret = match_class!(match ret { s @ PyStr => { let sval = s.as_str(); if sval.is_empty() { return Err(eof_err()); } if let Some(nonl) = sval.strip_suffix('\n') { vm.ctx.new_utf8_str(nonl) } else { s.into_object() } } b @ PyBytes => { let buf = b.as_bytes(); if buf.is_empty() { return Err(eof_err()); } if buf.last() == Some(&b'\n') { vm.ctx.new_bytes(buf[..buf.len() - 1].to_owned()) } else { b.into_object() } } _ => return Err(vm.new_type_error("object.readline() returned non-string".to_owned())), }); Ok(ret) }
PyWriter
servicemonitor.go
package metrics import ( "fmt" "github.com/caos/boom/internal/bundle/application/applications/prometheus/servicemonitor" "github.com/caos/boom/internal/bundle/application/applications/prometheusnodeexporter/info" "github.com/caos/boom/internal/labels" ) func getLocalServiceMonitor(appName string, monitorMatchingLabels, serviceMatchingLabels map[string]string) *servicemonitor.Config
func getIngestionServiceMonitor(appName string, monitorMatchingLabels, serviceMatchingLabels map[string]string) *servicemonitor.Config { relabelings := []*servicemonitor.ConfigRelabeling{{ Action: "replace", SourceLabels: []string{"__meta_kubernetes_pod_node_name"}, TargetLabel: "instance", }, { Action: "replace", SourceLabels: []string{"job"}, TargetLabel: "job", Replacement: "caos_remote_${1}", }, { Action: "labeldrop", Regex: "(container|endpoint|namespace|pod)", }} metricRelabelings := []*servicemonitor.ConfigRelabeling{{ Action: "keep", SourceLabels: []string{ "__name__", "mode", "device", "fstype", "mountpoint", }, Regex: "(node_cpu_seconds_total;idle;;;|(node_filesystem_avail_bytes|node_filesystem_size_bytes);;rootfs;rootfs;/|(node_memory_MemAvailable_bytes|node_memory_MemTotal_bytes|node_boot_time_seconds);;;;)", }, { Action: "labelkeep", Regex: "__.+|job|instance|cpu", }, { Action: "replace", SourceLabels: []string{"__name__"}, TargetLabel: "__name__", Replacement: "dist_${1}", }} endpoint := &servicemonitor.ConfigEndpoint{ Port: "metrics", Path: "/metrics", HonorLabels: false, Relabelings: relabelings, MetricRelabelings: metricRelabelings, } return &servicemonitor.Config{ Name: "prometheus-ingestion-node-exporter-servicemonitor", Endpoints: []*servicemonitor.ConfigEndpoint{endpoint}, JobName: fmt.Sprintf("ingestion-%s", appName), MonitorMatchingLabels: monitorMatchingLabels, ServiceMatchingLabels: serviceMatchingLabels, } } func GetServicemonitors(instanceName string) []*servicemonitor.Config { appName := info.GetName() appNameStr := appName.String() monitorLabels := labels.GetMonitorLabels(instanceName, appName) ls := labels.GetApplicationLabels(appName) return []*servicemonitor.Config{ getLocalServiceMonitor(appNameStr, monitorLabels, ls), getIngestionServiceMonitor(appNameStr, monitorLabels, ls), } }
{ relabelings := make([]*servicemonitor.ConfigRelabeling, 0) relabeling := &servicemonitor.ConfigRelabeling{ Action: "replace", Regex: "(.*)", Replacement: "$1", SourceLabels: []string{"__meta_kubernetes_pod_node_name"}, TargetLabel: "instance", } relabelings = append(relabelings, relabeling) endpoint := &servicemonitor.ConfigEndpoint{ Port: "metrics", Path: "/metrics", Relabelings: relabelings, } return &servicemonitor.Config{ Name: "prometheus-local-node-exporter-servicemonitor", Endpoints: []*servicemonitor.ConfigEndpoint{endpoint}, JobName: fmt.Sprintf("local-%s", appName), MonitorMatchingLabels: monitorMatchingLabels, ServiceMatchingLabels: serviceMatchingLabels, } }
wexinSignature.py
import hashlib import random import string import time from django.core.cache import cache import requests from common.config import WECHAT_GET_JSSDK_TICKET_URL, WECHAT_GET_ACCESS_TOKEN_URL class Signature: """ Get Wechat JSSDK signature """ def __init__(self,url):
def __create_nonce_str(self): return ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(15)) def __create_timestamp(self): return int(time.time()) def sign(self): string = '&'.join(['%s=%s' % (key.lower(), self.ret[key]) for key in sorted(self.ret)]).encode('utf-8') self.ret['signature'] = hashlib.sha1(string).hexdigest() return self.ret class Base_authorization(): """ Get JSSDK ticket and accesstoken Cache to Django table cache """ @classmethod def get_ticket(cls): key = 'ticket' if cache.has_key(key): ticket = cache.get(key) else: if cache.has_key('access_token'): access_token = cache.get('access_token') else: access_token = cls.get_access_token() ticket = requests.get(WECHAT_GET_JSSDK_TICKET_URL+access_token).json()['ticket'] cache.set(key,ticket,110*60) return ticket @staticmethod def get_access_token(): key = 'access_token' access_token = requests.get(WECHAT_GET_ACCESS_TOKEN_URL).json()['access_token'] # print(access_token.text) cache.set(key,access_token,110*60) return access_token
self.ret = { 'nonceStr': self.__create_nonce_str(), 'jsapi_ticket': Base_authorization.get_ticket(), 'timestamp': self.__create_timestamp(), 'url': url }
UIPill.test.ts
import { mount } from '@vue/test-utils'; import UIPill from './UIPill.vue'; describe('UIPill', () => { it('should display correctly', () => { const wrapper = mount(UIPill, { slots: { default: 'my-string' } }); expect(wrapper.element).toMatchSnapshot(); }); it('should display the given label prop', () => { const wrapper = mount(UIPill, { props: { label: 'my-string' } }); expect(wrapper.text()).toBe('my-string'); }); it('should display the default slot', () => { const wrapper = mount(UIPill, { slots: { default: 'my-string' } });
expect(wrapper.text()).toBe('my-string'); }); });
P1.py
import numpy as np import matplotlib.pyplot as plt # Part A: Numerical Differentiation Closure def
(f,h): def inner(x): return (f(x+h) - f(x))/h return inner # Part B: f = np.log x = np.linspace(0.2, 0.4, 500) h = [1e-1, 1e-7, 1e-15] y_analytical = 1/x result = {} for i in h: y = numerical_diff(f,i)(x) result[i] = y # Plotting plt.figure(figsize = (8,5)) plt.plot(x, y_analytical, 'x-', label='Analytical Derivative') for i in h: plt.plot(x, result[i], label='Estimated derivative h = '+str(i)) plt.xlabel("X value") plt.ylabel("Derivative Value at X") plt.title("Differentiation Value at X on various h value") plt.legend() # Part C: print("Answer to Q-a: When h value is 1e-7, it most closely approximates the true derivative. \n", "When h value is too small: The approximation is jumping around stepwise and not displaying a smooth curve approximation, it amplifies floating point errors in numerical operation such as rounding and division\n", "When h value is too large: The approximation is lower than the true value, it doesn't provide a good approximation to the derivative\n") print("Answer to Q-b: Automatic differentiation avoids the problem of not choosing a good h value. \n" "The finite difference approach is quick and easy but suffers from accuracy and stability problems.\n" "Symbolic derivatives can be evaluated to machine precision, but can be costly to evaluate.\n" "Automatic differentiation (AD) overcomes both of these deficiencies. It is less costly than symbolic differentiation while evaluating derivatives to machine precision.\n" "AD uses forward or backward modes to differentiate, via Computational Graph, chain rule and evaluation trace.") # Show plot plt.show() # plt.savefig('P1_fig.png')
numerical_diff
entity_type_manager_impl.rs
use crate::api::{EntityTypeImportError, Lifecycle}; use crate::api::{ComponentManager, EntityTypeManager}; use crate::model::{EntityType, PropertyType}; use async_trait::async_trait; use indradb::Type; use rust_embed::RustEmbed; use std::fs::File; use std::io::BufReader; use std::sync::RwLock; use waiter_di::*; use log::{warn, debug, error}; #[derive(RustEmbed)] #[folder = "static/types/entity"] struct EntityTypeAsset; #[wrapper] pub struct EntityTypes(RwLock<std::vec::Vec<crate::model::EntityType>>); #[provides] fn create_external_type_dependency() -> EntityTypes { EntityTypes(RwLock::new(std::vec::Vec::new())) } #[component] pub struct EntityTypeManagerImpl { component_manager: Wrc<dyn ComponentManager>, entity_types: EntityTypes, } #[async_trait] #[provides] impl EntityTypeManager for EntityTypeManagerImpl { fn register(&self, mut entity_type: crate::model::EntityType) { debug!("Registered entity type {}", entity_type.name); // Construct the type entity_type.t = Type::new(entity_type.name.clone()).unwrap(); for component_name in entity_type.components.to_vec() { let component = self.component_manager.get(component_name.clone()); if component.is_some() { entity_type.properties .append(&mut component.unwrap().properties); } else { warn!("Entity type {} not fully initialized: No component named {}", entity_type.name.clone(), component_name); } } self.entity_types.0.write().unwrap().push(entity_type); } fn load_static_entity_types(&self) { for file in EntityTypeAsset::iter() { let filename = file.as_ref(); debug!("Loading entity type from resource {}", filename); let asset = EntityTypeAsset::get(filename).unwrap(); let result = std::str::from_utf8(asset.as_ref()); if result.is_ok() { let json_str = result.unwrap(); let entity_type: crate::model::EntityType = serde_json::from_str(json_str).unwrap(); self.register(entity_type); } else { error!("Could not decode UTF-8 {}", filename) } } } fn get_entity_types(&self) -> Vec<crate::model::EntityType> { self.entity_types.0.read().unwrap().to_vec() } fn has(&self, name: String) -> bool { self.get(name).is_some() } fn get(&self, name: String) -> Option<EntityType> { self.entity_types.0.read().unwrap() .to_vec().into_iter() .find(|entity_type| entity_type.name == name) } fn create(&self, name: String, components: Vec<String>, behaviours: Vec<String>, properties: Vec<PropertyType>) { self.register(EntityType::new( name.clone(), components.to_vec(), behaviours.to_vec(), properties.to_vec(), )); } fn delete(&self, name: String) { self.entity_types.0.write().unwrap() .retain(|entity_type| entity_type.name != name); } fn
(&self, path: String) -> Result<EntityType, EntityTypeImportError> { let file = File::open(path); if file.is_ok() { let file = file.unwrap(); let reader = BufReader::new(file); let entity_type = serde_json::from_reader(reader); if entity_type.is_ok() { let entity_type: EntityType = entity_type.unwrap(); self.register(entity_type.clone()); return Ok(entity_type.clone()); } } Err(EntityTypeImportError.into()) } fn export(&self, name: String, path: String) { let o_entity_type = self.get(name.clone()); if o_entity_type.is_some() { let r_file = File::create(path.clone()); match r_file { Ok(file) => { let result = serde_json::to_writer_pretty(&file, &o_entity_type.unwrap()); if result.is_err() { error!("Failed to export entity type {} to {}: {}", name, path, result.err().unwrap()); } } Err(error) => { error!("Failed to export entity type {} to {}: {}", name, path, error.to_string()); } } } } } impl Lifecycle for EntityTypeManagerImpl { fn init(&self) { self.load_static_entity_types(); } fn shutdown(&self) { // TODO: self.clear_entity_types(); } }
import
graph.py
from rdflib.term import Literal # required for doctests assert Literal # avoid warning from rdflib.namespace import Namespace # required for doctests assert Namespace # avoid warning from rdflib.py3compat import format_doctest_out __doc__ = format_doctest_out("""\ RDFLib defines the following kinds of Graphs: * :class:`~rdflib.graph.Graph` * :class:`~rdflib.graph.QuotedGraph` * :class:`~rdflib.graph.ConjunctiveGraph` * :class:`~rdflib.graph.Dataset` Graph ----- An RDF graph is a set of RDF triples. Graphs support the python ``in`` operator, as well as iteration and some operations like union, difference and intersection. see :class:`~rdflib.graph.Graph` Conjunctive Graph ----------------- A Conjunctive Graph is the most relevant collection of graphs that are considered to be the boundary for closed world assumptions. This boundary is equivalent to that of the store instance (which is itself uniquely identified and distinct from other instances of :class:`Store` that signify other Conjunctive Graphs). It is equivalent to all the named graphs within it and associated with a ``_default_`` graph which is automatically assigned a :class:`BNode` for an identifier - if one isn't given. see :class:`~rdflib.graph.ConjunctiveGraph` Quoted graph ------------ The notion of an RDF graph [14] is extended to include the concept of a formula node. A formula node may occur wherever any other kind of node can appear. Associated with a formula node is an RDF graph that is completely disjoint from all other graphs; i.e. has no nodes in common with any other graph. (It may contain the same labels as other RDF graphs; because this is, by definition, a separate graph, considerations of tidiness do not apply between the graph at a formula node and any other graph.) This is intended to map the idea of "{ N3-expression }" that is used by N3 into an RDF graph upon which RDF semantics is defined. see :class:`~rdflib.graph.QuotedGraph` Dataset ------- The RDF 1.1 Dataset, a small extension to the Conjunctive Graph. The primary term is "graphs in the datasets" and not "contexts with quads" so there is a separate method to set/retrieve a graph in a dataset and to operate with dataset graphs. As a consequence of this approach, dataset graphs cannot be identified with blank nodes, a name is always required (RDFLib will automatically add a name if one is not provided at creation time). This implementation includes a convenience method to directly add a single quad to a dataset graph. see :class:`~rdflib.graph.Dataset` Working with graphs =================== Instantiating Graphs with default store (IOMemory) and default identifier (a BNode): >>> g = Graph() >>> g.store.__class__ <class 'rdflib.plugins.memory.IOMemory'> >>> g.identifier.__class__ <class 'rdflib.term.BNode'> Instantiating Graphs with a IOMemory store and an identifier - <http://rdflib.net>: >>> g = Graph('IOMemory', URIRef("http://rdflib.net")) >>> g.identifier rdflib.term.URIRef(%(u)s'http://rdflib.net') >>> str(g) # doctest: +NORMALIZE_WHITESPACE "<http://rdflib.net> a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']." Creating a ConjunctiveGraph - The top level container for all named Graphs in a 'database': >>> g = ConjunctiveGraph() >>> str(g.default_context) "[a rdfg:Graph;rdflib:storage [a rdflib:Store;rdfs:label 'IOMemory']]." Adding / removing reified triples to Graph and iterating over it directly or via triple pattern: >>> g = Graph() >>> statementId = BNode() >>> print(len(g)) 0 >>> g.add((statementId, RDF.type, RDF.Statement)) >>> g.add((statementId, RDF.subject, ... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph'))) >>> g.add((statementId, RDF.predicate, RDFS.label)) >>> g.add((statementId, RDF.object, Literal("Conjunctive Graph"))) >>> print(len(g)) 4 >>> for s, p, o in g: ... print(type(s)) ... <class 'rdflib.term.BNode'> <class 'rdflib.term.BNode'> <class 'rdflib.term.BNode'> <class 'rdflib.term.BNode'> >>> for s, p, o in g.triples((None, RDF.object, None)): ... print(o) ... Conjunctive Graph >>> g.remove((statementId, RDF.type, RDF.Statement)) >>> print(len(g)) 3 ``None`` terms in calls to :meth:`~rdflib.graph.Graph.triples` can be thought of as "open variables". Graph support set-theoretic operators, you can add/subtract graphs, as well as intersection (with multiplication operator g1*g2) and xor (g1 ^ g2). Note that BNode IDs are kept when doing set-theoretic operations, this may or may not be what you want. Two named graphs within the same application probably want share BNode IDs, two graphs with data from different sources probably not. If your BNode IDs are all generated by RDFLib they are UUIDs and unique. >>> g1 = Graph() >>> g2 = Graph() >>> u = URIRef(%(u)s'http://example.com/foo') >>> g1.add([u, RDFS.label, Literal('foo')]) >>> g1.add([u, RDFS.label, Literal('bar')]) >>> g2.add([u, RDFS.label, Literal('foo')]) >>> g2.add([u, RDFS.label, Literal('bing')]) >>> len(g1 + g2) # adds bing as label 3 >>> len(g1 - g2) # removes foo 1 >>> len(g1 * g2) # only foo 1 >>> g1 += g2 # now g1 contains everything Graph Aggregation - ConjunctiveGraphs and ReadOnlyGraphAggregate within the same store: >>> store = plugin.get('IOMemory', Store)() >>> g1 = Graph(store) >>> g2 = Graph(store) >>> g3 = Graph(store) >>> stmt1 = BNode() >>> stmt2 = BNode() >>> stmt3 = BNode() >>> g1.add((stmt1, RDF.type, RDF.Statement)) >>> g1.add((stmt1, RDF.subject, ... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph'))) >>> g1.add((stmt1, RDF.predicate, RDFS.label)) >>> g1.add((stmt1, RDF.object, Literal("Conjunctive Graph"))) >>> g2.add((stmt2, RDF.type, RDF.Statement)) >>> g2.add((stmt2, RDF.subject, ... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph'))) >>> g2.add((stmt2, RDF.predicate, RDF.type)) >>> g2.add((stmt2, RDF.object, RDFS.Class)) >>> g3.add((stmt3, RDF.type, RDF.Statement)) >>> g3.add((stmt3, RDF.subject, ... URIRef(%(u)s'http://rdflib.net/store/ConjunctiveGraph'))) >>> g3.add((stmt3, RDF.predicate, RDFS.comment)) >>> g3.add((stmt3, RDF.object, Literal( ... "The top-level aggregate graph - The sum " + ... "of all named graphs within a Store"))) >>> len(list(ConjunctiveGraph(store).subjects(RDF.type, RDF.Statement))) 3 >>> len(list(ReadOnlyGraphAggregate([g1,g2]).subjects( ... RDF.type, RDF.Statement))) 2 ConjunctiveGraphs have a :meth:`~rdflib.graph.ConjunctiveGraph.quads` method which returns quads instead of triples, where the fourth item is the Graph (or subclass thereof) instance in which the triple was asserted: >>> uniqueGraphNames = set( ... [graph.identifier for s, p, o, graph in ConjunctiveGraph(store ... ).quads((None, RDF.predicate, None))]) >>> len(uniqueGraphNames) 3 >>> unionGraph = ReadOnlyGraphAggregate([g1, g2]) >>> uniqueGraphNames = set( ... [graph.identifier for s, p, o, graph in unionGraph.quads( ... (None, RDF.predicate, None))]) >>> len(uniqueGraphNames) 2 Parsing N3 from a string >>> g2 = Graph() >>> src = ''' ... @prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#> . ... @prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> . ... [ a rdf:Statement ; ... rdf:subject <http://rdflib.net/store#ConjunctiveGraph>; ... rdf:predicate rdfs:label; ... rdf:object "Conjunctive Graph" ] . ... ''' >>> g2 = g2.parse(data=src, format='n3') >>> print(len(g2)) 4 Using Namespace class: >>> RDFLib = Namespace('http://rdflib.net/') >>> RDFLib.ConjunctiveGraph rdflib.term.URIRef(%(u)s'http://rdflib.net/ConjunctiveGraph') >>> RDFLib['Graph'] rdflib.term.URIRef(%(u)s'http://rdflib.net/Graph') """) import logging logger = logging.getLogger(__name__) # import md5 import random import warnings from hashlib import md5 try: from io import BytesIO assert BytesIO except ImportError: try: from io import StringIO as BytesIO assert BytesIO except ImportError: from io import StringIO as BytesIO assert BytesIO from rdflib.namespace import RDF, RDFS, SKOS from rdflib import plugin, exceptions, query from rdflib.term import Node, URIRef, Genid from rdflib.term import BNode import rdflib.term from rdflib.paths import Path from rdflib.store import Store from rdflib.serializer import Serializer from rdflib.parser import Parser from rdflib.parser import create_input_source from rdflib.namespace import NamespaceManager from rdflib.resource import Resource from rdflib.collection import Collection from rdflib import py3compat b = py3compat.b import os import shutil import tempfile from urllib.parse import urlparse __all__ = [ 'Graph', 'ConjunctiveGraph', 'QuotedGraph', 'Seq', 'ModificationException', 'Dataset', 'UnSupportedAggregateOperation', 'ReadOnlyGraphAggregate'] class Graph(Node): """An RDF Graph The constructor accepts one argument, the 'store' that will be used to store the graph data (see the 'store' package for stores currently shipped with rdflib). Stores can be context-aware or unaware. Unaware stores take up (some) less space but cannot support features that require context, such as true merging/demerging of sub-graphs and provenance. The Graph constructor can take an identifier which identifies the Graph by name. If none is given, the graph is assigned a BNode for its identifier. For more on named graphs, see: http://www.w3.org/2004/03/trix/ """ def __init__(self, store='default', identifier=None, namespace_manager=None): super(Graph, self).__init__() self.__identifier = identifier or BNode() if not isinstance(self.__identifier, Node): self.__identifier = URIRef(self.__identifier) if not isinstance(store, Store): # TODO: error handling self.__store = store = plugin.get(store, Store)() else: self.__store = store self.__namespace_manager = namespace_manager self.context_aware = False self.formula_aware = False self.default_union = False def __get_store(self): return self.__store store = property(__get_store) # read-only attr def __get_identifier(self): return self.__identifier identifier = property(__get_identifier) # read-only attr def _get_namespace_manager(self): if self.__namespace_manager is None: self.__namespace_manager = NamespaceManager(self) return self.__namespace_manager def _set_namespace_manager(self, nm): self.__namespace_manager = nm namespace_manager = property(_get_namespace_manager, _set_namespace_manager, doc="this graph's namespace-manager") def __repr__(self): return "<Graph identifier=%s (%s)>" % (self.identifier, type(self)) def __str__(self): if isinstance(self.identifier, URIRef): return ("%s a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s'].") % ( self.identifier.n3(), self.store.__class__.__name__) else: return ("[a rdfg:Graph;rdflib:storage " + "[a rdflib:Store;rdfs:label '%s']].") % ( self.store.__class__.__name__) def toPython(self): return self def destroy(self, configuration): """Destroy the store identified by `configuration` if supported""" self.__store.destroy(configuration) # Transactional interfaces (optional) def commit(self): """Commits active transactions""" self.__store.commit() def rollback(self): """Rollback active transactions""" self.__store.rollback() def open(self, configuration, create=False): """Open the graph store Might be necessary for stores that require opening a connection to a database or acquiring some resource. """ return self.__store.open(configuration, create) def close(self, commit_pending_transaction=False): """Close the graph store Might be necessary for stores that require closing a connection to a database or releasing some resource. """ self.__store.close( commit_pending_transaction=commit_pending_transaction) def add(self, xxx_todo_changeme): """Add a triple with self as context""" (s, p, o) = xxx_todo_changeme assert isinstance(s, Node), \ "Subject %s must be an rdflib term" % (s,) assert isinstance(p, Node), \ "Predicate %s must be an rdflib term" % (p,) assert isinstance(o, Node), \ "Object %s must be an rdflib term" % (o,) self.__store.add((s, p, o), self, quoted=False) def addN(self, quads): """Add a sequence of triple with context""" self.__store.addN((s, p, o, c) for s, p, o, c in quads if isinstance(c, Graph) and c.identifier is self.identifier and _assertnode(s,p,o) ) def remove(self, xxx_todo_changeme1): """Remove a triple from the graph If the triple does not provide a context attribute, removes the triple from all contexts. """ (s, p, o) = xxx_todo_changeme1 self.__store.remove((s, p, o), context=self) def triples(self, xxx_todo_changeme2): """Generator over the triple store Returns triples that match the given triple pattern. If triple pattern does not provide a context, all contexts will be searched. """ (s, p, o) = xxx_todo_changeme2 if isinstance(p, Path): for _s, _o in p.eval(self, s, o): yield (_s, p, _o) else: for (s, p, o), cg in self.__store.triples((s, p, o), context=self): yield (s, p, o) @py3compat.format_doctest_out def __getitem__(self, item): """ A graph can be "sliced" as a shortcut for the triples method The python slice syntax is (ab)used for specifying triples. A generator over matches is returned, the returned tuples include only the parts not given >>> import rdflib >>> g = rdflib.Graph() >>> g.add((rdflib.URIRef('urn:bob'), rdflib.RDFS.label, rdflib.Literal('Bob'))) >>> list(g[rdflib.URIRef('urn:bob')]) # all triples about bob [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal(%(u)s'Bob'))] >>> list(g[:rdflib.RDFS.label]) # all label triples [(rdflib.term.URIRef(%(u)s'urn:bob'), rdflib.term.Literal(%(u)s'Bob'))] >>> list(g[::rdflib.Literal('Bob')]) # all triples with bob as object [(rdflib.term.URIRef(%(u)s'urn:bob'), rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'))] Combined with SPARQL paths, more complex queries can be written concisely: Name of all Bobs friends: g[bob : FOAF.knows/FOAF.name ] Some label for Bob: g[bob : DC.title|FOAF.name|RDFS.label] All friends and friends of friends of Bob g[bob : FOAF.knows * '+'] etc. .. versionadded:: 4.0 """ if isinstance(item, slice): s,p,o=item.start,item.stop,item.step if s is None and p is None and o is None: return self.triples((s,p,o)) elif s is None and p is None: return self.subject_predicates(o) elif s is None and o is None: return self.subject_objects(p) elif p is None and o is None: return self.predicate_objects(s) elif s is None: return self.subjects(p,o) elif p is None: return self.predicates(s,o) elif o is None: return self.objects(s,p) else: # all given return (s,p,o) in self elif isinstance(item, (Path,Node)): return self.predicate_objects(item) else: raise TypeError("You can only index a graph by a single rdflib term or path, or a slice of rdflib terms.") def __len__(self): """Returns the number of triples in the graph If context is specified then the number of triples in the context is returned instead. """ return self.__store.__len__(context=self) def __iter__(self): """Iterates over all triples in the store""" return self.triples((None, None, None)) def __contains__(self, triple): """Support for 'triple in graph' syntax""" for triple in self.triples(triple): return True return False def __hash__(self): return hash(self.identifier) def md5_term_hash(self): d = md5(str(self.identifier)) d.update("G") return d.hexdigest() def __cmp__(self, other): if other is None: return -1 elif isinstance(other, Graph): return cmp(self.identifier, other.identifier) else: # Note if None is considered equivalent to owl:Nothing # Then perhaps a graph with length 0 should be considered # equivalent to None (if compared to it)? return 1 def __eq__(self, other): return isinstance(other, Graph) \ and self.identifier == other.identifier def __lt__(self, other): return (other is None) \ or (isinstance(other, Graph) and self.identifier < other.identifier) def __le__(self, other): return self < other or self == other def __gt__(self, other): return (isinstance(other, Graph) and self.identifier > other.identifier) \ or (other is not None) def __ge__(self, other): return self > other or self == other def __iadd__(self, other): """Add all triples in Graph other to Graph. BNode IDs are not changed.""" self.addN((s, p, o, self) for s, p, o in other) return self def __isub__(self, other): """Subtract all triples in Graph other from Graph. BNode IDs are not changed.""" for triple in other: self.remove(triple) return self def __add__(self, other): """Set-theoretic union BNode IDs are not changed.""" retval = Graph() for (prefix, uri) in set( list(self.namespaces()) + list(other.namespaces())): retval.bind(prefix, uri) for x in self: retval.add(x) for y in other: retval.add(y) return retval def __mul__(self, other): """Set-theoretic intersection. BNode IDs are not changed.""" retval = Graph() for x in other: if x in self: retval.add(x) return retval def __sub__(self, other): """Set-theoretic difference. BNode IDs are not changed.""" retval = Graph() for x in self: if not x in other: retval.add(x) return retval def __xor__(self, other): """Set-theoretic XOR. BNode IDs are not changed.""" return (self - other) + (other - self) __or__ = __add__ __and__ = __mul__ # Conv. methods def set(self, triple): """Convenience method to update the value of object Remove any existing triples for subject and predicate before adding (subject, predicate, object). """ (subject, predicate, object_) = triple assert subject is not None, \ "s can't be None in .set([s,p,o]), as it would remove (*, p, *)" assert predicate is not None, \ "p can't be None in .set([s,p,o]), as it would remove (s, *, *)" self.remove((subject, predicate, None)) self.add((subject, predicate, object_)) def subjects(self, predicate=None, object=None): """A generator of subjects with the given predicate and object""" for s, p, o in self.triples((None, predicate, object)): yield s def predicates(self, subject=None, object=None): """A generator of predicates with the given subject and object""" for s, p, o in self.triples((subject, None, object)): yield p def objects(self, subject=None, predicate=None): """A generator of objects with the given subject and predicate""" for s, p, o in self.triples((subject, predicate, None)): yield o def subject_predicates(self, object=None): """A generator of (subject, predicate) tuples for the given object""" for s, p, o in self.triples((None, None, object)): yield s, p def subject_objects(self, predicate=None): """A generator of (subject, object) tuples for the given predicate""" for s, p, o in self.triples((None, predicate, None)): yield s, o def predicate_objects(self, subject=None): """A generator of (predicate, object) tuples for the given subject""" for s, p, o in self.triples((subject, None, None)): yield p, o def triples_choices(self, xxx_todo_changeme3, context=None): (subject, predicate, object_) = xxx_todo_changeme3 for (s, p, o), cg in self.store.triples_choices( (subject, predicate, object_), context=self): yield (s, p, o) def value(self, subject=None, predicate=RDF.value, object=None, default=None, any=True): """Get a value for a pair of two criteria Exactly one of subject, predicate, object must be None. Useful if one knows that there may only be one value. It is one of those situations that occur a lot, hence this 'macro' like utility Parameters: subject, predicate, object -- exactly one must be None default -- value to be returned if no values found any -- if True, return any value in the case there is more than one, else, raise UniquenessError """ retval = default if (subject is None and predicate is None) or \ (subject is None and object is None) or \ (predicate is None and object is None): return None if object is None: values = self.objects(subject, predicate) if subject is None: values = self.subjects(predicate, object) if predicate is None:
try: retval = next(values) except StopIteration: retval = default else: if any is False: try: next(values) msg = ("While trying to find a value for (%s, %s, %s) the" " following multiple values where found:\n" % (subject, predicate, object)) triples = self.store.triples( (subject, predicate, object), None) for (s, p, o), contexts in triples: msg += "(%s, %s, %s)\n (contexts: %s)\n" % ( s, p, o, list(contexts)) raise exceptions.UniquenessError(msg) except StopIteration: pass return retval def label(self, subject, default=''): """Query for the RDFS.label of the subject Return default if no label exists or any label if multiple exist. """ if subject is None: return default return self.value(subject, RDFS.label, default=default, any=True) @py3compat.format_doctest_out def preferredLabel(self, subject, lang=None, default=None, labelProperties=(SKOS.prefLabel, RDFS.label)): """ Find the preferred label for subject. By default prefers skos:prefLabels over rdfs:labels. In case at least one prefLabel is found returns those, else returns labels. In case a language string (e.g., 'en', 'de' or even '' for no lang-tagged literals) is given, only such labels will be considered. Return a list of (labelProp, label) pairs, where labelProp is either skos:prefLabel or rdfs:label. >>> from rdflib import ConjunctiveGraph, URIRef, RDFS, Literal >>> from rdflib.namespace import SKOS >>> from pprint import pprint >>> g = ConjunctiveGraph() >>> u = URIRef(%(u)s'http://example.com/foo') >>> g.add([u, RDFS.label, Literal('foo')]) >>> g.add([u, RDFS.label, Literal('bar')]) >>> pprint(sorted(g.preferredLabel(u))) [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal(%(u)s'bar')), (rdflib.term.URIRef(%(u)s'http://www.w3.org/2000/01/rdf-schema#label'), rdflib.term.Literal(%(u)s'foo'))] >>> g.add([u, SKOS.prefLabel, Literal('bla')]) >>> pprint(g.preferredLabel(u)) [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(%(u)s'bla'))] >>> g.add([u, SKOS.prefLabel, Literal('blubb', lang='en')]) >>> sorted(g.preferredLabel(u)) #doctest: +NORMALIZE_WHITESPACE [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(%(u)s'bla')), (rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(%(u)s'blubb', lang='en'))] >>> g.preferredLabel(u, lang='') #doctest: +NORMALIZE_WHITESPACE [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(%(u)s'bla'))] >>> pprint(g.preferredLabel(u, lang='en')) [(rdflib.term.URIRef(%(u)s'http://www.w3.org/2004/02/skos/core#prefLabel'), rdflib.term.Literal(%(u)s'blubb', lang='en'))] """ if default is None: default = [] # setup the language filtering if lang is not None: if lang == '': # we only want not language-tagged literals langfilter = lambda l: l.language is None else: langfilter = lambda l: l.language == lang else: # we don't care about language tags langfilter = lambda l: True for labelProp in labelProperties: labels = list(filter(langfilter, self.objects(subject, labelProp))) if len(labels) == 0: continue else: return [(labelProp, l) for l in labels] return default def comment(self, subject, default=''): """Query for the RDFS.comment of the subject Return default if no comment exists """ if subject is None: return default return self.value(subject, RDFS.comment, default=default, any=True) def items(self, list): """Generator over all items in the resource specified by list list is an RDF collection. """ chain = set([list]) while list: item = self.value(list, RDF.first) if item is not None: yield item list = self.value(list, RDF.rest) if list in chain: raise ValueError("List contains a recursive rdf:rest reference") chain.add(list) def transitiveClosure(self, func, arg, seen=None): """ Generates transitive closure of a user-defined function against the graph >>> from rdflib.collection import Collection >>> g=Graph() >>> a=BNode('foo') >>> b=BNode('bar') >>> c=BNode('baz') >>> g.add((a,RDF.first,RDF.type)) >>> g.add((a,RDF.rest,b)) >>> g.add((b,RDF.first,RDFS.label)) >>> g.add((b,RDF.rest,c)) >>> g.add((c,RDF.first,RDFS.comment)) >>> g.add((c,RDF.rest,RDF.nil)) >>> def topList(node,g): ... for s in g.subjects(RDF.rest,node): ... yield s >>> def reverseList(node,g): ... for f in g.objects(node,RDF.first): ... print(f) ... for s in g.subjects(RDF.rest,node): ... yield s >>> [rt for rt in g.transitiveClosure( ... topList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE [rdflib.term.BNode('baz'), rdflib.term.BNode('bar'), rdflib.term.BNode('foo')] >>> [rt for rt in g.transitiveClosure( ... reverseList,RDF.nil)] # doctest: +NORMALIZE_WHITESPACE http://www.w3.org/2000/01/rdf-schema#comment http://www.w3.org/2000/01/rdf-schema#label http://www.w3.org/1999/02/22-rdf-syntax-ns#type [rdflib.term.BNode('baz'), rdflib.term.BNode('bar'), rdflib.term.BNode('foo')] """ if seen is None: seen = {} elif arg in seen: return seen[arg] = 1 for rt in func(arg, self): yield rt for rt_2 in self.transitiveClosure(func, rt, seen): yield rt_2 def transitive_objects(self, subject, property, remember=None): """Transitively generate objects for the ``property`` relationship Generated objects belong to the depth first transitive closure of the ``property`` relationship starting at ``subject``. """ if remember is None: remember = {} if subject in remember: return remember[subject] = 1 yield subject for object in self.objects(subject, property): for o in self.transitive_objects(object, property, remember): yield o def transitive_subjects(self, predicate, object, remember=None): """Transitively generate objects for the ``property`` relationship Generated objects belong to the depth first transitive closure of the ``property`` relationship starting at ``subject``. """ if remember is None: remember = {} if object in remember: return remember[object] = 1 yield object for subject in self.subjects(predicate, object): for s in self.transitive_subjects(predicate, subject, remember): yield s def seq(self, subject): """Check if subject is an rdf:Seq If yes, it returns a Seq class instance, None otherwise. """ if (subject, RDF.type, RDF.Seq) in self: return Seq(self, subject) else: return None def qname(self, uri): return self.namespace_manager.qname(uri) def compute_qname(self, uri, generate=True): return self.namespace_manager.compute_qname(uri, generate) def bind(self, prefix, namespace, override=True): """Bind prefix to namespace If override is True will bind namespace to given prefix even if namespace was already bound to a different prefix. for example: graph.bind('foaf', 'http://xmlns.com/foaf/0.1/') """ return self.namespace_manager.bind( prefix, namespace, override=override) def namespaces(self): """Generator over all the prefix, namespace tuples""" for prefix, namespace in self.namespace_manager.namespaces(): yield prefix, namespace def absolutize(self, uri, defrag=1): """Turn uri into an absolute URI if it's not one already""" return self.namespace_manager.absolutize(uri, defrag) def serialize(self, destination=None, format="xml", base=None, encoding=None, **args): """Serialize the Graph to destination If destination is None serialize method returns the serialization as a string. Format defaults to xml (AKA rdf/xml). Format support can be extended with plugins, but 'xml', 'n3', 'turtle', 'nt', 'pretty-xml', 'trix', 'trig' and 'nquads' are built in. """ serializer = plugin.get(format, Serializer)(self) if destination is None: stream = BytesIO() serializer.serialize(stream, base=base, encoding=encoding, **args) return stream.getvalue() if hasattr(destination, "write"): stream = destination serializer.serialize(stream, base=base, encoding=encoding, **args) else: location = destination scheme, netloc, path, params, _query, fragment = urlparse(location) if netloc != "": print(("WARNING: not saving as location" + "is not a local file reference")) return fd, name = tempfile.mkstemp() stream = os.fdopen(fd, "wb") serializer.serialize(stream, base=base, encoding=encoding, **args) stream.close() if hasattr(shutil, "move"): shutil.move(name, path) else: shutil.copy(name, path) os.remove(name) def parse(self, source=None, publicID=None, format=None, location=None, file=None, data=None, **args): """ Parse source adding the resulting triples to the Graph. The source is specified using one of source, location, file or data. :Parameters: - `source`: An InputSource, file-like object, or string. In the case of a string the string is the location of the source. - `location`: A string indicating the relative or absolute URL of the source. Graph's absolutize method is used if a relative location is specified. - `file`: A file-like object. - `data`: A string containing the data to be parsed. - `format`: Used if format can not be determined from source. Defaults to rdf/xml. Format support can be extended with plugins, but 'xml', 'n3', 'nt', 'trix', 'rdfa' are built in. - `publicID`: the logical URI to use as the document base. If None specified the document location is used (at least in the case where there is a document location). :Returns: - self, the graph instance. Examples: >>> my_data = ''' ... <rdf:RDF ... xmlns:rdf='http://www.w3.org/1999/02/22-rdf-syntax-ns#' ... xmlns:rdfs='http://www.w3.org/2000/01/rdf-schema#' ... > ... <rdf:Description> ... <rdfs:label>Example</rdfs:label> ... <rdfs:comment>This is really just an example.</rdfs:comment> ... </rdf:Description> ... </rdf:RDF> ... ''' >>> import tempfile >>> fd, file_name = tempfile.mkstemp() >>> f = os.fdopen(fd, 'w') >>> dummy = f.write(my_data) # Returns num bytes written on py3 >>> f.close() >>> g = Graph() >>> result = g.parse(data=my_data, format="application/rdf+xml") >>> len(g) 2 >>> g = Graph() >>> result = g.parse(location=file_name, format="application/rdf+xml") >>> len(g) 2 >>> g = Graph() >>> with open(file_name, "r") as f: ... result = g.parse(f, format="application/rdf+xml") >>> len(g) 2 >>> os.remove(file_name) """ source = create_input_source(source=source, publicID=publicID, location=location, file=file, data=data, format=format) if format is None: format = source.content_type if format is None: # raise Exception("Could not determine format for %r. You can" + \ # "expicitly specify one with the format argument." % source) format = "application/rdf+xml" parser = plugin.get(format, Parser)() try: parser.parse(source, self, **args) finally: if source.auto_close: source.close() return self def load(self, source, publicID=None, format="xml"): self.parse(source, publicID, format) def query(self, query_object, processor='sparql', result='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs): """ Query this graph. A type of 'prepared queries' can be realised by providing initial variable bindings with initBindings Initial namespaces are used to resolve prefixes used in the query, if none are given, the namespaces from the graph's namespace manager are used. :returntype: rdflib.query.QueryResult """ initBindings = initBindings or {} initNs = initNs or dict(self.namespaces()) if hasattr(self.store, "query") and use_store_provided: try: return self.store.query( query_object, initNs, initBindings, self.default_union and '__UNION__' or self.identifier, **kwargs) except NotImplementedError: pass # store has no own implementation if not isinstance(result, query.Result): result = plugin.get(result, query.Result) if not isinstance(processor, query.Processor): processor = plugin.get(processor, query.Processor)(self) return result(processor.query( query_object, initBindings, initNs, **kwargs)) def update(self, update_object, processor='sparql', initNs=None, initBindings=None, use_store_provided=True, **kwargs): """Update this graph with the given update query.""" initBindings = initBindings or {} initNs = initNs or dict(self.namespaces()) if hasattr(self.store, "update") and use_store_provided: try: return self.store.update( update_object, initNs, initBindings, self.default_union and '__UNION__' or self.identifier, **kwargs) except NotImplementedError: pass # store has no own implementation if not isinstance(processor, query.UpdateProcessor): processor = plugin.get(processor, query.UpdateProcessor)(self) return processor.update(update_object, initBindings, initNs, **kwargs) def n3(self): """return an n3 identifier for the Graph""" return "[%s]" % self.identifier.n3() def __reduce__(self): return (Graph, (self.store, self.identifier,)) def isomorphic(self, other): """ does a very basic check if these graphs are the same If no BNodes are involved, this is accurate. See rdflib.compare for a correct implementation of isomorphism checks """ # TODO: this is only an approximation. if len(self) != len(other): return False for s, p, o in self: if not isinstance(s, BNode) and not isinstance(o, BNode): if not (s, p, o) in other: return False for s, p, o in other: if not isinstance(s, BNode) and not isinstance(o, BNode): if not (s, p, o) in self: return False # TODO: very well could be a false positive at this point yet. return True def connected(self): """Check if the Graph is connected The Graph is considered undirectional. Performs a search on the Graph, starting from a random node. Then iteratively goes depth-first through the triplets where the node is subject and object. Return True if all nodes have been visited and False if it cannot continue and there are still unvisited nodes left. """ all_nodes = list(self.all_nodes()) discovered = [] # take a random one, could also always take the first one, doesn't # really matter. if not all_nodes: return False visiting = [all_nodes[random.randrange(len(all_nodes))]] while visiting: x = visiting.pop() if x not in discovered: discovered.append(x) for new_x in self.objects(subject=x): if new_x not in discovered and new_x not in visiting: visiting.append(new_x) for new_x in self.subjects(object=x): if new_x not in discovered and new_x not in visiting: visiting.append(new_x) # optimisation by only considering length, since no new objects can # be introduced anywhere. if len(all_nodes) == len(discovered): return True else: return False def all_nodes(self): res = set(self.objects()) res.update(self.subjects()) return res def collection(self, identifier): """Create a new ``Collection`` instance. Parameters: - ``identifier``: a URIRef or BNode instance. Example:: >>> graph = Graph() >>> uri = URIRef("http://example.org/resource") >>> collection = graph.collection(uri) >>> assert isinstance(collection, Collection) >>> assert collection.uri is uri >>> assert collection.graph is graph >>> collection += [ Literal(1), Literal(2) ] """ return Collection(self, identifier) def resource(self, identifier): """Create a new ``Resource`` instance. Parameters: - ``identifier``: a URIRef or BNode instance. Example:: >>> graph = Graph() >>> uri = URIRef("http://example.org/resource") >>> resource = graph.resource(uri) >>> assert isinstance(resource, Resource) >>> assert resource.identifier is uri >>> assert resource.graph is graph """ if not isinstance(identifier, Node): identifier = URIRef(identifier) return Resource(self, identifier) def _process_skolem_tuples(self, target, func): for t in self.triples((None, None, None)): target.add(func(t)) def skolemize(self, new_graph=None, bnode=None): def do_skolemize(bnode, t): (s, p, o) = t if s == bnode: s = s.skolemize() if o == bnode: o = o.skolemize() return (s, p, o) def do_skolemize2(t): (s, p, o) = t if isinstance(s, BNode): s = s.skolemize() if isinstance(o, BNode): o = o.skolemize() return (s, p, o) retval = Graph() if new_graph is None else new_graph if bnode is None: self._process_skolem_tuples(retval, do_skolemize2) elif isinstance(bnode, BNode): self._process_skolem_tuples( retval, lambda t: do_skolemize(bnode, t)) return retval def de_skolemize(self, new_graph=None, uriref=None): def do_de_skolemize(uriref, t): (s, p, o) = t if s == uriref: s = s.de_skolemize() if o == uriref: o = o.de_skolemize() return (s, p, o) def do_de_skolemize2(t): (s, p, o) = t if isinstance(s, Genid): s = s.de_skolemize() if isinstance(o, Genid): o = o.de_skolemize() return (s, p, o) retval = Graph() if new_graph is None else new_graph if uriref is None: self._process_skolem_tuples(retval, do_de_skolemize2) elif isinstance(uriref, Genid): self._process_skolem_tuples( retval, lambda t: do_de_skolemize(uriref, t)) return retval class ConjunctiveGraph(Graph): """ A ConjunctiveGraph is an (unnamed) aggregation of all the named graphs in a store. It has a ``default`` graph, whose name is associated with the graph throughout its life. :meth:`__init__` can take an identifier to use as the name of this default graph or it will assign a BNode. All methods that add triples work against this default graph. All queries are carried out against the union of all graphs. """ def __init__(self, store='default', identifier=None): super(ConjunctiveGraph, self).__init__(store, identifier=identifier) assert self.store.context_aware, ("ConjunctiveGraph must be backed by" " a context aware store.") self.context_aware = True self.default_union = True # Conjunctive! self.default_context = Graph(store=self.store, identifier=identifier or BNode()) def __str__(self): pattern = ("[a rdflib:ConjunctiveGraph;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]") return pattern % self.store.__class__.__name__ def _spoc(self, triple_or_quad, default=False): """ helper method for having methods that support either triples or quads """ if triple_or_quad is None: return (None, None, None, self.default_context if default else None) if len(triple_or_quad) == 3: c = self.default_context if default else None (s, p, o) = triple_or_quad elif len(triple_or_quad) == 4: (s, p, o, c) = triple_or_quad c = self._graph(c) return s,p,o,c def __contains__(self, triple_or_quad): """Support for 'triple/quad in graph' syntax""" s,p,o,c = self._spoc(triple_or_quad) for t in self.triples((s,p,o), context=c): return True return False def add(self, triple_or_quad): """ Add a triple or quad to the store. if a triple is given it is added to the default context """ s,p,o,c = self._spoc(triple_or_quad, default=True) _assertnode(s,p,o) self.store.add((s, p, o), context=c, quoted=False) def _graph(self, c): if c is None: return None if not isinstance(c, Graph): return self.get_context(c) else: return c def addN(self, quads): """Add a sequence of triples with context""" self.store.addN( (s, p, o, self._graph(c)) for s, p, o, c in quads if _assertnode(s, p, o) ) def remove(self, triple_or_quad): """ Removes a triple or quads if a triple is given it is removed from all contexts a quad is removed from the given context only """ s,p,o,c = self._spoc(triple_or_quad) self.store.remove((s, p, o), context=c) def triples(self, triple_or_quad, context=None): """ Iterate over all the triples in the entire conjunctive graph For legacy reasons, this can take the context to query either as a fourth element of the quad, or as the explicit context keyword parameter. The kw param takes precedence. """ s,p,o,c = self._spoc(triple_or_quad) context = self._graph(context or c) if self.default_union: if context==self.default_context: context = None else: if context is None: context = self.default_context if isinstance(p, Path): if context is None: context = self for s, o in p.eval(context, s, o): yield (s, p, o) else: for (s, p, o), cg in self.store.triples((s, p, o), context=context): yield s, p, o def quads(self, triple_or_quad=None): """Iterate over all the quads in the entire conjunctive graph""" s,p,o,c = self._spoc(triple_or_quad) for (s, p, o), cg in self.store.triples((s, p, o), context=c): for ctx in cg: yield s, p, o, ctx def triples_choices(self, xxx_todo_changeme4, context=None): """Iterate over all the triples in the entire conjunctive graph""" (s, p, o) = xxx_todo_changeme4 if context is None: if not self.default_union: context=self.default_context else: context = self._graph(context) for (s1, p1, o1), cg in self.store.triples_choices((s, p, o), context=context): yield (s1, p1, o1) def __len__(self): """Number of triples in the entire conjunctive graph""" return self.store.__len__() def contexts(self, triple=None): """Iterate over all contexts in the graph If triple is specified, iterate over all contexts the triple is in. """ for context in self.store.contexts(triple): if isinstance(context, Graph): # TODO: One of these should never happen and probably # should raise an exception rather than smoothing over # the weirdness - see #225 yield context else: yield self.get_context(context) def get_context(self, identifier, quoted=False): """Return a context graph for the given identifier identifier must be a URIRef or BNode. """ return Graph(store=self.store, identifier=identifier, namespace_manager=self) def remove_context(self, context): """Removes the given context from the graph""" self.store.remove((None, None, None), context) def context_id(self, uri, context_id=None): """URI#context""" uri = uri.split("#", 1)[0] if context_id is None: context_id = "#context" return URIRef(context_id, base=uri) def parse(self, source=None, publicID=None, format="xml", location=None, file=None, data=None, **args): """ Parse source adding the resulting triples to its own context (sub graph of this graph). See :meth:`rdflib.graph.Graph.parse` for documentation on arguments. :Returns: The graph into which the source was parsed. In the case of n3 it returns the root context. """ source = create_input_source( source=source, publicID=publicID, location=location, file=file, data=data, format=format) g_id = publicID and publicID or source.getPublicId() if not isinstance(g_id, Node): g_id = URIRef(g_id) context = Graph(store=self.store, identifier=g_id) context.remove((None, None, None)) # hmm ? context.parse(source, publicID=publicID, format=format, **args) return context def __reduce__(self): return (ConjunctiveGraph, (self.store, self.identifier)) DATASET_DEFAULT_GRAPH_ID = URIRef('urn:x-rdflib:default') class Dataset(ConjunctiveGraph): __doc__ = format_doctest_out(""" RDF 1.1 Dataset. Small extension to the Conjunctive Graph: - the primary term is graphs in the datasets and not contexts with quads, so there is a separate method to set/retrieve a graph in a dataset and operate with graphs - graphs cannot be identified with blank nodes - added a method to directly add a single quad Examples of usage: >>> # Create a new Dataset >>> ds = Dataset() >>> # simple triples goes to default graph >>> ds.add((URIRef('http://example.org/a'), ... URIRef('http://www.example.org/b'), ... Literal('foo'))) >>> >>> # Create a graph in the dataset, if the graph name has already been >>> # used, the corresponding graph will be returned >>> # (ie, the Dataset keeps track of the constituent graphs) >>> g = ds.graph(URIRef('http://www.example.com/gr')) >>> >>> # add triples to the new graph as usual >>> g.add( ... (URIRef('http://example.org/x'), ... URIRef('http://example.org/y'), ... Literal('bar')) ) >>> # alternatively: add a quad to the dataset -> goes to the graph >>> ds.add( ... (URIRef('http://example.org/x'), ... URIRef('http://example.org/z'), ... Literal('foo-bar'),g) ) >>> >>> # querying triples return them all regardless of the graph >>> for t in ds.triples((None,None,None)): # doctest: +SKIP ... print(t) # doctest: +NORMALIZE_WHITESPACE (rdflib.term.URIRef(%(u)s'http://example.org/a'), rdflib.term.URIRef(%(u)s'http://www.example.org/b'), rdflib.term.Literal(%(u)s'foo')) (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/z'), rdflib.term.Literal(%(u)s'foo-bar')) (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/y'), rdflib.term.Literal(%(u)s'bar')) >>> >>> # querying quads return quads; the fourth argument can be unrestricted >>> # or restricted to a graph >>> for q in ds.quads((None, None, None, None)): # doctest: +SKIP ... print(q) # doctest: +NORMALIZE_WHITESPACE (rdflib.term.URIRef(%(u)s'http://example.org/a'), rdflib.term.URIRef(%(u)s'http://www.example.org/b'), rdflib.term.Literal(%(u)s'foo'), None) (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/y'), rdflib.term.Literal(%(u)s'bar'), rdflib.term.URIRef(%(u)s'http://www.example.com/gr')) (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/z'), rdflib.term.Literal(%(u)s'foo-bar'), rdflib.term.URIRef(%(u)s'http://www.example.com/gr')) >>> >>> for q in ds.quads((None,None,None,g)): # doctest: +SKIP ... print(q) # doctest: +NORMALIZE_WHITESPACE (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/y'), rdflib.term.Literal(%(u)s'bar'), rdflib.term.URIRef(%(u)s'http://www.example.com/gr')) (rdflib.term.URIRef(%(u)s'http://example.org/x'), rdflib.term.URIRef(%(u)s'http://example.org/z'), rdflib.term.Literal(%(u)s'foo-bar'), rdflib.term.URIRef(%(u)s'http://www.example.com/gr')) >>> # Note that in the call above - >>> # ds.quads((None,None,None,'http://www.example.com/gr')) >>> # would have been accepted, too >>> >>> # graph names in the dataset can be queried: >>> for c in ds.graphs(): # doctest: +SKIP ... print(c) # doctest: DEFAULT http://www.example.com/gr >>> # A graph can be created without specifying a name; a skolemized genid >>> # is created on the fly >>> h = ds.graph() >>> for c in ds.graphs(): # doctest: +SKIP ... print(c) # doctest: +NORMALIZE_WHITESPACE +ELLIPSIS DEFAULT http://rdlib.net/.well-known/genid/rdflib/N... http://www.example.com/gr >>> # Note that the Dataset.graphs() call returns names of empty graphs, >>> # too. This can be restricted: >>> for c in ds.graphs(empty=False): # doctest: +SKIP ... print(c) # doctest: +NORMALIZE_WHITESPACE DEFAULT http://www.example.com/gr >>> >>> # a graph can also be removed from a dataset via ds.remove_graph(g) .. versionadded:: 4.0 """) def __init__(self, store='default', default_union=False): super(Dataset, self).__init__(store=store, identifier=None) if not self.store.graph_aware: raise Exception("DataSet must be backed by a graph-aware store!") self.default_context = Graph(store=self.store, identifier=DATASET_DEFAULT_GRAPH_ID) self.default_union = default_union def __str__(self): pattern = ("[a rdflib:Dataset;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']]") return pattern % self.store.__class__.__name__ def graph(self, identifier=None): if identifier is None: from rdflib.term import rdflib_skolem_genid self.bind( "genid", "http://rdflib.net" + rdflib_skolem_genid, override=False) identifier = BNode().skolemize() g = self._graph(identifier) self.store.add_graph(g) return g def parse(self, source=None, publicID=None, format="xml", location=None, file=None, data=None, **args): c = ConjunctiveGraph.parse(self, source, publicID, format, location, file, data, **args) self.graph(c) return c def add_graph(self, g): """alias of graph for consistency""" return self.graph(g) def remove_graph(self, g): if not isinstance(g, Graph): g = self.get_context(g) self.store.remove_graph(g) if g is None or g == self.default_context: # default graph cannot be removed # only triples deleted, so add it back in self.store.add_graph(self.default_context) def contexts(self, triple=None): default = False for c in super(Dataset, self).contexts(triple): default |= c.identifier == DATASET_DEFAULT_GRAPH_ID yield c if not default: yield self.graph(DATASET_DEFAULT_GRAPH_ID) graphs = contexts def quads(self, quad): for s, p, o, c in super(Dataset, self).quads(quad): if c.identifier==self.default_context: yield (s, p, o, None) else: yield (s, p, o, c.identifier) class QuotedGraph(Graph): """ Quoted Graphs are intended to implement Notation 3 formulae. They are associated with a required identifier that the N3 parser *must* provide in order to maintain consistent formulae identification for scenarios such as implication and other such processing. """ def __init__(self, store, identifier): super(QuotedGraph, self).__init__(store, identifier) def add(self, xxx_todo_changeme5): """Add a triple with self as context""" (s, p, o) = xxx_todo_changeme5 assert isinstance(s, Node), \ "Subject %s must be an rdflib term" % (s,) assert isinstance(p, Node), \ "Predicate %s must be an rdflib term" % (p,) assert isinstance(o, Node), \ "Object %s must be an rdflib term" % (o,) self.store.add((s, p, o), self, quoted=True) def addN(self, quads): """Add a sequence of triple with context""" self.store.addN( (s, p, o, c) for s, p, o, c in quads if isinstance(c, QuotedGraph) and c.identifier is self.identifier and _assertnode(s, p, o) ) def n3(self): """Return an n3 identifier for the Graph""" return "{%s}" % self.identifier.n3() def __str__(self): identifier = self.identifier.n3() label = self.store.__class__.__name__ pattern = ("{this rdflib.identifier %s;rdflib:storage " "[a rdflib:Store;rdfs:label '%s']}") return pattern % (identifier, label) def __reduce__(self): return (QuotedGraph, (self.store, self.identifier)) # Make sure QuotedGraph is ordered correctly # wrt to other Terms. # this must be done here, as the QuotedGraph cannot be # circularily imported in term.py rdflib.term._ORDERING[QuotedGraph]=11 class Seq(object): """Wrapper around an RDF Seq resource It implements a container type in Python with the order of the items returned corresponding to the Seq content. It is based on the natural ordering of the predicate names _1, _2, _3, etc, which is the 'implementation' of a sequence in RDF terms. """ def __init__(self, graph, subject): """Parameters: - graph: the graph containing the Seq - subject: the subject of a Seq. Note that the init does not check whether this is a Seq, this is done in whoever creates this instance! """ _list = self._list = list() LI_INDEX = URIRef(str(RDF) + "_") for (p, o) in graph.predicate_objects(subject): if p.startswith(LI_INDEX): # != RDF.Seq: # i = int(p.replace(LI_INDEX, '')) _list.append((i, o)) # here is the trick: the predicates are _1, _2, _3, etc. Ie, # by sorting the keys (by integer) we have what we want! _list.sort() def toPython(self): return self def __iter__(self): """Generator over the items in the Seq""" for _, item in self._list: yield item def __len__(self): """Length of the Seq""" return len(self._list) def __getitem__(self, index): """Item given by index from the Seq""" index, item = self._list.__getitem__(index) return item class ModificationException(Exception): def __init__(self): pass def __str__(self): return ("Modifications and transactional operations not allowed on " "ReadOnlyGraphAggregate instances") class UnSupportedAggregateOperation(Exception): def __init__(self): pass def __str__(self): return ("This operation is not supported by ReadOnlyGraphAggregate " "instances") class ReadOnlyGraphAggregate(ConjunctiveGraph): """Utility class for treating a set of graphs as a single graph Only read operations are supported (hence the name). Essentially a ConjunctiveGraph over an explicit subset of the entire store. """ def __init__(self, graphs, store='default'): if store is not None: super(ReadOnlyGraphAggregate, self).__init__(store) Graph.__init__(self, store) self.__namespace_manager = None assert isinstance(graphs, list) \ and graphs \ and [g for g in graphs if isinstance(g, Graph)], \ "graphs argument must be a list of Graphs!!" self.graphs = graphs def __repr__(self): return "<ReadOnlyGraphAggregate: %s graphs>" % len(self.graphs) def destroy(self, configuration): raise ModificationException() # Transactional interfaces (optional) def commit(self): raise ModificationException() def rollback(self): raise ModificationException() def open(self, configuration, create=False): # TODO: is there a use case for this method? for graph in self.graphs: graph.open(self, configuration, create) def close(self): for graph in self.graphs: graph.close() def add(self, xxx_todo_changeme6): (s, p, o) = xxx_todo_changeme6 raise ModificationException() def addN(self, quads): raise ModificationException() def remove(self, xxx_todo_changeme7): (s, p, o) = xxx_todo_changeme7 raise ModificationException() def triples(self, xxx_todo_changeme8): (s, p, o) = xxx_todo_changeme8 for graph in self.graphs: if isinstance(p, Path): for s, o in p.eval(self, s, o): yield s, p, o else: for s1, p1, o1 in graph.triples((s, p, o)): yield (s1, p1, o1) def __contains__(self, triple_or_quad): context = None if len(triple_or_quad) == 4: context = triple_or_quad[3] for graph in self.graphs: if context is None or graph.identifier == context.identifier: if triple_or_quad[:3] in graph: return True return False def quads(self, xxx_todo_changeme9): """Iterate over all the quads in the entire aggregate graph""" (s, p, o) = xxx_todo_changeme9 for graph in self.graphs: for s1, p1, o1 in graph.triples((s, p, o)): yield (s1, p1, o1, graph) def __len__(self): return sum(len(g) for g in self.graphs) def __hash__(self): raise UnSupportedAggregateOperation() def __cmp__(self, other): if other is None: return -1 elif isinstance(other, Graph): return -1 elif isinstance(other, ReadOnlyGraphAggregate): return cmp(self.graphs, other.graphs) else: return -1 def __iadd__(self, other): raise ModificationException() def __isub__(self, other): raise ModificationException() # Conv. methods def triples_choices(self, xxx_todo_changeme10, context=None): (subject, predicate, object_) = xxx_todo_changeme10 for graph in self.graphs: choices = graph.triples_choices((subject, predicate, object_)) for (s, p, o) in choices: yield (s, p, o) def qname(self, uri): if hasattr(self, 'namespace_manager') and self.namespace_manager: return self.namespace_manager.qname(uri) raise UnSupportedAggregateOperation() def compute_qname(self, uri, generate=True): if hasattr(self, 'namespace_manager') and self.namespace_manager: return self.namespace_manager.compute_qname(uri, generate) raise UnSupportedAggregateOperation() def bind(self, prefix, namespace, override=True): raise UnSupportedAggregateOperation() def namespaces(self): if hasattr(self, 'namespace_manager'): for prefix, namespace in self.namespace_manager.namespaces(): yield prefix, namespace else: for graph in self.graphs: for prefix, namespace in graph.namespaces(): yield prefix, namespace def absolutize(self, uri, defrag=1): raise UnSupportedAggregateOperation() def parse(self, source, publicID=None, format="xml", **args): raise ModificationException() def n3(self): raise UnSupportedAggregateOperation() def __reduce__(self): raise UnSupportedAggregateOperation() def _assertnode(*terms): for t in terms: assert isinstance(t, Node), \ 'Term %s must be an rdflib term' % (t,) return True def test(): import doctest doctest.testmod() if __name__ == '__main__': test()
values = self.predicates(subject, object)
version.rs
mod utils; use std::str; use clap::{App, AppSettings, Arg, ErrorKind}; fn common() -> App<'static> { App::new("foo") } fn with_version() -> App<'static> { common().version("3.0") } fn with_long_version() -> App<'static> { common().long_version("3.0 (abcdefg)") } fn with_subcommand() -> App<'static> { with_version().subcommand(App::new("bar").subcommand(App::new("baz"))) } #[test] fn no_version_flag_short() { let res = common().try_get_matches_from("foo -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, clap::ErrorKind::UnknownArgument); assert_eq!(err.info, ["-V"]); } #[test] fn no_version_flag_long() { let res = common().try_get_matches_from("foo --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, clap::ErrorKind::UnknownArgument); assert_eq!(err.info, ["--version"]); } #[test] fn version_flag_from_version_short() { let res = with_version().try_get_matches_from("foo -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); assert_eq!(err.to_string(), "foo 3.0\n"); } #[test] fn version_flag_from_version_long() { let res = with_version().try_get_matches_from("foo --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); assert_eq!(err.to_string(), "foo 3.0\n"); } #[test] fn version_flag_from_long_version_short() { let res = with_long_version().try_get_matches_from("foo -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); assert_eq!(err.to_string(), "foo 3.0 (abcdefg)\n"); } #[test] fn version_flag_from_long_version_long() { let res = with_long_version().try_get_matches_from("foo --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); assert_eq!(err.to_string(), "foo 3.0 (abcdefg)\n"); } #[test] fn override_version_long_with_user_flag() { let res = with_version() .arg(Arg::new("ver").long("version")) .try_get_matches_from("foo --version".split(" ")); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("ver")); } #[test] fn override_version_long_with_user_flag_no_version_flag() { let res = with_version() .arg(Arg::new("ver").long("version")) .try_get_matches_from("foo -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::UnknownArgument); } #[test] fn override_version_short_with_user_flag() { let res = with_version() .arg(Arg::new("ver").short('V')) .try_get_matches_from("foo -V".split(" ")); assert!(res.is_ok()); let m = res.unwrap(); assert!(m.is_present("ver")); } #[test] fn override_version_short_with_user_flag_long_still_works() { let res = with_version() .arg(Arg::new("ver").short('V')) .try_get_matches_from("foo --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); } #[test] fn mut_version_short() { let res = with_version() .mut_arg("version", |a| a.short('z')) .try_get_matches_from("foo -z".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); } #[test] fn mut_version_long() { let res = with_version() .mut_arg("version", |a| a.long("qux")) .try_get_matches_from("foo --qux".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); } static VERSION_ABOUT_MULTI_SC: &str = "foo-bar-baz 3.0 USAGE: foo bar baz FLAGS: -h, --help Print help information -V, --version Print custom version about text "; #[test] fn version_about_multi_subcmd() { let app = with_subcommand() .mut_arg("version", |a| a.about("Print custom version about text")) .global_setting(AppSettings::PropagateVersion); assert!(utils::compare_output( app, "foo bar baz -h", VERSION_ABOUT_MULTI_SC, false )); } #[test] fn
() { // Version Flag should not be propagated to subcommands let res = with_subcommand().try_get_matches_from("foo bar --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::UnknownArgument); assert_eq!(err.info, &["--version"]); } #[test] fn no_propagation_by_default_short() { let res = with_subcommand().try_get_matches_from("foo bar -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::UnknownArgument); assert_eq!(err.info, &["-V"]); } #[test] fn propagate_version_long() { let res = with_subcommand() .setting(AppSettings::PropagateVersion) .try_get_matches_from("foo bar --version".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); } #[test] fn propagate_version_short() { let res = with_subcommand() .setting(AppSettings::PropagateVersion) .try_get_matches_from("foo bar -V".split(" ")); assert!(res.is_err()); let err = res.unwrap_err(); assert_eq!(err.kind, ErrorKind::DisplayVersion); } #[cfg(debug_assertions)] #[test] #[should_panic = "Used App::mut_arg(\"version\", ..) without providing App::version, App::long_version or using AppSettings::NoAutoVersion"] fn mut_arg_version_panic() { let _res = common() .mut_arg("version", |v| v.short('z')) .try_get_matches_from("foo -z".split(" ")); } #[test] fn mut_arg_version_no_auto_version() { let res = common() .mut_arg("version", |v| v.short('z')) .setting(AppSettings::NoAutoVersion) .try_get_matches_from("foo -z".split(" ")); assert!(res.is_ok()); assert!(res.unwrap().is_present("version")); } #[cfg(debug_assertions)] #[test] #[should_panic = "No version information via App::version or App::long_version to propagate"] fn propagate_version_no_version_info() { let _res = common() .setting(AppSettings::PropagateVersion) .subcommand(App::new("bar")) .try_get_matches_from("foo".split(" ")); }
no_propagation_by_default_long
api_ue_reach_ind_document.go
/* * Namf_MT * * AMF Mobile Termination Service * * API version: 1.0.0 * Generated by: OpenAPI Generator (https://openapi-generator.tech) */ package Namf_MT import ( "github.com/yangalan0903/openapi" "github.com/yangalan0903/openapi/models" "context" "fmt" "io/ioutil" "net/http" "net/url" "strings" ) // Linger please var ( _ context.Context ) type UeReachIndDocumentApiService service /* UeReachIndDocumentApiService Namf_MT EnableUEReachability service Operation * @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). * @param ueContextId UE Context Identifier * @param enableUeReachabilityReqData @return models.EnableUeReachabilityRspData */ func (a *UeReachIndDocumentApiService) EnableUeReachability(ctx context.Context, ueContextId string, enableUeReachabilityReqData models.EnableUeReachabilityReqData) (models.EnableUeReachabilityRspData, *http.Response, error) { var ( localVarHTTPMethod = strings.ToUpper("Post") localVarPostBody interface{} localVarFormFileName string localVarFileName string localVarFileBytes []byte localVarReturnValue models.EnableUeReachabilityRspData ) // create path and map variables localVarPath := a.client.cfg.BasePath() + "/ue-contexts/{ueContextId}/ue-reachind" localVarPath = strings.Replace(localVarPath, "{"+"ueContextId"+"}", fmt.Sprintf("%v", ueContextId), -1) localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} localVarFormParams := url.Values{} localVarHTTPContentTypes := []string{"application/json"} localVarHeaderParams["Content-Type"] = localVarHTTPContentTypes[0] // use the first content type specified in 'consumes' // to determine the Accept header localVarHTTPHeaderAccepts := []string{"application/json", "application/problem+json"} // set Accept header localVarHTTPHeaderAccept := openapi.SelectHeaderAccept(localVarHTTPHeaderAccepts) if localVarHTTPHeaderAccept != "" { localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept } // body params localVarPostBody = &enableUeReachabilityReqData r, err := openapi.PrepareRequest(ctx, a.client.cfg, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, localVarFormFileName, localVarFileName, localVarFileBytes) if err != nil { return localVarReturnValue, nil, err } localVarHTTPResponse, err := openapi.CallAPI(a.client.cfg, r) if err != nil || localVarHTTPResponse == nil { return localVarReturnValue, localVarHTTPResponse, err } localVarBody, err := ioutil.ReadAll(localVarHTTPResponse.Body) localVarHTTPResponse.Body.Close() if err != nil { return localVarReturnValue, localVarHTTPResponse, err } apiError := openapi.GenericOpenAPIError{ RawBody: localVarBody, ErrorStatus: localVarHTTPResponse.Status, } switch localVarHTTPResponse.StatusCode { case 200: err = openapi.Deserialize(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() } return localVarReturnValue, localVarHTTPResponse, nil case 307: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 400: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 403: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 404: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 411: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 413: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 415: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 429: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 500: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 503: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil
apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError case 504: var v models.ProblemDetails err = openapi.Deserialize(&v, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) if err != nil { apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError } apiError.ErrorModel = v return localVarReturnValue, localVarHTTPResponse, apiError default: return localVarReturnValue, localVarHTTPResponse, nil } }
{ apiError.ErrorStatus = err.Error() return localVarReturnValue, localVarHTTPResponse, apiError }
machine.go
package api import ( "encoding/json" "fmt" "github.com/mitchellh/mapstructure" ) type NodeType string const ( Master NodeType = "master" Worker NodeType = "worker" LoadBalancer NodeType = "loadbalancer" ) type Machine struct { NodeType NodeType `json:"node_type" validate:"required"` Size string `json:"size" validate:"required"` Image *Image `json:"image" validate:"required"` // TODO: Could add the omitempty json tag once Terraform supports optional // object arguments. // https://github.com/hashicorp/terraform/issues/19898 ProviderSettings interface{} `json:"provider_settings"` } type MachineState struct { Machine PublicIP string PrivateIP string } type MachineFactory struct { cloudProvider CloudProvider machine *Machine imageName string } // NewMachineFactoryFromExistingMachine returns a MachineFactory which starts // with an existing Machine. This is useful when cloning or replacing a machine
machine *Machine, ) *MachineFactory { machineCopy := &Machine{ NodeType: machine.NodeType, Size: machine.Size, Image: machine.Image, } // TODO: This is very ugly. Might want to introduce a deep copy library or // just find a better way to deal with provider specific machine settings. if machine.ProviderSettings != nil { data, err := json.Marshal( machine.ProviderSettings, ) if err != nil { panic(err) } if err := json.Unmarshal( data, &machineCopy.ProviderSettings, ); err != nil { panic(err) } if err := decodeMachine(cloudProvider, machineCopy); err != nil { panic(err) } } return &MachineFactory{ cloudProvider: cloudProvider, machine: machineCopy, } } // NewMachineFactory returns a MachineFactory which is used to build a Machine. func NewMachineFactory( cloudProvider CloudProvider, nodeType NodeType, size string, ) *MachineFactory { return &MachineFactory{ cloudProvider: cloudProvider, machine: &Machine{ NodeType: nodeType, Size: size, Image: LatestImage(cloudProvider, nodeType), }, } } // WithImage sets the image of the Machine. func (f *MachineFactory) WithImage(imageName string) *MachineFactory { f.imageName = imageName return f } // WithProviderSettings sets cloud provider specific parameters on the Machine. func (f *MachineFactory) WithProviderSettings( providerSettingsMap map[string]interface{}, ) *MachineFactory { f.machine.ProviderSettings = providerSettingsMap return f } // Build returns the finished Machine. It returns an UnsupportedImageError if // the image is not supported by the cloud provider. func (f *MachineFactory) Build() (*Machine, error) { if f.imageName != "" { image, ok := LookupImage( f.cloudProvider, f.machine.NodeType, f.imageName, ) if !ok { return f.machine, NewUnsupportedImageError( f.cloudProvider.Type(), f.imageName, ) } f.machine.Image = image } if err := decodeMachine( f.cloudProvider, f.machine, ); err != nil { return f.machine, fmt.Errorf( "error decoding machine: %w", err, ) } return f.machine, nil } // MustBuild runs Build() except that it panics if there is an error. func (f *MachineFactory) MustBuild() *Machine { machine, err := f.Build() if err != nil { panic(err) } return machine } // LatestImage returns the latest supported image for the cloud provider. func LatestImage(cloudProvider CloudProvider, nodeType NodeType) *Image { images := cloudProvider.MachineImages(nodeType) return images[len(images)-1] } // LookupImage retrieves an image by name from the cloud provider. func LookupImage( cloudProvider CloudProvider, nodeType NodeType, imageName string, ) (*Image, bool) { for _, image := range cloudProvider.MachineImages(nodeType) { if imageName == image.Name { return image, true } } return nil, false } func decodeMachine( cloudProvider CloudProvider, machine *Machine, ) error { if machine.ProviderSettings == nil { return nil } providerSettings := cloudProvider.MachineSettings() if providerSettings == nil { return nil } decoder, err := mapstructure.NewDecoder(&mapstructure.DecoderConfig{ Metadata: nil, Result: providerSettings, TagName: "json", }) if err != nil { return err } if err := decoder.Decode(machine.ProviderSettings); err != nil { return fmt.Errorf("error decoding provider machine settings: %w", err) } machine.ProviderSettings = providerSettings return nil }
// and some values needs to be changed. func NewMachineFactoryFromExistingMachine( cloudProvider CloudProvider,
parser.go
package k8s import ( "fmt" "regexp" "strings" "github.com/traefik/traefik/v2/pkg/log" "k8s.io/apimachinery/pkg/runtime" "k8s.io/client-go/kubernetes/scheme" ) // MustParseYaml parses a YAML to objects. func
(content []byte) []runtime.Object { acceptedK8sTypes := regexp.MustCompile(`^(Deployment|Endpoints|Service|Ingress|IngressRoute|IngressRouteTCP|IngressRouteUDP|Middleware|MiddlewareTCP|Secret|TLSOption|TLSStore|TraefikService|IngressClass|ServersTransport|GatewayClass|Gateway|HTTPRoute|TCPRoute|TLSRoute)$`) files := strings.Split(string(content), "---") retVal := make([]runtime.Object, 0, len(files)) for _, file := range files { if file == "\n" || file == "" { continue } decode := scheme.Codecs.UniversalDeserializer().Decode obj, groupVersionKind, err := decode([]byte(file), nil, nil) if err != nil { panic(fmt.Sprintf("Error while decoding YAML object. Err was: %s", err)) } if !acceptedK8sTypes.MatchString(groupVersionKind.Kind) { log.WithoutContext().Debugf("The custom-roles configMap contained K8s object types which are not supported! Skipping object with type: %s", groupVersionKind.Kind) } else { retVal = append(retVal, obj) } } return retVal }
MustParseYaml
missing-description.js
/** * @license Copyright 2016 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ 'use strict'; const LighthouseAudit = require('../../../audits/audit.js'); class MissingDescription extends LighthouseAudit { static get meta() {
title: 'Missing description', failureTitle: 'Missing description is failing', requiredArtifacts: ['HTML'], }; } static audit(_) { return { score: 1, }; } } module.exports = MissingDescription;
return { id: 'missing-description',
RiTapeLine.d.ts
// THIS FILE IS AUTO GENERATED
export declare const RiTapeLine: IconType;
import { IconTree, IconType } from '../lib'
test_parser.rs
use nu_parser::ParseError; use nu_parser::*; use nu_protocol::{ ast::{Expr, Expression}, engine::{Command, EngineState, Stack, StateWorkingSet}, Signature, SyntaxShape, }; #[cfg(test)] #[derive(Clone)] pub struct Let; #[cfg(test)] impl Command for Let { fn name(&self) -> &str { "let" } fn usage(&self) -> &str { "Create a variable and give it a value." } fn signature(&self) -> nu_protocol::Signature { Signature::build("let") .required("var_name", SyntaxShape::VarWithOptType, "variable name") .required( "initial_value", SyntaxShape::Keyword(b"=".to_vec(), Box::new(SyntaxShape::Expression)), "equals sign followed by value", ) } fn run( &self, _engine_state: &EngineState, _stack: &mut Stack, _call: &nu_protocol::ast::Call, _input: nu_protocol::PipelineData, ) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> { todo!() } } #[test] pub fn parse_int() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"3", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Int(3), .. } )) } #[test] pub fn parse_binary_with_hex_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0x[13]", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert_eq!(expressions[0].expr, Expr::Binary(vec![0x13])) } #[test] pub fn parse_binary_with_incomplete_hex_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0x[3]", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert_eq!(expressions[0].expr, Expr::Binary(vec![0x03])) } #[test] pub fn parse_binary_with_binary_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0b[1010 1000]", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert_eq!(expressions[0].expr, Expr::Binary(vec![0b10101000])) } #[test] pub fn parse_binary_with_incomplete_binary_format() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0b[10]", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert_eq!(expressions[0].expr, Expr::Binary(vec![0b00000010])) } #[test] pub fn parse_call() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let (block, err) = parse(&mut working_set, None, b"foo", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0];
if let Expression { expr: Expr::Call(call), .. } = &expressions[0] { assert_eq!(call.decl_id, 0); } } #[test] pub fn parse_call_missing_flag_arg() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo --jazz", true, &[]); assert!(matches!(err, Some(ParseError::MissingFlagParam(..)))); } #[test] pub fn parse_call_missing_short_flag_arg() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo -j", true, &[]); assert!(matches!(err, Some(ParseError::MissingFlagParam(..)))); } #[test] pub fn parse_call_too_many_shortflag_args() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo") .named("--jazz", SyntaxShape::Int, "jazz!!", Some('j')) .named("--math", SyntaxShape::Int, "math!!", Some('m')); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo -mj", true, &[]); assert!(matches!( err, Some(ParseError::ShortFlagBatchCantTakeArg(..)) )); } #[test] pub fn parse_call_unknown_shorthand() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").switch("--jazz", "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo -mj", true, &[]); assert!(matches!(err, Some(ParseError::UnknownFlag(..)))); } #[test] pub fn parse_call_extra_positional() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").switch("--jazz", "jazz!!", Some('j')); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo -j 100", true, &[]); assert!(matches!(err, Some(ParseError::ExtraPositional(..)))); } #[test] pub fn parse_call_missing_req_positional() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").required("jazz", SyntaxShape::Int, "jazz!!"); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo", true, &[]); assert!(matches!(err, Some(ParseError::MissingPositional(..)))); } #[test] pub fn parse_call_missing_req_flag() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let sig = Signature::build("foo").required_named("--jazz", SyntaxShape::Int, "jazz!!", None); working_set.add_decl(sig.predeclare()); let (_, err) = parse(&mut working_set, None, b"foo", true, &[]); assert!(matches!(err, Some(ParseError::MissingRequiredFlag(..)))); } #[test] fn test_nothing_comparisson_eq() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"2 == $nothing", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( &expressions[0], Expression { expr: Expr::BinaryOp(..), .. } )) } #[test] fn test_nothing_comparisson_neq() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"2 != $nothing", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( &expressions[0], Expression { expr: Expr::BinaryOp(..), .. } )) } mod range { use super::*; use nu_protocol::ast::{RangeInclusion, RangeOperator}; #[test] fn parse_inclusive_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0..10", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_exclusive_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0..<10", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::RightExclusive, .. } ), .. } )) } #[test] fn parse_reverse_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"10..0", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_subexpression_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"(3 - 3)..<(8 + 2)", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::RightExclusive, .. } ), .. } )) } #[test] fn parse_variable_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Let)); let (block, err) = parse(&mut working_set, None, b"let a = 2; $a..10", true, &[]); assert!(err.is_none()); assert!(block.len() == 2); let expressions = &block[1]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_subexpression_variable_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); working_set.add_decl(Box::new(Let)); let (block, err) = parse( &mut working_set, None, b"let a = 2; $a..<($a + 10)", true, &[], ); assert!(err.is_none()); assert!(block.len() == 2); let expressions = &block[1]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::RightExclusive, .. } ), .. } )) } #[test] fn parse_right_unbounded_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"0..", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, None, RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_left_unbounded_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"..10", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( None, None, Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_negative_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"-10..-3", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), None, Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn parse_float_range() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (block, err) = parse(&mut working_set, None, b"2.0..4.0..10.0", true, &[]); assert!(err.is_none()); assert!(block.len() == 1); let expressions = &block[0]; assert!(expressions.len() == 1); assert!(matches!( expressions[0], Expression { expr: Expr::Range( Some(_), Some(_), Some(_), RangeOperator { inclusion: RangeInclusion::Inclusive, .. } ), .. } )) } #[test] fn bad_parse_does_crash() { let engine_state = EngineState::new(); let mut working_set = StateWorkingSet::new(&engine_state); let (_, err) = parse(&mut working_set, None, b"(0)..\"a\"", true, &[]); assert!(err.is_some()); } }
assert_eq!(expressions.len(), 1);
_project.py
import logging import json import os import shutil import subprocess import sys # PyArmor in the parent path PYARMOR_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), '..')) os.environ['PYARMOR_PATH'] = PYARMOR_PATH sys.path.insert(0, PYARMOR_PATH) from config import version, config_filename, capsule_filename from project import Project project_base_path = os.path.join(PYARMOR_PATH, 'projects') project_index_name = 'index.json' project_capsule_name = capsule_filename project_config_name = config_filename def call_armor(args): p = subprocess.Popen([sys.executable, 'pyarmor.py'] + list(args), cwd=PYARMOR_PATH) p.wait() if p.returncode != 0: raise RuntimeError('Call pyarmor failed, see the details in console window') def _check_trial_license(): filename = os.path.join(PYARMOR_PATH, 'license.lic') if not os.path.exists(filename): shutil.copy(os.path.join(PYARMOR_PATH, 'license.tri'), filename) return os.path.getsize(filename) == 256 def _check_project_index(): filename = os.path.join(project_base_path, project_index_name) if not os.path.exists(filename): if not os.path.exists(project_base_path): os.makedirs(project_base_path) with open(filename, 'w') as fp: json.dump(dict(counter=0, projects={}), fp) return filename def _create_default_project(**kwargs): return Project(**kwargs) def newProject(args=None): ''' >>> p = newProject() >>> p['message'] 'Project has been created' ''' filename = _check_project_index() with open(filename, 'r') as fp: pindexes = json.load(fp) counter = pindexes['counter'] + 1 name = 'project-%d' % counter path = os.path.join(project_base_path, name) if os.path.exists(path): logging.warning('Project path %s has been exists', path) else: logging.info('Make project path %s', path) os.mkdir(path) args = ['init', '--src', path, path] call_pyarmor(args) pindexes['projects'][name] = os.path.abspath(path) pindexes['counter'] = counter with open(filename, 'w') as fp: json.dump(pindexes, fp) project = Project() project.open(path) project['name'] = name project['title'] = name project['output'] = 'dist' return dict(project=project, message='Project has been created') def updateProject(args): ''' >>> p = newProject()['project'] >>> updateProject(title='My Project') 'Update project OK' ''' name = args['name'] path = os.path.join(project_base_path, name) project = Project() project.open(path) if not args['output']: args['output'] = 'dist' project._update(args) project.save(path) return 'Update project OK' def buildProject(args): ''' >>> p = newProject()['project'] >>> p['src'] = '' >>> p['output'] = os.path.join('projects', 'build') >>> buildProject(p) 'Build project OK.' ''' name = args['name'] path = os.path.join(project_base_path, name) call_pyarmor(['build', path]) return 'Build project OK.' def removeProject(args): ''' >>> p1 = newProject()['project'] >>> m = removeProject(p1) >>> m == 'Remove project %s OK' % p1['name'] True ''' filename = _check_project_index() with open(filename, 'r') as fp: pindexes = json.load(fp) name = args['name'] try: pindexes['projects'].pop(name) except KeyError: pass with open(filename, 'w') as fp: json.dump(pindexes, fp) shutil.rmtree(os.path.join(project_base_path, name)) return 'Remove project %s OK' % name def queryProject(args=None): ''' >>> r = queryProject() >>> len(r) > 1 True ''' if args is not None and args.get('name') is not None: name = args.get('name') path = os.path.join(project_base_path, name) project = Project() project.open(path) return dict(project=project, message='Got project %s' % name) filename = _check_project_index() with open(filename, 'r') as fp: pindexes = json.load(fp) result = [] for name, filename in pindexes['projects'].items(): path = os.path.join(project_base_path, name) project = Project() project.open(path) item = dict(name=name, title=project['title']) result.append(item) return result def queryVersion(args=None): ''' >>> r = queryVersion() >>> r['version'][0] == '3' True >>> r['rcode'] == '' True ''' rcode = '' if _check_trial_license() else 'PyArmor' return dict(version=version, rcode=rcode) def newLicense(args): ''' >>> p = newProject()['project'] >>> p['rcode'] = 'Curstomer-Tom' >>> a1 = newLicense(p) >>> p['expired'] = '2017-11-20' >>> a2 = newLicense(p) ''' name = args['name'] path = os.path.join(project_base_path, name) title = args['rcode'].strip() params = ['licenses', '--project', path] for opt in ('expired', 'bind_disk', 'bind_ipv4', 'bind_mac'): if args[opt]: params.extend(['--%s' % opt.replace('_', '-'), args[opt]]) params.append(title) call_pyarmor(params) output = os.path.join(path, 'licenses', title, 'license.lic') return dict(title=title, filename=output) def obfuscateScripts(args): params = ['obfuscate'] for opt in ['output']: if args[opt]: params.extend(['--%s' % opt, args[opt]]) params.append(args['entry']) call_armor(params) output = args['output'] if args['output'] \ else os.path.join(PYARMOR_PATH, 'dist') return dict(output=output) def generateLicenses(args): params = ['licenses', '--output', PYARMOR_PATH] for opt in ('expired', 'bind_disk', 'bind_ipv4', 'bind_mac'): if args[opt]: params.extend(['--%s' % opt.replace('_', '-'), args[opt]]) rcode = args['rcode'].strip()
params.append(rcode) call_armor(params) return dict(output=os.path.join( PYARMOR_PATH, 'licenses', rcode, 'license.lic')) def packObfuscatedScripts(args): params = ['pack', '--type', args['type'], args['entry']] if args['output']: params[3:3] = ['--output', args['output']] if args['setup']: params[3:3] = ['--setup', args['setup']] call_armor(params) return dict(output=args['output']) if __name__ == '__main__': import doctest doctest.testmod()
Leetcode49.py
class Solution: def groupAnagrams(self, strs): if not strs or len(strs)==0: return strs memo=dict() for i in strs: temp=self.sortString(i)
return memo.values() def sortString(self,s): sorted_s=sorted(s) return ''.join(sorted_s) if __name__ == '__main__': sol=Solution() # strs = ["eat", "tea", "tan", "ate", "nat", "bat"] strs=['',''] print(sol.groupAnagrams(strs))
if memo.get(temp): memo[temp].append(i) else: memo[temp]=[i]
feature_flags.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use indexmap::IndexSet; use interner::StringKey; use serde::Deserialize; use std::fmt::{Display, Formatter, Result}; #[derive(Debug, Deserialize, Clone)] #[serde(deny_unknown_fields)] pub struct FeatureFlags { #[serde(default)] pub enable_flight_transform: bool, pub enable_required_transform_for_prefix: Option<StringKey>, #[serde(default)] pub no_inline: NoInlineFeature, } impl Default for FeatureFlags { fn default() -> Self
} #[derive(Debug, Deserialize, Clone)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum NoInlineFeature { /// Fully disabled: developers may not use @no_inline Disabled, /// Fully enabled: developers may use @no_inline on any fragment, with or without variable definitions Enabled, /// Partially enabled: developers may only use @no_inline on the listed fragments. For now, this also /// disallows fragments with variable definitions /// NOTE that the presence of a fragment in this list only controls whether a fragment is *allowed* to /// use @no_inline: whether the fragment is inlined or not depends on whether it actually uses that /// directive. Limited { allowlist: IndexSet<StringKey> }, } impl Default for NoInlineFeature { fn default() -> Self { NoInlineFeature::Disabled } } impl NoInlineFeature { pub fn enable_for_fragment(&self, name: StringKey) -> bool { match self { NoInlineFeature::Enabled => true, NoInlineFeature::Limited { allowlist } => allowlist.contains(&name), _ => false, } } pub fn enable_fragment_variables(&self) -> bool { match self { NoInlineFeature::Enabled => true, _ => false, } } } impl Display for NoInlineFeature { fn fmt(&self, f: &mut Formatter<'_>) -> Result { match self { NoInlineFeature::Disabled => f.write_str("disabled"), NoInlineFeature::Enabled => f.write_str("enabled"), NoInlineFeature::Limited { allowlist } => { let items: Vec<_> = allowlist.iter().map(|x| x.lookup()).collect(); f.write_str("limited to: ")?; f.write_str(&items.join(", ")) } } } }
{ FeatureFlags { enable_flight_transform: false, enable_required_transform_for_prefix: None, no_inline: Default::default(), } }
base_registry.py
from typing import Dict, Any, Tuple from checkov.common.checks.base_check_registry import BaseCheckRegistry class Registry(BaseCheckRegistry): def
(self, entity: Dict[str, Any]) -> Tuple[str, str, Dict[str, Any]]: provider_type = list(entity.keys())[0] provider_name = list(entity.keys())[0] provider_configuration = entity[provider_name] return provider_type, provider_name, provider_configuration
extract_entity_details
Popup.js
import _extends from "@babel/runtime/helpers/extends"; import _objectSpread from "@babel/runtime/helpers/objectSpread"; import _classCallCheck from "@babel/runtime/helpers/classCallCheck"; import _createClass from "@babel/runtime/helpers/createClass"; import _possibleConstructorReturn from "@babel/runtime/helpers/possibleConstructorReturn"; import _getPrototypeOf from "@babel/runtime/helpers/getPrototypeOf"; import _assertThisInitialized from "@babel/runtime/helpers/assertThisInitialized"; import _inherits from "@babel/runtime/helpers/inherits"; import _defineProperty from "@babel/runtime/helpers/defineProperty"; import _isNil from "lodash/isNil"; import _merge from "lodash/merge"; import _invoke from "lodash/invoke"; import _isArray from "lodash/isArray"; import _pick from "lodash/pick"; import _includes from "lodash/includes"; import _reduce from "lodash/reduce"; import _without from "lodash/without"; import EventStack from '@semantic-ui-react/event-stack'; import cx from 'classnames'; import PropTypes from 'prop-types'; import React, { Component, createRef } from 'react'; import { Popper } from 'react-popper'; import shallowEqual from 'shallowequal'; import { eventStack, childrenUtils, customPropTypes, getElementType, getUnhandledProps, SUI, useKeyOnly, useKeyOrValueAndKey } from '../../lib'; import Portal from '../../addons/Portal'; import Ref from '../../addons/Ref'; import { placementMapping, positions, positionsMapping } from './lib/positions'; import createReferenceProxy from './lib/createReferenceProxy'; import PopupContent from './PopupContent'; import PopupHeader from './PopupHeader'; /** * A Popup displays additional information on top of a page. */ var Popup = /*#__PURE__*/ function (_Component) { _inherits(Popup, _Component); function
() { var _getPrototypeOf2; var _this; _classCallCheck(this, Popup); for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } _this = _possibleConstructorReturn(this, (_getPrototypeOf2 = _getPrototypeOf(Popup)).call.apply(_getPrototypeOf2, [this].concat(args))); _defineProperty(_assertThisInitialized(_this), "state", {}); _defineProperty(_assertThisInitialized(_this), "open", false); _defineProperty(_assertThisInitialized(_this), "triggerRef", createRef()); _defineProperty(_assertThisInitialized(_this), "getPortalProps", function () { var portalProps = {}; var _this$props = _this.props, on = _this$props.on, hoverable = _this$props.hoverable; var normalizedOn = _isArray(on) ? on : [on]; if (hoverable) { portalProps.closeOnPortalMouseLeave = true; portalProps.mouseLeaveDelay = 300; } if (_includes(normalizedOn, 'click')) { portalProps.openOnTriggerClick = true; portalProps.closeOnTriggerClick = true; portalProps.closeOnDocumentClick = true; } if (_includes(normalizedOn, 'focus')) { portalProps.openOnTriggerFocus = true; portalProps.closeOnTriggerBlur = true; } if (_includes(normalizedOn, 'hover')) { portalProps.openOnTriggerMouseEnter = true; portalProps.closeOnTriggerMouseLeave = true; // Taken from SUI: https://git.io/vPmCm portalProps.mouseLeaveDelay = 70; portalProps.mouseEnterDelay = 50; } return portalProps; }); _defineProperty(_assertThisInitialized(_this), "hideOnScroll", function (e) { _this.setState({ closed: true }); eventStack.unsub('scroll', _this.hideOnScroll, { target: window }); _this.timeoutId = setTimeout(function () { _this.setState({ closed: false }); }, 50); _this.handleClose(e); }); _defineProperty(_assertThisInitialized(_this), "handleClose", function (e) { _invoke(_this.props, 'onClose', e, _this.props); }); _defineProperty(_assertThisInitialized(_this), "handleOpen", function (e) { _invoke(_this.props, 'onOpen', e, _this.props); }); _defineProperty(_assertThisInitialized(_this), "handlePortalMount", function (e) { _invoke(_this.props, 'onMount', e, _this.props); }); _defineProperty(_assertThisInitialized(_this), "handlePortalUnmount", function (e) { _this.positionUpdate = null; _invoke(_this.props, 'onUnmount', e, _this.props); }); _defineProperty(_assertThisInitialized(_this), "renderContent", function (_ref) { var popperPlacement = _ref.placement, popperRef = _ref.ref, scheduleUpdate = _ref.scheduleUpdate, popperStyle = _ref.style; var _this$props2 = _this.props, basic = _this$props2.basic, children = _this$props2.children, className = _this$props2.className, content = _this$props2.content, hideOnScroll = _this$props2.hideOnScroll, flowing = _this$props2.flowing, header = _this$props2.header, inverted = _this$props2.inverted, size = _this$props2.size, style = _this$props2.style, wide = _this$props2.wide; var contentRestProps = _this.state.contentRestProps; _this.positionUpdate = scheduleUpdate; var classes = cx('ui', placementMapping[popperPlacement], size, useKeyOrValueAndKey(wide, 'wide'), useKeyOnly(basic, 'basic'), useKeyOnly(flowing, 'flowing'), useKeyOnly(inverted, 'inverted'), 'popup transition visible', className); var ElementType = getElementType(Popup, _this.props); var styles = _objectSpread({ // Heads up! We need default styles to get working correctly `flowing` left: 'auto', right: 'auto' }, popperStyle, style); return React.createElement(Ref, { innerRef: popperRef }, React.createElement(ElementType, _extends({}, contentRestProps, { className: classes, style: styles }), childrenUtils.isNil(children) ? React.createElement(React.Fragment, null, PopupHeader.create(header, { autoGenerateKey: false }), PopupContent.create(content, { autoGenerateKey: false })) : children, hideOnScroll && React.createElement(EventStack, { on: _this.hideOnScroll, name: "scroll", target: "window" }))); }); return _this; } _createClass(Popup, [{ key: "componentDidUpdate", value: function componentDidUpdate(prevProps) { var depsEqual = shallowEqual(this.props.popperDependencies, prevProps.popperDependencies); if (!depsEqual) { this.handleUpdate(); } } }, { key: "componentWillUnmount", value: function componentWillUnmount() { clearTimeout(this.timeoutId); } }, { key: "handleUpdate", value: function handleUpdate() { if (this.positionUpdate) this.positionUpdate(); } }, { key: "render", value: function render() { var _this$props3 = this.props, context = _this$props3.context, disabled = _this$props3.disabled, offset = _this$props3.offset, pinned = _this$props3.pinned, popperModifiers = _this$props3.popperModifiers, position = _this$props3.position, trigger = _this$props3.trigger; var _this$state = this.state, closed = _this$state.closed, portalRestProps = _this$state.portalRestProps; if (closed || disabled) return trigger; var modifiers = _merge({ arrow: { enabled: false }, flip: { enabled: !pinned }, // There are issues with `keepTogether` and `offset` // https://github.com/FezVrasta/popper.js/issues/557 keepTogether: { enabled: !!offset }, offset: { offset: offset } }, popperModifiers); var referenceElement = createReferenceProxy(_isNil(context) ? this.triggerRef : context); var mergedPortalProps = _objectSpread({}, this.getPortalProps(), portalRestProps); return React.createElement(Portal, _extends({}, mergedPortalProps, { onClose: this.handleClose, onMount: this.handlePortalMount, onOpen: this.handleOpen, onUnmount: this.handlePortalUnmount, trigger: trigger, triggerRef: this.triggerRef }), React.createElement(Popper, { modifiers: modifiers, placement: positionsMapping[position], referenceElement: referenceElement }, this.renderContent)); } }], [{ key: "getDerivedStateFromProps", value: function getDerivedStateFromProps(props, state) { if (state.closed || state.disabled) return {}; var unhandledProps = getUnhandledProps(Popup, props); var contentRestProps = _reduce(unhandledProps, function (acc, val, key) { if (!_includes(Portal.handledProps, key)) acc[key] = val; return acc; }, {}); var portalRestProps = _pick(unhandledProps, Portal.handledProps); return { contentRestProps: contentRestProps, portalRestProps: portalRestProps }; } }]); return Popup; }(Component); _defineProperty(Popup, "defaultProps", { disabled: false, offset: 0, on: 'hover', pinned: false, position: 'top left' }); _defineProperty(Popup, "Content", PopupContent); _defineProperty(Popup, "Header", PopupHeader); _defineProperty(Popup, "handledProps", ["as", "basic", "children", "className", "content", "context", "disabled", "flowing", "header", "hideOnScroll", "hoverable", "inverted", "offset", "on", "onClose", "onMount", "onOpen", "onUnmount", "pinned", "popperDependencies", "popperModifiers", "position", "size", "style", "trigger", "wide"]); export { Popup as default }; Popup.propTypes = process.env.NODE_ENV !== "production" ? { /** An element type to render as (string or function). */ as: customPropTypes.as, /** Display the popup without the pointing arrow. */ basic: PropTypes.bool, /** Primary content. */ children: PropTypes.node, /** Additional classes. */ className: PropTypes.string, /** Simple text content for the popover. */ content: customPropTypes.itemShorthand, /** Existing element the pop-up should be bound to. */ context: PropTypes.oneOfType([PropTypes.object, customPropTypes.refObject]), /** A disabled popup only renders its trigger. */ disabled: PropTypes.bool, /** A flowing Popup has no maximum width and continues to flow to fit its content. */ flowing: PropTypes.bool, /** Takes up the entire width of its offset container. */ // TODO: implement the Popup fluid layout // fluid: PropTypes.bool, /** Header displayed above the content in bold. */ header: customPropTypes.itemShorthand, /** Hide the Popup when scrolling the window. */ hideOnScroll: PropTypes.bool, /** Whether the popup should not close on hover. */ hoverable: PropTypes.bool, /** Invert the colors of the Popup. */ inverted: PropTypes.bool, /** Offset value to apply to rendered popup. Accepts the following units: * - px or unit-less, interpreted as pixels * - %, percentage relative to the length of the trigger element * - %p, percentage relative to the length of the popup element * - vw, CSS viewport width unit * - vh, CSS viewport height unit */ offset: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), /** Events triggering the popup. */ on: PropTypes.oneOfType([PropTypes.oneOf(['hover', 'click', 'focus']), PropTypes.arrayOf(PropTypes.oneOf(['hover', 'click', 'focus']))]), /** * Called when a close event happens. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onClose: PropTypes.func, /** * Called when the portal is mounted on the DOM. * * @param {null} * @param {object} data - All props. */ onMount: PropTypes.func, /** * Called when an open event happens. * * @param {SyntheticEvent} event - React's original SyntheticEvent. * @param {object} data - All props. */ onOpen: PropTypes.func, /** * Called when the portal is unmounted from the DOM. * * @param {null} * @param {object} data - All props. */ onUnmount: PropTypes.func, /** Disables automatic repositioning of the component, it will always be placed according to the position value. */ pinned: PropTypes.bool, /** Position for the popover. */ position: PropTypes.oneOf(positions), /** An object containing custom settings for the Popper.js modifiers. */ popperModifiers: PropTypes.object, /** A popup can have dependencies which update will schedule a position update. */ popperDependencies: PropTypes.array, /** Popup size. */ size: PropTypes.oneOf(_without(SUI.SIZES, 'medium', 'big', 'massive')), /** Custom Popup style. */ style: PropTypes.object, /** Element to be rendered in-place where the popup is defined. */ trigger: PropTypes.node, /** Popup width. */ wide: PropTypes.oneOfType([PropTypes.bool, PropTypes.oneOf(['very'])]) } : {};
Popup
typescript.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use crate::writer::{Prop, Writer, AST, SPREAD_KEY}; use interner::{Intern, StringKey}; use std::fmt::{Result, Write}; pub struct TypeScriptPrinter { indentation: u32, } impl Writer for TypeScriptPrinter { fn write_ast(&mut self, ast: &AST) -> String { let mut writer = String::new(); self.write(&mut writer, ast) .expect("Expected Ok result from writing TypeScript code"); writer } } impl TypeScriptPrinter { pub fn new() -> Self { Self { indentation: 0 } } fn write(&mut self, writer: &mut dyn Write, ast: &AST) -> Result { match ast { AST::Any => write!(writer, "any")?, AST::String => write!(writer, "string")?, AST::StringLiteral(literal) => self.write_string_literal(writer, *literal)?, AST::OtherEnumValue => self.write_other_string(writer)?, AST::Number => write!(writer, "number")?, AST::Boolean => write!(writer, "boolean")?, AST::Identifier(identifier) => write!(writer, "{}", identifier)?, AST::RawType(raw) => write!(writer, "{}", raw)?, AST::Union(members) => self.write_union(writer, members)?, AST::Intersection(members) => self.write_intersection(writer, members)?, AST::ReadOnlyArray(of_type) => self.write_read_only_array(writer, of_type)?, AST::Nullable(of_type) => self.write_nullable(writer, of_type)?, AST::ExactObject(props) => self.write_object(writer, props, true)?, AST::InexactObject(props) => self.write_object(writer, props, false)?, AST::Local3DPayload(document_name, selections) => { self.write_local_3d_payload(writer, *document_name, selections)? } AST::ImportType(types, from) => self.write_import_type(writer, types, from)?, AST::DeclareExportOpaqueType(alias, value) => { self.write_declare_export_opaque_type(writer, alias, value)? } AST::ExportTypeEquals(name, value) => { self.write_export_type_equals(writer, name, value)? } AST::ExportList(names) => self.write_export_list(writer, names)?, } Ok(()) } fn write_indentation(&mut self, writer: &mut dyn Write) -> Result { for _ in 0..self.indentation { write!(writer, " ")?; } Ok(()) } fn write_string_literal(&mut self, writer: &mut dyn Write, literal: StringKey) -> Result { write!(writer, "\"{}\"", literal) } fn write_other_string(&mut self, writer: &mut dyn Write) -> Result { write!(writer, r#""%other""#) } fn write_and_wrap_union(&mut self, writer: &mut dyn Write, ast: &AST) -> Result { match ast { AST::Union(members) if members.len() > 1 => { write!(writer, "(")?; self.write_union(writer, members)?; write!(writer, ")")?; } _ => { self.write(writer, ast)?; } } Ok(()) } fn write_union(&mut self, writer: &mut dyn Write, members: &[AST]) -> Result { let mut first = true; for member in members { if first { first = false; } else { write!(writer, " | ")?; } self.write(writer, member)?; } Ok(()) } fn write_intersection(&mut self, writer: &mut dyn Write, members: &[AST]) -> Result { let mut first = true; for member in members { if first { first = false; } else { write!(writer, " & ")?; } self.write_and_wrap_union(writer, member)?; } Ok(()) } fn write_read_only_array(&mut self, writer: &mut dyn Write, of_type: &AST) -> Result { write!(writer, "ReadonlyArray<")?; self.write(writer, of_type)?; write!(writer, ">") } fn write_nullable(&mut self, writer: &mut dyn Write, of_type: &AST) -> Result { let null_type = AST::RawType("null".intern()); if let AST::Union(members) = of_type { let mut new_members = Vec::with_capacity(members.len() + 1); new_members.extend_from_slice(members); new_members.push(null_type); self.write_union(writer, &*new_members)?; } else { self.write_union(writer, &*vec![of_type.clone(), null_type])?; } Ok(()) } fn write_object(&mut self, writer: &mut dyn Write, props: &[Prop], exact: bool) -> Result { if props.is_empty() { write!(writer, "{{}}")?; return Ok(()); } // Replication of babel printer oddity: objects only containing a spread // are missing a newline. if props.len() == 1 && props[0].key == *SPREAD_KEY { write!(writer, "{{}}")?; return Ok(()); } writeln!(writer, "{{")?; self.indentation += 1; let mut first = true; for prop in props { if prop.key == *SPREAD_KEY
self.write_indentation(writer)?; if let AST::OtherEnumValue = prop.value { writeln!(writer, "// This will never be '%other', but we need some")?; self.write_indentation(writer)?; writeln!( writer, "// value in case none of the concrete values match." )?; self.write_indentation(writer)?; } if prop.read_only { write!(writer, "readonly ")?; } write!(writer, "{}", prop.key)?; if match &prop.value { AST::Nullable(_) => true, _ => prop.optional, } { write!(writer, "?")?; } write!(writer, ": ")?; self.write( writer, if let AST::Nullable(value) = &prop.value { value } else { &prop.value }, )?; if first && props.len() == 1 && exact { writeln!(writer)?; } else { writeln!(writer, ",")?; } first = false; } self.indentation -= 1; self.write_indentation(writer)?; write!(writer, "}}")?; Ok(()) } fn write_local_3d_payload( &mut self, writer: &mut dyn Write, document_name: StringKey, selections: &AST, ) -> Result { write!(writer, "Local3DPayload<\"{}\", ", document_name)?; self.write(writer, selections)?; write!(writer, ">")?; Ok(()) } fn write_import_type( &mut self, writer: &mut dyn Write, types: &Vec<StringKey>, from: &StringKey, ) -> Result { write!( writer, "import {{ {} }} from \"{}\";", types .iter() .map(|t| format!("{}", t)) .collect::<Vec<_>>() .join(", "), from ) } fn write_declare_export_opaque_type( &mut self, writer: &mut dyn Write, alias: &StringKey, value: &StringKey, ) -> Result { write!( writer, "export type {} = {} & {{ _: \"{}\" }};", alias, value, alias ) } fn write_export_type_equals( &mut self, writer: &mut dyn Write, name: &StringKey, value: &AST, ) -> Result { write!(writer, "export type {} = {};", name, self.write_ast(value)) } fn write_export_list(&mut self, writer: &mut dyn Write, names: &Vec<StringKey>) -> Result { write!( writer, "export {{ {} }};", names .iter() .map(|t| format!("{}", t)) .collect::<Vec<_>>() .join(", "), ) } } #[cfg(test)] mod tests { use super::*; use interner::Intern; fn print_type(ast: &AST) -> String { TypeScriptPrinter::new().write_ast(ast) } #[test] fn scalar_types() { assert_eq!(print_type(&AST::Any), "any".to_string()); assert_eq!(print_type(&AST::String), "string".to_string()); assert_eq!(print_type(&AST::Number), "number".to_string()); } #[test] fn union_type() { assert_eq!( print_type(&AST::Union(vec![AST::String, AST::Number])), "string | number".to_string() ); } #[test] fn read_only_array_type() { assert_eq!( print_type(&AST::ReadOnlyArray(Box::new(AST::String))), "ReadonlyArray<string>".to_string() ); } #[test] fn nullable_type() { assert_eq!( print_type(&AST::Nullable(Box::new(AST::String))), "string | null".to_string() ); assert_eq!( print_type(&AST::Nullable(Box::new(AST::Union(vec![ AST::String, AST::Number, ])))), "string | number | null" ) } #[test] fn intersections() { assert_eq!( print_type(&AST::Intersection(vec![ AST::ExactObject(vec![Prop { key: "first".intern(), optional: false, read_only: false, value: AST::String }]), AST::ExactObject(vec![Prop { key: "second".intern(), optional: false, read_only: false, value: AST::Number }]), ])), r"{ first: string } & { second: number }" ); assert_eq!( print_type(&AST::Intersection(vec![ AST::Union(vec![ AST::ExactObject(vec![Prop { key: "first".intern(), optional: false, read_only: false, value: AST::String }]), AST::ExactObject(vec![Prop { key: "second".intern(), optional: false, read_only: false, value: AST::Number }]), ]), AST::ExactObject(vec![Prop { key: "third".intern(), optional: false, read_only: false, value: AST::Number }]), ],)), r"({ first: string } | { second: number }) & { third: number }" ); } #[test] fn exact_object() { assert_eq!(print_type(&AST::ExactObject(Vec::new())), r"{}".to_string()); assert_eq!( print_type(&AST::ExactObject(vec![Prop { key: "single".intern(), optional: false, read_only: false, value: AST::String, },])), r"{ single: string }" .to_string() ); assert_eq!( print_type(&AST::ExactObject(vec![ Prop { key: "foo".intern(), optional: true, read_only: false, value: AST::String, }, Prop { key: "bar".intern(), optional: false, read_only: true, value: AST::Number, }, ])), r"{ foo?: string, readonly bar: number, }" .to_string() ); } #[test] fn nested_object() { assert_eq!( print_type(&AST::ExactObject(vec![ Prop { key: "foo".intern(), optional: true, read_only: false, value: AST::ExactObject(vec![ Prop { key: "nested_foo".intern(), optional: true, read_only: false, value: AST::String, }, Prop { key: "nested_foo2".intern(), optional: false, read_only: true, value: AST::Number, }, ]), }, Prop { key: "bar".intern(), optional: false, read_only: true, value: AST::Number, }, ])), r"{ foo?: { nested_foo?: string, readonly nested_foo2: number, }, readonly bar: number, }" .to_string() ); } #[test] fn inexact_object() { assert_eq!( print_type(&AST::InexactObject(Vec::new())), "{}".to_string() ); assert_eq!( print_type(&AST::InexactObject(vec![Prop { key: "single".intern(), optional: false, read_only: false, value: AST::String, },])), r"{ single: string, }" .to_string() ); assert_eq!( print_type(&AST::InexactObject(vec![ Prop { key: "foo".intern(), optional: false, read_only: false, value: AST::String, }, Prop { key: "bar".intern(), optional: true, read_only: true, value: AST::Number, } ])), r"{ foo: string, readonly bar?: number, }" .to_string() ); } #[test] fn other_comment() { assert_eq!( print_type(&AST::ExactObject(vec![Prop { key: "with_comment".intern(), optional: false, read_only: false, value: AST::OtherEnumValue, },])), r#"{ // This will never be '%other', but we need some // value in case none of the concrete values match. with_comment: "%other" }"# .to_string() ); } }
{ continue; }
withTheme.js
import React from 'react'; import ThemeContext from '../../contexts/ThemeContext'; const withTheme = WrappedComponent => {
</ThemeContext.Consumer> ); }; }; export default withTheme;
return function WithTheme(props) { return ( <ThemeContext.Consumer> {theme => <WrappedComponent {...props} theme={theme} />}
source_id.rs
use mun_syntax::{ast, AstNode, AstPtr, SyntaxNode, SyntaxNodePtr}; use std::hash::{Hash, Hasher}; use std::marker::PhantomData; use std::sync::Arc; /// `AstId` points to an AST node in any file. /// /// It is stable across reparses, and can be used as salsa key/value. pub(crate) type AstId<N> = InFile<FileAstId<N>>; impl<N: AstNode> AstId<N> { pub fn to_node(&self, db: &dyn DefDatabase) -> N { let root = db.parse(self.file_id); db.ast_id_map(self.file_id) .get(self.value) .to_node(&root.syntax_node()) } } #[derive(Debug)] pub(crate) struct FileAstId<N: AstNode> { raw: ErasedFileAstId, _ty: PhantomData<fn() -> N>, } impl<N: AstNode> Clone for FileAstId<N> { fn clone(&self) -> FileAstId<N> { *self } } impl<N: AstNode> Copy for FileAstId<N> {} impl<N: AstNode> PartialEq for FileAstId<N> { fn eq(&self, other: &Self) -> bool { self.raw == other.raw } } impl<N: AstNode> Eq for FileAstId<N> {} impl<N: AstNode> Hash for FileAstId<N> { fn hash<H: Hasher>(&self, hasher: &mut H) { self.raw.hash(hasher); } } impl<N: AstNode> FileAstId<N> { pub(crate) fn with_file_id(self, file_id: FileId) -> AstId<N> { AstId::new(file_id, self) } } /// Maps items' `SyntaxNode`s to `ErasedFileAstId`s and back. #[derive(Debug, PartialEq, Eq, Default)] pub struct AstIdMap { arena: Arena<ErasedFileAstId, SyntaxNodePtr>, } /// An id of an AST node in a specific file. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct ErasedFileAstId(RawId); impl_arena_id!(ErasedFileAstId); impl AstIdMap { pub(crate) fn ast_id_map_query(db: &impl DefDatabase, file_id: FileId) -> Arc<AstIdMap> { let map = AstIdMap::from_source(&db.parse(file_id).tree().syntax()); Arc::new(map) } pub(crate) fn file_item_query( db: &impl DefDatabase, file_id: FileId, ast_id: ErasedFileAstId, ) -> SyntaxNode { let node = db.parse(file_id); db.ast_id_map(file_id).arena[ast_id].to_node(&node.tree().syntax()) } pub(crate) fn ast_id<N: AstNode>(&self, item: &N) -> FileAstId<N> { let ptr = SyntaxNodePtr::new(item.syntax()); let raw = match self.arena.iter().find(|(_id, i)| **i == ptr) { Some((it, _)) => it, None => panic!( "Can't find {:?} in AstIdMap:\n{:?}", item.syntax(), self.arena.iter().map(|(_id, i)| i).collect::<Vec<_>>(), ), }; FileAstId { raw, _ty: PhantomData, } } /// Constructs a new `AstIdMap` from a root SyntaxNode. /// `node` must be the root of a syntax tree. fn from_source(node: &SyntaxNode) -> AstIdMap { assert!(node.parent().is_none()); let mut res = AstIdMap::default(); // By walking the tree in bread-first order we make sure that parents // get lower ids then children. That is, adding a new child does not // change parent's id. This means that, say, adding a new function to a // trait does not change ids of top-level items, which helps caching. bfs(node, |it| { if let Some(module_item) = ast::ModuleItem::cast(it) { res.alloc(module_item.syntax()); } }); res } /// Returns the `AstPtr` of the given id. pub(crate) fn get<N: AstNode>(&self, id: FileAstId<N>) -> AstPtr<N> { self.arena[id.raw].try_cast::<N>().unwrap() } /// Constructs a new `ErasedFileAstId` from a `SyntaxNode` fn alloc(&mut self, item: &SyntaxNode) -> ErasedFileAstId { self.arena.alloc(SyntaxNodePtr::new(item)) } } /// Walks the subtree in bfs order, calling `f` for each node. fn bfs(node: &SyntaxNode, mut f: impl FnMut(SyntaxNode)) { let mut curr_layer = vec![node.clone()]; let mut next_layer = vec![]; while !curr_layer.is_empty() { curr_layer.drain(..).for_each(|node| { next_layer.extend(node.children()); f(node); }); std::mem::swap(&mut curr_layer, &mut next_layer); } }
use crate::in_file::InFile; use crate::{db::DefDatabase, Arena, FileId, RawId};
daemon_main.go
// SPDX-License-Identifier: Apache-2.0 // Copyright 2016-2021 Authors of Cilium package cmd import ( "context" "fmt" "net" "os" "path" "path/filepath" "regexp" "strings" "time" "github.com/go-openapi/loads" gops "github.com/google/gops/agent" "github.com/sirupsen/logrus" "github.com/spf13/cobra" "github.com/spf13/viper" "github.com/vishvananda/netlink" "google.golang.org/grpc" "github.com/cilium/cilium/api/v1/server" "github.com/cilium/cilium/api/v1/server/restapi" "github.com/cilium/cilium/pkg/aws/eni" "github.com/cilium/cilium/pkg/bpf" "github.com/cilium/cilium/pkg/cgroups" "github.com/cilium/cilium/pkg/common" "github.com/cilium/cilium/pkg/components" "github.com/cilium/cilium/pkg/controller" "github.com/cilium/cilium/pkg/datapath/connector" "github.com/cilium/cilium/pkg/datapath/iptables" "github.com/cilium/cilium/pkg/datapath/link" linuxdatapath "github.com/cilium/cilium/pkg/datapath/linux" "github.com/cilium/cilium/pkg/datapath/linux/ipsec" "github.com/cilium/cilium/pkg/datapath/linux/probes" linuxrouting "github.com/cilium/cilium/pkg/datapath/linux/routing" "github.com/cilium/cilium/pkg/datapath/loader" "github.com/cilium/cilium/pkg/datapath/maps" datapathOption "github.com/cilium/cilium/pkg/datapath/option" "github.com/cilium/cilium/pkg/defaults" "github.com/cilium/cilium/pkg/endpoint" "github.com/cilium/cilium/pkg/envoy" "github.com/cilium/cilium/pkg/flowdebug" "github.com/cilium/cilium/pkg/hubble/exporter/exporteroption" "github.com/cilium/cilium/pkg/hubble/observer/observeroption" "github.com/cilium/cilium/pkg/identity" ipamOption "github.com/cilium/cilium/pkg/ipam/option" "github.com/cilium/cilium/pkg/ipmasq" "github.com/cilium/cilium/pkg/k8s" "github.com/cilium/cilium/pkg/k8s/watchers" "github.com/cilium/cilium/pkg/kvstore" "github.com/cilium/cilium/pkg/labels" "github.com/cilium/cilium/pkg/labelsfilter" "github.com/cilium/cilium/pkg/loadinfo" "github.com/cilium/cilium/pkg/logging" "github.com/cilium/cilium/pkg/logging/logfields" "github.com/cilium/cilium/pkg/maglev" "github.com/cilium/cilium/pkg/maps/ctmap" "github.com/cilium/cilium/pkg/maps/ctmap/gc" "github.com/cilium/cilium/pkg/maps/lbmap" "github.com/cilium/cilium/pkg/maps/nat" "github.com/cilium/cilium/pkg/maps/neighborsmap" "github.com/cilium/cilium/pkg/maps/policymap" "github.com/cilium/cilium/pkg/metrics" monitorAPI "github.com/cilium/cilium/pkg/monitor/api" "github.com/cilium/cilium/pkg/node" nodeTypes "github.com/cilium/cilium/pkg/node/types" "github.com/cilium/cilium/pkg/option" "github.com/cilium/cilium/pkg/pidfile" "github.com/cilium/cilium/pkg/policy" "github.com/cilium/cilium/pkg/pprof" "github.com/cilium/cilium/pkg/version" wireguard "github.com/cilium/cilium/pkg/wireguard/agent" wireguardTypes "github.com/cilium/cilium/pkg/wireguard/types" ) const ( // list of supported verbose debug groups argDebugVerboseFlow = "flow" argDebugVerboseKvstore = "kvstore" argDebugVerboseEnvoy = "envoy" argDebugVerboseDatapath = "datapath" argDebugVerbosePolicy = "policy" apiTimeout = 60 * time.Second daemonSubsys = "daemon" // fatalSleep is the duration Cilium should sleep before existing in case // of a log.Fatal is issued or a CLI flag is specified but does not exist. fatalSleep = 2 * time.Second ) var ( log = logging.DefaultLogger.WithField(logfields.LogSubsys, daemonSubsys) bootstrapTimestamp = time.Now() // RootCmd represents the base command when called without any subcommands RootCmd = &cobra.Command{ Use: "cilium-agent", Short: "Run the cilium agent", Run: func(cmd *cobra.Command, args []string) { cmdRefDir := viper.GetString(option.CMDRef) if cmdRefDir != "" { genMarkdown(cmd, cmdRefDir) os.Exit(0) } // Open socket for using gops to get stacktraces of the agent. addr := fmt.Sprintf("127.0.0.1:%d", viper.GetInt(option.GopsPort)) addrField := logrus.Fields{"address": addr} if err := gops.Listen(gops.Options{ Addr: addr, ReuseSocketAddrAndPort: true, }); err != nil { log.WithError(err).WithFields(addrField).Fatal("Cannot start gops server") } log.WithFields(addrField).Info("Started gops server") bootstrapStats.earlyInit.Start() initEnv(cmd) bootstrapStats.earlyInit.End(true) runDaemon() }, } bootstrapStats = bootstrapStatistics{} ) // Execute sets up gops, installs the cleanup signal handler and invokes // the root command. This function only returns when an interrupt // signal has been received. This is intended to be called by main.main(). func Execute() { bootstrapStats.overall.Start() interruptCh := cleaner.registerSigHandler() if err := RootCmd.Execute(); err != nil { fmt.Println(err) os.Exit(1) } <-interruptCh } func skipInit(basePath string) bool { switch basePath { case components.CiliumAgentName, components.CiliumDaemonTestName: return false default: return true } } func init() { setupSleepBeforeFatal() initializeFlags() registerBootstrapMetrics() } func setupSleepBeforeFatal() { RootCmd.SetFlagErrorFunc(func(_ *cobra.Command, e error) error { time.Sleep(fatalSleep) return e }) logrus.RegisterExitHandler(func() { time.Sleep(fatalSleep) }, ) } func initializeFlags() { if skipInit(path.Base(os.Args[0])) { log.Debug("Skipping preparation of cilium-agent environment") return } cobra.OnInitialize(option.InitConfig(RootCmd, "Cilium", "ciliumd")) // Reset the help function to also exit, as we block elsewhere in interrupts // and would not exit when called with -h. oldHelpFunc := RootCmd.HelpFunc() RootCmd.SetHelpFunc(func(c *cobra.Command, a []string) { oldHelpFunc(c, a) os.Exit(0) }) flags := RootCmd.Flags() // Validators option.Config.FixedIdentityMappingValidator = option.Validator(func(val string) (string, error) { vals := strings.Split(val, "=") if len(vals) != 2 { return "", fmt.Errorf(`invalid fixed identity: expecting "<numeric-identity>=<identity-name>" got %q`, val) } ni, err := identity.ParseNumericIdentity(vals[0]) if err != nil { return "", fmt.Errorf(`invalid numeric identity %q: %s`, val, err) } if !identity.IsUserReservedIdentity(ni) { return "", fmt.Errorf(`invalid numeric identity %q: valid numeric identity is between %d and %d`, val, identity.UserReservedNumericIdentity.Uint32(), identity.MinimalNumericIdentity.Uint32()) } lblStr := vals[1] lbl := labels.ParseLabel(lblStr) if lbl.IsReservedSource() { return "", fmt.Errorf(`invalid source %q for label: %s`, labels.LabelSourceReserved, lblStr) } return val, nil }) // Env bindings flags.Int(option.AgentHealthPort, defaults.AgentHealthPort, "TCP port for agent health status API") option.BindEnv(option.AgentHealthPort) flags.Int(option.ClusterHealthPort, defaults.ClusterHealthPort, "TCP port for cluster-wide network connectivity health API") option.BindEnv(option.ClusterHealthPort) flags.StringSlice(option.AgentLabels, []string{}, "Additional labels to identify this agent") option.BindEnv(option.AgentLabels) flags.Bool(option.AllowICMPFragNeeded, defaults.AllowICMPFragNeeded, "Allow ICMP Fragmentation Needed type packets for purposes like TCP Path MTU.") option.BindEnv(option.AllowICMPFragNeeded) flags.String(option.AllowLocalhost, option.AllowLocalhostAuto, "Policy when to allow local stack to reach local endpoints { auto | always | policy }") option.BindEnv(option.AllowLocalhost) flags.Bool(option.AnnotateK8sNode, defaults.AnnotateK8sNode, "Annotate Kubernetes node") option.BindEnv(option.AnnotateK8sNode) flags.Duration(option.ARPPingRefreshPeriod, defaults.ARPBaseReachableTime, "Period for remote node ARP entry refresh (set 0 to disable)") option.BindEnv(option.ARPPingRefreshPeriod) flags.Bool(option.EnableL2NeighDiscovery, true, "Enables L2 neighbor discovery used by kube-proxy-replacement and IPsec") option.BindEnv(option.EnableL2NeighDiscovery) flags.Bool(option.AutoCreateCiliumNodeResource, defaults.AutoCreateCiliumNodeResource, "Automatically create CiliumNode resource for own node on startup") option.BindEnv(option.AutoCreateCiliumNodeResource) flags.String(option.BPFRoot, "", "Path to BPF filesystem") option.BindEnv(option.BPFRoot) flags.Bool(option.EnableBPFClockProbe, false, "Enable BPF clock source probing for more efficient tick retrieval") option.BindEnv(option.EnableBPFClockProbe) flags.String(option.CGroupRoot, "", "Path to Cgroup2 filesystem") option.BindEnv(option.CGroupRoot) flags.Bool(option.SockopsEnableName, defaults.SockopsEnable, "Enable sockops when kernel supported") option.BindEnv(option.SockopsEnableName) flags.Int(option.ClusterIDName, 0, "Unique identifier of the cluster") option.BindEnv(option.ClusterIDName) flags.String(option.ClusterName, defaults.ClusterName, "Name of the cluster") option.BindEnv(option.ClusterName) flags.String(option.ClusterMeshConfigName, "", "Path to the ClusterMesh configuration directory") option.BindEnv(option.ClusterMeshConfigName) flags.StringSlice(option.CompilerFlags, []string{}, "Extra CFLAGS for BPF compilation") flags.MarkHidden(option.CompilerFlags) option.BindEnv(option.CompilerFlags) flags.String(option.ConfigFile, "", `Configuration file (default "$HOME/ciliumd.yaml")`) option.BindEnv(option.ConfigFile) flags.String(option.ConfigDir, "", `Configuration directory that contains a file for each option`) option.BindEnv(option.ConfigDir) flags.Duration(option.ConntrackGCInterval, time.Duration(0), "Overwrite the connection-tracking garbage collection interval") option.BindEnv(option.ConntrackGCInterval) flags.BoolP(option.DebugArg, "D", false, "Enable debugging mode") option.BindEnv(option.DebugArg) flags.StringSlice(option.DebugVerbose, []string{}, "List of enabled verbose debug groups") option.BindEnv(option.DebugVerbose) flags.StringSlice(option.Devices, []string{}, "List of devices facing cluster/external network (used for BPF NodePort, BPF masquerading and host firewall); supports '+' as wildcard in device name, e.g. 'eth+'") option.BindEnv(option.Devices) flags.String(option.DirectRoutingDevice, "", "Device name used to connect nodes in direct routing mode (used by BPF NodePort, BPF fast redirect; if empty, automatically set to a device with k8s InternalIP/ExternalIP or with a default route)") option.BindEnv(option.DirectRoutingDevice) flags.String(option.LBDevInheritIPAddr, "", fmt.Sprintf("Device name which IP addr is inherited by devices running LB BPF program (--%s)", option.Devices)) option.BindEnv(option.LBDevInheritIPAddr) flags.String(option.DatapathMode, defaults.DatapathMode, "Datapath mode name") option.BindEnv(option.DatapathMode) flags.StringP(option.IpvlanMasterDevice, "", "undefined", "Device facing external network acting as ipvlan master") option.BindEnv(option.IpvlanMasterDevice) flags.MarkDeprecated(option.IpvlanMasterDevice, "This option will be removed in v1.12") flags.Bool(option.DisableConntrack, false, "Disable connection tracking") option.BindEnv(option.DisableConntrack) flags.Bool(option.EnableEndpointRoutes, defaults.EnableEndpointRoutes, "Use per endpoint routes instead of routing via cilium_host") option.BindEnv(option.EnableEndpointRoutes) flags.Bool(option.EnableHealthChecking, defaults.EnableHealthChecking, "Enable connectivity health checking") option.BindEnv(option.EnableHealthChecking) flags.Bool(option.EnableHealthCheckNodePort, defaults.EnableHealthCheckNodePort, "Enables a healthcheck nodePort server for NodePort services with 'healthCheckNodePort' being set") option.BindEnv(option.EnableHealthCheckNodePort) flags.StringSlice(option.EndpointStatus, []string{}, "Enable additional CiliumEndpoint status features ("+strings.Join(option.EndpointStatusValues(), ",")+")") option.BindEnv(option.EndpointStatus) flags.Bool(option.EnableEndpointHealthChecking, defaults.EnableEndpointHealthChecking, "Enable connectivity health checking between virtual endpoints") option.BindEnv(option.EnableEndpointHealthChecking) flags.Bool(option.EnableLocalNodeRoute, defaults.EnableLocalNodeRoute, "Enable installation of the route which points the allocation prefix of the local node") option.BindEnv(option.EnableLocalNodeRoute) flags.Bool(option.EnableIPv4Name, defaults.EnableIPv4, "Enable IPv4 support") option.BindEnv(option.EnableIPv4Name) flags.Bool(option.EnableIPv6Name, defaults.EnableIPv6, "Enable IPv6 support") option.BindEnv(option.EnableIPv6Name) flags.Bool(option.EnableIPv6NDPName, defaults.EnableIPv6NDP, "Enable IPv6 NDP support") option.BindEnv(option.EnableIPv6NDPName) flags.String(option.IPv6MCastDevice, "", "Device that joins a Solicited-Node multicast group for IPv6") option.BindEnv(option.IPv6MCastDevice) flags.Bool(option.EnableRemoteNodeIdentity, defaults.EnableRemoteNodeIdentity, "Enable use of remote node identity") option.BindEnv(option.EnableRemoteNodeIdentity) flags.String(option.EncryptInterface, "", "Transparent encryption interface") option.BindEnv(option.EncryptInterface) flags.Bool(option.EncryptNode, defaults.EncryptNode, "Enables encrypting traffic from non-Cilium pods and host networking") option.BindEnv(option.EncryptNode) flags.StringSlice(option.IPv4PodSubnets, []string{}, "List of IPv4 pod subnets to preconfigure for encryption") option.BindEnv(option.IPv4PodSubnets) flags.StringSlice(option.IPv6PodSubnets, []string{}, "List of IPv6 pod subnets to preconfigure for encryption") option.BindEnv(option.IPv6PodSubnets) flags.String(option.EndpointInterfaceNamePrefix, "", "Prefix of interface name shared by all endpoints") option.BindEnv(option.EndpointInterfaceNamePrefix) flags.MarkHidden(option.EndpointInterfaceNamePrefix) flags.MarkDeprecated(option.EndpointInterfaceNamePrefix, "This option no longer has any effect and will be removed in v1.13.") flags.StringSlice(option.ExcludeLocalAddress, []string{}, "Exclude CIDR from being recognized as local address") option.BindEnv(option.ExcludeLocalAddress) flags.Bool(option.DisableCiliumEndpointCRDName, false, "Disable use of CiliumEndpoint CRD") option.BindEnv(option.DisableCiliumEndpointCRDName) flags.String(option.EgressMasqueradeInterfaces, "", "Limit egress masquerading to interface selector") option.BindEnv(option.EgressMasqueradeInterfaces) flags.Bool(option.BPFSocketLBHostnsOnly, false, "Skip socket LB for services when inside a pod namespace, in favor of service LB at the pod interface. Socket LB is still used when in the host namespace. Required by service mesh (e.g., Istio, Linkerd).") option.BindEnv(option.BPFSocketLBHostnsOnly) flags.Bool(option.EnableHostReachableServices, false, "Enable reachability of services for host applications") option.BindEnv(option.EnableHostReachableServices) flags.StringSlice(option.HostReachableServicesProtos, []string{option.HostServicesTCP, option.HostServicesUDP}, "Only enable reachability of services for host applications for specific protocols") option.BindEnv(option.HostReachableServicesProtos) flags.Bool(option.EnableAutoDirectRoutingName, defaults.EnableAutoDirectRouting, "Enable automatic L2 routing between nodes") option.BindEnv(option.EnableAutoDirectRoutingName) flags.Bool(option.EnableBPFTProxy, defaults.EnableBPFTProxy, "Enable BPF-based proxy redirection, if support available") option.BindEnv(option.EnableBPFTProxy) flags.Bool(option.EnableHostLegacyRouting, defaults.EnableHostLegacyRouting, "Enable the legacy host forwarding model which does not bypass upper stack in host namespace") option.BindEnv(option.EnableHostLegacyRouting) flags.Bool(option.EnableXTSocketFallbackName, defaults.EnableXTSocketFallback, "Enable fallback for missing xt_socket module") option.BindEnv(option.EnableXTSocketFallbackName) flags.String(option.EnablePolicy, option.DefaultEnforcement, "Enable policy enforcement") option.BindEnv(option.EnablePolicy) flags.Bool(option.EnableExternalIPs, defaults.EnableExternalIPs, fmt.Sprintf("Enable k8s service externalIPs feature (requires enabling %s)", option.EnableNodePort)) option.BindEnv(option.EnableExternalIPs) flags.Bool(option.K8sEnableEndpointSlice, defaults.K8sEnableEndpointSlice, "Enables k8s EndpointSlice feature in Cilium if the k8s cluster supports it") option.BindEnv(option.K8sEnableEndpointSlice) flags.Bool(option.K8sEnableAPIDiscovery, defaults.K8sEnableAPIDiscovery, "Enable discovery of Kubernetes API groups and resources with the discovery API") option.BindEnv(option.K8sEnableAPIDiscovery) flags.Bool(option.EnableL7Proxy, defaults.EnableL7Proxy, "Enable L7 proxy for L7 policy enforcement") option.BindEnv(option.EnableL7Proxy) flags.Bool(option.EnableTracing, false, "Enable tracing while determining policy (debugging)") option.BindEnv(option.EnableTracing) flags.Bool(option.EnableWellKnownIdentities, defaults.EnableWellKnownIdentities, "Enable well-known identities for known Kubernetes components") option.BindEnv(option.EnableWellKnownIdentities) flags.String(option.EnvoyLog, "", "Path to a separate Envoy log file, if any") option.BindEnv(option.EnvoyLog) flags.Bool(option.EnableIPSecName, defaults.EnableIPSec, "Enable IPSec support") option.BindEnv(option.EnableIPSecName) flags.String(option.IPSecKeyFileName, "", "Path to IPSec key file") option.BindEnv(option.IPSecKeyFileName) flags.Bool(option.EnableWireguard, false, "Enable wireguard") option.BindEnv(option.EnableWireguard) flags.Bool(option.EnableWireguardUserspaceFallback, false, "Enables the fallback to the wireguard userspace implementation") option.BindEnv(option.EnableWireguardUserspaceFallback) flags.Bool(option.ForceLocalPolicyEvalAtSource, defaults.ForceLocalPolicyEvalAtSource, "Force policy evaluation of all local communication at the source endpoint") option.BindEnv(option.ForceLocalPolicyEvalAtSource) flags.Bool(option.HTTPNormalizePath, true, "Use Envoy HTTP path normalization options, which currently includes RFC 3986 path normalization, Envoy merge slashes option, and unescaping and redirecting for paths that contain escaped slashes. These are necessary to keep path based access control functional, and should not interfere with normal operation. Set this to false only with caution.") option.BindEnv(option.HTTPNormalizePath) flags.String(option.HTTP403Message, "", "Message returned in proxy L7 403 body") flags.MarkHidden(option.HTTP403Message) option.BindEnv(option.HTTP403Message) flags.Uint(option.HTTPRequestTimeout, 60*60, "Time after which a forwarded HTTP request is considered failed unless completed (in seconds); Use 0 for unlimited") option.BindEnv(option.HTTPRequestTimeout) flags.Uint(option.HTTPIdleTimeout, 0, "Time after which a non-gRPC HTTP stream is considered failed unless traffic in the stream has been processed (in seconds); defaults to 0 (unlimited)") option.BindEnv(option.HTTPIdleTimeout) flags.Uint(option.HTTPMaxGRPCTimeout, 0, "Time after which a forwarded gRPC request is considered failed unless completed (in seconds). A \"grpc-timeout\" header may override this with a shorter value; defaults to 0 (unlimited)") option.BindEnv(option.HTTPMaxGRPCTimeout) flags.Uint(option.HTTPRetryCount, 3, "Number of retries performed after a forwarded request attempt fails") option.BindEnv(option.HTTPRetryCount) flags.Uint(option.HTTPRetryTimeout, 0, "Time after which a forwarded but uncompleted request is retried (connection failures are retried immediately); defaults to 0 (never)") option.BindEnv(option.HTTPRetryTimeout) flags.Uint(option.ProxyConnectTimeout, 1, "Time after which a TCP connect attempt is considered failed unless completed (in seconds)") option.BindEnv(option.ProxyConnectTimeout) flags.Int(option.ProxyPrometheusPort, 0, "Port to serve Envoy metrics on. Default 0 (disabled).") option.BindEnv(option.ProxyPrometheusPort) flags.Bool(option.DisableEnvoyVersionCheck, false, "Do not perform Envoy binary version check on startup") flags.MarkHidden(option.DisableEnvoyVersionCheck) // Disable version check if Envoy build is disabled option.BindEnvWithLegacyEnvFallback(option.DisableEnvoyVersionCheck, "CILIUM_DISABLE_ENVOY_BUILD") flags.Var(option.NewNamedMapOptions(option.FixedIdentityMapping, &option.Config.FixedIdentityMapping, option.Config.FixedIdentityMappingValidator), option.FixedIdentityMapping, "Key-value for the fixed identity mapping which allows to use reserved label for fixed identities") option.BindEnv(option.FixedIdentityMapping) flags.Duration(option.IdentityChangeGracePeriod, defaults.IdentityChangeGracePeriod, "Time to wait before using new identity on endpoint identity change") option.BindEnv(option.IdentityChangeGracePeriod) flags.String(option.IdentityAllocationMode, option.IdentityAllocationModeKVstore, "Method to use for identity allocation") option.BindEnv(option.IdentityAllocationMode) flags.String(option.IPAM, ipamOption.IPAMClusterPool, "Backend to use for IPAM") option.BindEnv(option.IPAM) flags.String(option.IPv4Range, AutoCIDR, "Per-node IPv4 endpoint prefix, e.g. 10.16.0.0/16") option.BindEnv(option.IPv4Range) flags.String(option.IPv6Range, AutoCIDR, "Per-node IPv6 endpoint prefix, e.g. fd02:1:1::/96") option.BindEnv(option.IPv6Range) flags.String(option.IPv6ClusterAllocCIDRName, defaults.IPv6ClusterAllocCIDR, "IPv6 /64 CIDR used to allocate per node endpoint /96 CIDR") option.BindEnv(option.IPv6ClusterAllocCIDRName) flags.String(option.IPv4ServiceRange, AutoCIDR, "Kubernetes IPv4 services CIDR if not inside cluster prefix") option.BindEnv(option.IPv4ServiceRange) flags.String(option.IPv6ServiceRange, AutoCIDR, "Kubernetes IPv6 services CIDR if not inside cluster prefix") option.BindEnv(option.IPv6ServiceRange) flags.Bool(option.K8sEventHandover, defaults.K8sEventHandover, "Enable k8s event handover to kvstore for improved scalability") option.BindEnv(option.K8sEventHandover) flags.String(option.K8sAPIServer, "", "Kubernetes API server URL") option.BindEnv(option.K8sAPIServer) flags.String(option.K8sKubeConfigPath, "", "Absolute path of the kubernetes kubeconfig file") option.BindEnv(option.K8sKubeConfigPath) flags.String(option.K8sNamespaceName, "", "Name of the Kubernetes namespace in which Cilium is deployed in") option.BindEnv(option.K8sNamespaceName) flags.Bool(option.JoinClusterName, false, "Join a Cilium cluster via kvstore registration") option.BindEnv(option.JoinClusterName) flags.Bool(option.K8sRequireIPv4PodCIDRName, false, "Require IPv4 PodCIDR to be specified in node resource") option.BindEnv(option.K8sRequireIPv4PodCIDRName) flags.Bool(option.K8sRequireIPv6PodCIDRName, false, "Require IPv6 PodCIDR to be specified in node resource") option.BindEnv(option.K8sRequireIPv6PodCIDRName) flags.Uint(option.K8sServiceCacheSize, defaults.K8sServiceCacheSize, "Cilium service cache size for kubernetes") option.BindEnv(option.K8sServiceCacheSize) flags.MarkHidden(option.K8sServiceCacheSize) flags.String(option.K8sWatcherEndpointSelector, defaults.K8sWatcherEndpointSelector, "K8s endpoint watcher will watch for these k8s endpoints") option.BindEnv(option.K8sWatcherEndpointSelector) flags.Bool(option.KeepConfig, false, "When restoring state, keeps containers' configuration in place") option.BindEnv(option.KeepConfig) flags.String(option.KVStore, "", "Key-value store type") option.BindEnv(option.KVStore) flags.Duration(option.KVstoreLeaseTTL, defaults.KVstoreLeaseTTL, "Time-to-live for the KVstore lease.") flags.MarkHidden(option.KVstoreLeaseTTL) option.BindEnv(option.KVstoreLeaseTTL) flags.Int(option.KVstoreMaxConsecutiveQuorumErrorsName, defaults.KVstoreMaxConsecutiveQuorumErrors, "Max acceptable kvstore consecutive quorum errors before the agent assumes permanent failure") option.BindEnv(option.KVstoreMaxConsecutiveQuorumErrorsName) flags.Duration(option.KVstorePeriodicSync, defaults.KVstorePeriodicSync, "Periodic KVstore synchronization interval") option.BindEnv(option.KVstorePeriodicSync) flags.Duration(option.KVstoreConnectivityTimeout, defaults.KVstoreConnectivityTimeout, "Time after which an incomplete kvstore operation is considered failed") option.BindEnv(option.KVstoreConnectivityTimeout) flags.Duration(option.IPAllocationTimeout, defaults.IPAllocationTimeout, "Time after which an incomplete CIDR allocation is considered failed") option.BindEnv(option.IPAllocationTimeout) flags.Var(option.NewNamedMapOptions(option.KVStoreOpt, &option.Config.KVStoreOpt, nil), option.KVStoreOpt, "Key-value store options") option.BindEnv(option.KVStoreOpt) flags.Duration(option.K8sSyncTimeoutName, defaults.K8sSyncTimeout, "Timeout for synchronizing k8s resources before exiting") flags.MarkHidden(option.K8sSyncTimeoutName) option.BindEnv(option.K8sSyncTimeoutName) flags.Duration(option.AllocatorListTimeoutName, defaults.AllocatorListTimeout, "Timeout for listing allocator state before exiting") option.BindEnv(option.AllocatorListTimeoutName) flags.String(option.LabelPrefixFile, "", "Valid label prefixes file path") option.BindEnv(option.LabelPrefixFile) flags.StringSlice(option.Labels, []string{}, "List of label prefixes used to determine identity of an endpoint") option.BindEnv(option.Labels) flags.String(option.KubeProxyReplacement, option.KubeProxyReplacementPartial, fmt.Sprintf( "auto-enable available features for kube-proxy replacement (%q), "+ "or enable only selected features (will panic if any selected feature cannot be enabled) (%q) "+ "or enable all features (will panic if any feature cannot be enabled) (%q), "+ "or completely disable it (ignores any selected feature) (%q)", option.KubeProxyReplacementProbe, option.KubeProxyReplacementPartial, option.KubeProxyReplacementStrict, option.KubeProxyReplacementDisabled)) option.BindEnv(option.KubeProxyReplacement) flags.String(option.KubeProxyReplacementHealthzBindAddr, defaults.KubeProxyReplacementHealthzBindAddr, "The IP address with port for kube-proxy replacement health check server to serve on (set to '0.0.0.0:10256' for all IPv4 interfaces and '[::]:10256' for all IPv6 interfaces). Set empty to disable.") option.BindEnv(option.KubeProxyReplacementHealthzBindAddr) flags.Bool(option.EnableHostPort, true, fmt.Sprintf("Enable k8s hostPort mapping feature (requires enabling %s)", option.EnableNodePort)) option.BindEnv(option.EnableHostPort) flags.Bool(option.EnableNodePort, false, "Enable NodePort type services by Cilium") option.BindEnv(option.EnableNodePort) flags.Bool(option.EnableSVCSourceRangeCheck, true, "Enable check of service source ranges (currently, only for LoadBalancer)") option.BindEnv(option.EnableSVCSourceRangeCheck) flags.Bool(option.EnableBandwidthManager, false, "Enable BPF bandwidth manager") option.BindEnv(option.EnableBandwidthManager) flags.Bool(option.EnableRecorder, false, "Enable BPF datapath pcap recorder") option.BindEnv(option.EnableRecorder) flags.Bool(option.EnableLocalRedirectPolicy, false, "Enable Local Redirect Policy") option.BindEnv(option.EnableLocalRedirectPolicy) flags.Bool(option.EnableMKE, false, "Enable BPF kube-proxy replacement for MKE environments") flags.MarkHidden(option.EnableMKE) option.BindEnv(option.EnableMKE) flags.String(option.CgroupPathMKE, "", "Cgroup v1 net_cls mount path for MKE environments") flags.MarkHidden(option.CgroupPathMKE) option.BindEnv(option.CgroupPathMKE) flags.String(option.NodePortMode, option.NodePortModeSNAT, "BPF NodePort mode (\"snat\", \"dsr\", \"hybrid\")") flags.MarkHidden(option.NodePortMode) option.BindEnv(option.NodePortMode) flags.String(option.NodePortAlg, option.NodePortAlgRandom, "BPF load balancing algorithm (\"random\", \"maglev\")") flags.MarkHidden(option.NodePortAlg) option.BindEnv(option.NodePortAlg) flags.String(option.NodePortAcceleration, option.NodePortAccelerationDisabled, fmt.Sprintf( "BPF NodePort acceleration via XDP (\"%s\", \"%s\")", option.NodePortAccelerationNative, option.NodePortAccelerationDisabled)) flags.MarkHidden(option.NodePortAcceleration) option.BindEnv(option.NodePortAcceleration) flags.String(option.LoadBalancerMode, option.NodePortModeSNAT, "BPF load balancing mode (\"snat\", \"dsr\", \"hybrid\")") option.BindEnv(option.LoadBalancerMode) flags.String(option.LoadBalancerAlg, option.NodePortAlgRandom, "BPF load balancing algorithm (\"random\", \"maglev\")") option.BindEnv(option.LoadBalancerAlg) flags.String(option.LoadBalancerDSRDispatch, option.DSRDispatchOption, "BPF load balancing DSR dispatch method (\"opt\", \"ipip\")") option.BindEnv(option.LoadBalancerDSRDispatch) flags.String(option.LoadBalancerDSRL4Xlate, option.DSRL4XlateFrontend, "BPF load balancing DSR L4 DNAT method for IPIP (\"frontend\", \"backend\")") option.BindEnv(option.LoadBalancerDSRL4Xlate) flags.String(option.LoadBalancerRSSv4CIDR, "", "BPF load balancing RSS outer source IPv4 CIDR prefix for IPIP") option.BindEnv(option.LoadBalancerRSSv4CIDR) flags.String(option.LoadBalancerRSSv6CIDR, "", "BPF load balancing RSS outer source IPv6 CIDR prefix for IPIP") option.BindEnv(option.LoadBalancerRSSv6CIDR) flags.String(option.LoadBalancerAcceleration, option.NodePortAccelerationDisabled, fmt.Sprintf( "BPF load balancing acceleration via XDP (\"%s\", \"%s\")", option.NodePortAccelerationNative, option.NodePortAccelerationDisabled)) option.BindEnv(option.LoadBalancerAcceleration) flags.Uint(option.MaglevTableSize, maglev.DefaultTableSize, "Maglev per service backend table size (parameter M)") option.BindEnv(option.MaglevTableSize) flags.String(option.MaglevHashSeed, maglev.DefaultHashSeed, "Maglev cluster-wide hash seed (base64 encoded)") option.BindEnv(option.MaglevHashSeed) flags.Bool(option.EnableAutoProtectNodePortRange, true, "Append NodePort range to net.ipv4.ip_local_reserved_ports if it overlaps "+ "with ephemeral port range (net.ipv4.ip_local_port_range)") option.BindEnv(option.EnableAutoProtectNodePortRange) flags.StringSlice(option.NodePortRange, []string{fmt.Sprintf("%d", option.NodePortMinDefault), fmt.Sprintf("%d", option.NodePortMaxDefault)}, "Set the min/max NodePort port range") option.BindEnv(option.NodePortRange) flags.Bool(option.NodePortBindProtection, true, "Reject application bind(2) requests to service ports in the NodePort range") option.BindEnv(option.NodePortBindProtection) flags.Bool(option.EnableSessionAffinity, false, "Enable support for service session affinity") option.BindEnv(option.EnableSessionAffinity) flags.Bool(option.EnableServiceTopology, false, "Enable support for service topology aware hints") option.BindEnv(option.EnableServiceTopology) flags.Bool(option.EnableIdentityMark, true, "Enable setting identity mark for local traffic") option.BindEnv(option.EnableIdentityMark) flags.Bool(option.EnableHostFirewall, false, "Enable host network policies") option.BindEnv(option.EnableHostFirewall) flags.String(option.NativeRoutingCIDR, "", fmt.Sprintf("Allows to explicitly specify the IPv4 CIDR for native routing. This value corresponds to the configured cluster-cidr. Deprecated in favor of --%s", option.IPv4NativeRoutingCIDR)) option.BindEnv(option.NativeRoutingCIDR) flags.MarkHidden(option.NativeRoutingCIDR) flags.MarkDeprecated(option.NativeRoutingCIDR, "This option will be removed in v1.12") flags.String(option.IPv4NativeRoutingCIDR, "", "Allows to explicitly specify the IPv4 CIDR for native routing. This value corresponds to the configured cluster-cidr.") option.BindEnv(option.IPv4NativeRoutingCIDR) flags.String(option.IPv6NativeRoutingCIDR, "", "Allows to explicitly specify the IPv6 CIDR for native routing. This value corresponds to the configured cluster-cidr.") option.BindEnv(option.IPv6NativeRoutingCIDR) flags.String(option.LibDir, defaults.LibraryPath, "Directory path to store runtime build environment") option.BindEnv(option.LibDir) flags.StringSlice(option.LogDriver, []string{}, "Logging endpoints to use for example syslog") option.BindEnv(option.LogDriver) flags.Var(option.NewNamedMapOptions(option.LogOpt, &option.Config.LogOpt, nil), option.LogOpt, `Log driver options for cilium-agent, `+ `configmap example for syslog driver: {"syslog.level":"info","syslog.facility":"local5","syslog.tag":"cilium-agent"}`) option.BindEnv(option.LogOpt) flags.Bool(option.LogSystemLoadConfigName, false, "Enable periodic logging of system load") option.BindEnv(option.LogSystemLoadConfigName) flags.String(option.LoopbackIPv4, defaults.LoopbackIPv4, "IPv4 address for service loopback SNAT") option.BindEnv(option.LoopbackIPv4) flags.String(option.NAT46Range, defaults.DefaultNAT46Prefix, "IPv6 prefix to map IPv4 addresses to") option.BindEnv(option.NAT46Range) flags.Bool(option.EnableIPv4Masquerade, true, "Masquerade IPv4 traffic from endpoints leaving the host") option.BindEnv(option.EnableIPv4Masquerade) flags.Bool(option.EnableIPv6Masquerade, true, "Masquerade IPv6 traffic from endpoints leaving the host") option.BindEnv(option.EnableIPv6Masquerade) flags.Bool(option.EnableBPFMasquerade, false, "Masquerade packets from endpoints leaving the host with BPF instead of iptables") option.BindEnv(option.EnableBPFMasquerade) flags.String(option.DeriveMasqIPAddrFromDevice, "", "Device name from which Cilium derives the IP addr for BPF masquerade") flags.MarkHidden(option.DeriveMasqIPAddrFromDevice) option.BindEnv(option.DeriveMasqIPAddrFromDevice) flags.Bool(option.EnableIPMasqAgent, false, "Enable BPF ip-masq-agent") option.BindEnv(option.EnableIPMasqAgent) flags.Bool(option.EnableIPv4EgressGateway, false, "Enable egress gateway for IPv4") option.BindEnv(option.EnableIPv4EgressGateway) flags.String(option.IPMasqAgentConfigPath, "/etc/config/ip-masq-agent", "ip-masq-agent configuration file path") option.BindEnv(option.IPMasqAgentConfigPath) flags.Bool(option.InstallIptRules, true, "Install base iptables rules for cilium to mainly interact with kube-proxy (and masquerading)") option.BindEnv(option.InstallIptRules) flags.Duration(option.IPTablesLockTimeout, 5*time.Second, "Time to pass to each iptables invocation to wait for xtables lock acquisition") option.BindEnv(option.IPTablesLockTimeout) flags.Bool(option.IPTablesRandomFully, false, "Set iptables flag random-fully on masquerading rules") option.BindEnv(option.IPTablesRandomFully) flags.Int(option.MaxCtrlIntervalName, 0, "Maximum interval (in seconds) between controller runs. Zero is no limit.") flags.MarkHidden(option.MaxCtrlIntervalName) option.BindEnv(option.MaxCtrlIntervalName) flags.StringSlice(option.Metrics, []string{}, "Metrics that should be enabled or disabled from the default metric list. (+metric_foo to enable metric_foo , -metric_bar to disable metric_bar)") option.BindEnv(option.Metrics) flags.Bool(option.EnableMonitorName, true, "Enable the monitor unix domain socket server") option.BindEnv(option.EnableMonitorName) flags.String(option.MonitorAggregationName, "None", "Level of monitor aggregation for traces from the datapath") option.BindEnvWithLegacyEnvFallback(option.MonitorAggregationName, "CILIUM_MONITOR_AGGREGATION_LEVEL") flags.Int(option.MonitorQueueSizeName, 0, "Size of the event queue when reading monitor events") option.BindEnv(option.MonitorQueueSizeName) flags.Int(option.MTUName, 0, "Overwrite auto-detected MTU of underlying network") option.BindEnv(option.MTUName) flags.Int(option.RouteMetric, 0, "Overwrite the metric used by cilium when adding routes to its 'cilium_host' device") option.BindEnv(option.RouteMetric) flags.Bool(option.PrependIptablesChainsName, true, "Prepend custom iptables chains instead of appending") option.BindEnvWithLegacyEnvFallback(option.PrependIptablesChainsName, "CILIUM_PREPEND_IPTABLES_CHAIN") flags.String(option.IPv6NodeAddr, "auto", "IPv6 address of node") option.BindEnv(option.IPv6NodeAddr) flags.String(option.IPv4NodeAddr, "auto", "IPv4 address of node") option.BindEnv(option.IPv4NodeAddr) flags.String(option.ReadCNIConfiguration, "", "Read to the CNI configuration at specified path to extract per node configuration") option.BindEnv(option.ReadCNIConfiguration) flags.Bool(option.Restore, true, "Restores state, if possible, from previous daemon") option.BindEnv(option.Restore) flags.String(option.SidecarIstioProxyImage, k8s.DefaultSidecarIstioProxyImageRegexp, "Regular expression matching compatible Istio sidecar istio-proxy container image names") option.BindEnv(option.SidecarIstioProxyImage) flags.Bool(option.SingleClusterRouteName, false, "Use a single cluster route instead of per node routes") option.BindEnv(option.SingleClusterRouteName) flags.String(option.SocketPath, defaults.SockPath, "Sets daemon's socket path to listen for connections") option.BindEnv(option.SocketPath) flags.String(option.StateDir, defaults.RuntimePath, "Directory path to store runtime state") option.BindEnv(option.StateDir) flags.StringP(option.TunnelName, "t", "", fmt.Sprintf("Tunnel mode {%s} (default \"vxlan\" for the \"veth\" datapath mode)", option.GetTunnelModes())) option.BindEnv(option.TunnelName) flags.Int(option.TunnelPortName, 0, fmt.Sprintf("Tunnel port (default %d for \"vxlan\" and %d for \"geneve\")", defaults.TunnelPortVXLAN, defaults.TunnelPortGeneve)) option.BindEnv(option.TunnelPortName) flags.Int(option.TracePayloadlen, 128, "Length of payload to capture when tracing") option.BindEnv(option.TracePayloadlen) flags.Bool(option.Version, false, "Print version information") option.BindEnv(option.Version) flags.Bool(option.PProf, false, "Enable serving the pprof debugging API") option.BindEnv(option.PProf) flags.Int(option.PProfPort, 6060, "Port that the pprof listens on") option.BindEnv(option.PProfPort) flags.Bool(option.EnableXDPPrefilter, false, "Enable XDP prefiltering") option.BindEnv(option.EnableXDPPrefilter) flags.String(option.PrefilterDevice, "undefined", "Device facing external network for XDP prefiltering") option.BindEnv(option.PrefilterDevice) flags.MarkHidden(option.PrefilterDevice) flags.MarkDeprecated(option.PrefilterDevice, fmt.Sprintf("This option will be removed in v1.12. Use --%s and --%s instead.", option.EnableXDPPrefilter, option.Devices)) flags.String(option.PrefilterMode, option.ModePreFilterNative, "Prefilter mode via XDP (\"native\", \"generic\")") option.BindEnv(option.PrefilterMode) flags.MarkHidden(option.PrefilterMode) flags.MarkDeprecated(option.PrefilterMode, fmt.Sprintf("This option will be removed in v1.12. Use --%s instead.", option.LoadBalancerAcceleration)) flags.Bool(option.PreAllocateMapsName, defaults.PreAllocateMaps, "Enable BPF map pre-allocation") option.BindEnv(option.PreAllocateMapsName) // We expect only one of the possible variables to be filled. The evaluation order is: // --prometheus-serve-addr, CILIUM_PROMETHEUS_SERVE_ADDR, then PROMETHEUS_SERVE_ADDR // The second environment variable (without the CILIUM_ prefix) is here to // handle the case where someone uses a new image with an older spec, and the // older spec used the older variable name. flags.String(option.PrometheusServeAddr, "", "IP:Port on which to serve prometheus metrics (pass \":Port\" to bind on all interfaces, \"\" is off)") option.BindEnvWithLegacyEnvFallback(option.PrometheusServeAddr, "PROMETHEUS_SERVE_ADDR") flags.Int(option.CTMapEntriesGlobalTCPName, option.CTMapEntriesGlobalTCPDefault, "Maximum number of entries in TCP CT table") option.BindEnvWithLegacyEnvFallback(option.CTMapEntriesGlobalTCPName, "CILIUM_GLOBAL_CT_MAX_TCP") flags.String(option.CertsDirectory, defaults.CertsDirectory, "Root directory to find certificates specified in L7 TLS policy enforcement") option.BindEnv(option.CertsDirectory) flags.Int(option.CTMapEntriesGlobalAnyName, option.CTMapEntriesGlobalAnyDefault, "Maximum number of entries in non-TCP CT table") option.BindEnvWithLegacyEnvFallback(option.CTMapEntriesGlobalAnyName, "CILIUM_GLOBAL_CT_MAX_ANY") flags.Duration(option.CTMapEntriesTimeoutTCPName, 21600*time.Second, "Timeout for established entries in TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutTCPName) flags.Duration(option.CTMapEntriesTimeoutAnyName, 60*time.Second, "Timeout for entries in non-TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutAnyName) flags.Duration(option.CTMapEntriesTimeoutSVCTCPName, 21600*time.Second, "Timeout for established service entries in TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutSVCTCPName) flags.Duration(option.CTMapEntriesTimeoutSVCAnyName, 60*time.Second, "Timeout for service entries in non-TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutSVCAnyName) flags.Duration(option.CTMapEntriesTimeoutSYNName, 60*time.Second, "Establishment timeout for entries in TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutSYNName) flags.Duration(option.CTMapEntriesTimeoutFINName, 10*time.Second, "Teardown timeout for entries in TCP CT table") option.BindEnv(option.CTMapEntriesTimeoutFINName) flags.Duration(option.MonitorAggregationInterval, 5*time.Second, "Monitor report interval when monitor aggregation is enabled") option.BindEnv(option.MonitorAggregationInterval) flags.StringSlice(option.MonitorAggregationFlags, option.MonitorAggregationFlagsDefault, "TCP flags that trigger monitor reports when monitor aggregation is enabled") option.BindEnv(option.MonitorAggregationFlags) flags.Int(option.NATMapEntriesGlobalName, option.NATMapEntriesGlobalDefault, "Maximum number of entries for the global BPF NAT table") option.BindEnv(option.NATMapEntriesGlobalName) flags.Int(option.NeighMapEntriesGlobalName, option.NATMapEntriesGlobalDefault, "Maximum number of entries for the global BPF neighbor table") option.BindEnv(option.NeighMapEntriesGlobalName) flags.Int(option.PolicyMapEntriesName, policymap.MaxEntries, "Maximum number of entries in endpoint policy map (per endpoint)") option.BindEnv(option.PolicyMapEntriesName) flags.Int(option.SockRevNatEntriesName, option.SockRevNATMapEntriesDefault, "Maximum number of entries for the SockRevNAT BPF map") option.BindEnv(option.SockRevNatEntriesName) flags.Float64(option.MapEntriesGlobalDynamicSizeRatioName, 0.0, "Ratio (0.0-1.0) of total system memory to use for dynamic sizing of CT, NAT and policy BPF maps. Set to 0.0 to disable dynamic BPF map sizing (default: 0.0)") option.BindEnv(option.MapEntriesGlobalDynamicSizeRatioName) flags.String(option.CMDRef, "", "Path to cmdref output directory") flags.MarkHidden(option.CMDRef) option.BindEnv(option.CMDRef) flags.Int(option.GopsPort, defaults.GopsPortAgent, "Port for gops server to listen on") option.BindEnv(option.GopsPort) flags.Int(option.ToFQDNsMinTTL, 0, fmt.Sprintf("The minimum time, in seconds, to use DNS data for toFQDNs policies. (default %d )", defaults.ToFQDNsMinTTL)) option.BindEnv(option.ToFQDNsMinTTL) flags.Int(option.ToFQDNsProxyPort, 0, "Global port on which the in-agent DNS proxy should listen. Default 0 is a OS-assigned port.") option.BindEnv(option.ToFQDNsProxyPort) flags.StringVar(&option.Config.FQDNRejectResponse, option.FQDNRejectResponseCode, option.FQDNProxyDenyWithRefused, fmt.Sprintf("DNS response code for rejecting DNS requests, available options are '%v'", option.FQDNRejectOptions)) option.BindEnv(option.FQDNRejectResponseCode) flags.Int(option.ToFQDNsMaxIPsPerHost, defaults.ToFQDNsMaxIPsPerHost, "Maximum number of IPs to maintain per FQDN name for each endpoint") option.BindEnv(option.ToFQDNsMaxIPsPerHost) flags.Int(option.DNSMaxIPsPerRestoredRule, defaults.DNSMaxIPsPerRestoredRule, "Maximum number of IPs to maintain for each restored DNS rule") option.BindEnv(option.DNSMaxIPsPerRestoredRule) flags.Int(option.ToFQDNsMaxDeferredConnectionDeletes, defaults.ToFQDNsMaxDeferredConnectionDeletes, "Maximum number of IPs to retain for expired DNS lookups with still-active connections") option.BindEnv(option.ToFQDNsMaxDeferredConnectionDeletes) flags.DurationVar(&option.Config.ToFQDNsIdleConnectionGracePeriod, option.ToFQDNsIdleConnectionGracePeriod, defaults.ToFQDNsIdleConnectionGracePeriod, "Time during which idle but previously active connections with expired DNS lookups are still considered alive (default 0s)") option.BindEnv(option.ToFQDNsIdleConnectionGracePeriod) flags.DurationVar(&option.Config.FQDNProxyResponseMaxDelay, option.FQDNProxyResponseMaxDelay, 100*time.Millisecond, "The maximum time the DNS proxy holds an allowed DNS response before sending it along. Responses are sent as soon as the datapath is updated with the new IP information.") option.BindEnv(option.FQDNProxyResponseMaxDelay) flags.String(option.ToFQDNsPreCache, defaults.ToFQDNsPreCache, "DNS cache data at this path is preloaded on agent startup") option.BindEnv(option.ToFQDNsPreCache) flags.Bool(option.ToFQDNsEnableDNSCompression, defaults.ToFQDNsEnableDNSCompression, "Allow the DNS proxy to compress responses to endpoints that are larger than 512 Bytes or the EDNS0 option, if present") option.BindEnv(option.ToFQDNsEnableDNSCompression) flags.Int(option.PolicyQueueSize, defaults.PolicyQueueSize, "size of queues for policy-related events") option.BindEnv(option.PolicyQueueSize) flags.Int(option.EndpointQueueSize, defaults.EndpointQueueSize, "size of EventQueue per-endpoint") option.BindEnv(option.EndpointQueueSize) flags.Duration(option.EndpointGCInterval, 5*time.Minute, "Periodically monitor local endpoint health via link status on this interval and garbage collect them if they become unhealthy, set to 0 to disable") flags.MarkHidden(option.EndpointGCInterval) option.BindEnv(option.EndpointGCInterval) flags.Bool(option.SelectiveRegeneration, true, "only regenerate endpoints which need to be regenerated upon policy changes") flags.MarkHidden(option.SelectiveRegeneration) option.BindEnv(option.SelectiveRegeneration) flags.String(option.WriteCNIConfigurationWhenReady, "", fmt.Sprintf("Write the CNI configuration as specified via --%s to path when agent is ready", option.ReadCNIConfiguration)) option.BindEnv(option.WriteCNIConfigurationWhenReady) flags.Duration(option.PolicyTriggerInterval, defaults.PolicyTriggerInterval, "Time between triggers of policy updates (regenerations for all endpoints)") flags.MarkHidden(option.PolicyTriggerInterval) option.BindEnv(option.PolicyTriggerInterval) flags.Bool(option.DisableCNPStatusUpdates, false, `Do not send CNP NodeStatus updates to the Kubernetes api-server (recommended to run with "cnp-node-status-gc-interval=0" in cilium-operator)`) option.BindEnv(option.DisableCNPStatusUpdates) flags.Bool(option.PolicyAuditModeArg, false, "Enable policy audit (non-drop) mode") option.BindEnv(option.PolicyAuditModeArg) flags.Bool(option.EnableHubble, false, "Enable hubble server") option.BindEnv(option.EnableHubble) flags.String(option.HubbleSocketPath, defaults.HubbleSockPath, "Set hubble's socket path to listen for connections") option.BindEnv(option.HubbleSocketPath) flags.String(option.HubbleListenAddress, "", `An additional address for Hubble server to listen to, e.g. ":4244"`) option.BindEnv(option.HubbleListenAddress) flags.Bool(option.HubbleTLSDisabled, false, "Allow Hubble server to run on the given listen address without TLS.") option.BindEnv(option.HubbleTLSDisabled) flags.String(option.HubbleTLSCertFile, "", "Path to the public key file for the Hubble server. The file must contain PEM encoded data.") option.BindEnv(option.HubbleTLSCertFile) flags.String(option.HubbleTLSKeyFile, "", "Path to the private key file for the Hubble server. The file must contain PEM encoded data.") option.BindEnv(option.HubbleTLSKeyFile) flags.StringSlice(option.HubbleTLSClientCAFiles, []string{}, "Paths to one or more public key files of client CA certificates to use for TLS with mutual authentication (mTLS). The files must contain PEM encoded data. When provided, this option effectively enables mTLS.") option.BindEnv(option.HubbleTLSClientCAFiles) flags.Int(option.HubbleEventBufferCapacity, observeroption.Default.MaxFlows.AsInt(), "Capacity of Hubble events buffer. The provided value must be one less than an integer power of two and no larger than 65535 (ie: 1, 3, ..., 2047, 4095, ..., 65535)") option.BindEnv(option.HubbleEventBufferCapacity) flags.Int(option.HubbleEventQueueSize, 0, "Buffer size of the channel to receive monitor events.") option.BindEnv(option.HubbleEventQueueSize) flags.String(option.HubbleMetricsServer, "", "Address to serve Hubble metrics on.") option.BindEnv(option.HubbleMetricsServer) flags.StringSlice(option.HubbleMetrics, []string{}, "List of Hubble metrics to enable.") option.BindEnv(option.HubbleMetrics) flags.String(option.HubbleExportFilePath, exporteroption.Default.Path, "Filepath to write Hubble events to.") option.BindEnv(option.HubbleExportFilePath) flags.Int(option.HubbleExportFileMaxSizeMB, exporteroption.Default.MaxSizeMB, "Size in MB at which to rotate Hubble export file.") option.BindEnv(option.HubbleExportFileMaxSizeMB) flags.Int(option.HubbleExportFileMaxBackups, exporteroption.Default.MaxBackups, "Number of rotated Hubble export files to keep.") option.BindEnv(option.HubbleExportFileMaxBackups) flags.Bool(option.HubbleExportFileCompress, exporteroption.Default.Compress, "Compress rotated Hubble export files.") option.BindEnv(option.HubbleExportFileCompress) flags.Bool(option.EnableHubbleRecorderAPI, true, "Enable the Hubble recorder API") option.BindEnv(option.EnableHubbleRecorderAPI) flags.String(option.HubbleRecorderStoragePath, defaults.HubbleRecorderStoragePath, "Directory in which pcap files created via the Hubble Recorder API are stored") option.BindEnv(option.HubbleRecorderStoragePath) flags.Int(option.HubbleRecorderSinkQueueSize, defaults.HubbleRecorderSinkQueueSize, "Queue size of each Hubble recorder sink") option.BindEnv(option.HubbleRecorderSinkQueueSize) flags.StringSlice(option.DisableIptablesFeederRules, []string{}, "Chains to ignore when installing feeder rules.") option.BindEnv(option.DisableIptablesFeederRules) flags.Duration(option.K8sHeartbeatTimeout, 30*time.Second, "Configures the timeout for api-server heartbeat, set to 0 to disable") option.BindEnv(option.K8sHeartbeatTimeout) flags.Bool(option.EnableIPv4FragmentsTrackingName, defaults.EnableIPv4FragmentsTracking, "Enable IPv4 fragments tracking for L4-based lookups") option.BindEnv(option.EnableIPv4FragmentsTrackingName) flags.Int(option.FragmentsMapEntriesName, defaults.FragmentsMapEntries, "Maximum number of entries in fragments tracking map") option.BindEnv(option.FragmentsMapEntriesName) flags.Int(option.LBMapEntriesName, lbmap.MaxEntries, "Maximum number of entries in Cilium BPF lbmap") option.BindEnv(option.LBMapEntriesName) flags.String(option.LocalRouterIPv4, "", "Link-local IPv4 used for Cilium's router devices") option.BindEnv(option.LocalRouterIPv4) flags.String(option.LocalRouterIPv6, "", "Link-local IPv6 used for Cilium's router devices") option.BindEnv(option.LocalRouterIPv6) flags.String(option.K8sServiceProxyName, "", "Value of K8s service-proxy-name label for which Cilium handles the services (empty = all services without service.kubernetes.io/service-proxy-name label)") option.BindEnv(option.K8sServiceProxyName) flags.Var(option.NewNamedMapOptions(option.APIRateLimitName, &option.Config.APIRateLimit, nil), option.APIRateLimitName, "API rate limiting configuration (example: --rate-limit endpoint-create=rate-limit:10/m,rate-burst:2)") option.BindEnv(option.APIRateLimitName) flags.Duration(option.CRDWaitTimeout, 5*time.Minute, "Cilium will exit if CRDs are not available within this duration upon startup") option.BindEnv(option.CRDWaitTimeout) flags.Bool(option.EgressMultiHomeIPRuleCompat, false, "Offset routing table IDs under ENI IPAM mode to avoid collisions with reserved table IDs. If false, the offset is performed (new scheme), otherwise, the old scheme stays in-place.") option.BindEnv(option.EgressMultiHomeIPRuleCompat) flags.Bool(option.EnableBPFBypassFIBLookup, false, "Enable FIB lookup bypass optimization for nodeport reverse NAT handling") option.BindEnv(option.EnableBPFBypassFIBLookup) flags.MarkHidden(option.EnableBPFBypassFIBLookup) flags.MarkDeprecated(option.EnableBPFBypassFIBLookup, fmt.Sprintf("This option will be removed in v1.12.")) flags.Bool(option.InstallNoConntrackIptRules, defaults.InstallNoConntrackIptRules, "Install Iptables rules to skip netfilter connection tracking on all pod traffic. This option is only effective when Cilium is running in direct routing and full KPR mode. Moreover, this option cannot be enabled when Cilium is running in a managed Kubernetes environment or in a chained CNI setup.") option.BindEnv(option.InstallNoConntrackIptRules) flags.Bool(option.EnableCustomCallsName, false, "Enable tail call hooks for custom eBPF programs") option.BindEnv(option.EnableCustomCallsName) flags.Bool(option.BGPAnnounceLBIP, false, "Announces service IPs of type LoadBalancer via BGP") option.BindEnv(option.BGPAnnounceLBIP) flags.Bool(option.BGPAnnouncePodCIDR, false, "Announces the node's pod CIDR via BGP") option.BindEnv(option.BGPAnnouncePodCIDR) flags.String(option.BGPConfigPath, "/var/lib/cilium/bgp/config.yaml", "Path to file containing the BGP configuration") option.BindEnv(option.BGPConfigPath) flags.Bool(option.ExternalClusterIPName, false, "Enable external access to ClusterIP services (default false)") option.BindEnv(option.ExternalClusterIPName) flags.IntSlice(option.VLANBPFBypass, []int{}, "List of explicitly allowed VLAN IDs, '0' id will allow all VLAN IDs") option.BindEnv(option.VLANBPFBypass) flags.Bool(option.EnableICMPRules, false, "Enable ICMP-based rule support for Cilium Network Policies") flags.MarkHidden(option.EnableICMPRules) option.BindEnv(option.EnableICMPRules) flags.Bool(option.BypassIPAvailabilityUponRestore, false, "Bypasses the IP availability error within IPAM upon endpoint restore") flags.MarkHidden(option.BypassIPAvailabilityUponRestore) option.BindEnv(option.BypassIPAvailabilityUponRestore) flags.Bool(option.EnableCiliumEndpointSlice, false, "If set to true, CiliumEndpointSlice feature is enabled and cilium agent watch for CiliumEndpointSlice instead of CiliumEndpoint to update the IPCache.") option.BindEnv(option.EnableCiliumEndpointSlice) flags.Bool(option.EnableK8sTerminatingEndpoint, true, "Enable auto-detect of terminating endpoint condition") option.BindEnv(option.EnableK8sTerminatingEndpoint) viper.BindPFlags(flags) } // restoreExecPermissions restores file permissions to 0740 of all files inside // `searchDir` with the given regex `patterns`. func restoreExecPermissions(searchDir string, patterns ...string) error { fileList := []string{} err := filepath.Walk(searchDir, func(path string, f os.FileInfo, err error) error { for _, pattern := range patterns { if regexp.MustCompile(pattern).MatchString(f.Name()) { fileList = append(fileList, path) break } } return nil }) for _, fileToChange := range fileList { // Changing files permissions to -rwx:r--:---, we are only // adding executable permission to the owner and keeping the // same permissions stored by go-bindata. if err := os.Chmod(fileToChange, os.FileMode(0740)); err != nil { return err } } return err } func initEnv(cmd *cobra.Command) { var debugDatapath bool option.Config.SetMapElementSizes( // for the conntrack and NAT element size we assume the largest possible // key size, i.e. IPv6 keys ctmap.SizeofCtKey6Global+ctmap.SizeofCtEntry, nat.SizeofNatKey6+nat.SizeofNatEntry6, neighborsmap.SizeofNeighKey6+neighborsmap.SizeOfNeighValue, lbmap.SizeofSockRevNat6Key+lbmap.SizeofSockRevNat6Value) // Prepopulate option.Config with options from CLI. option.Config.Populate() // add hooks after setting up metrics in the option.Config logging.DefaultLogger.Hooks.Add(metrics.NewLoggingHook(components.CiliumAgentName)) // Logging should always be bootstrapped first. Do not add any code above this! if err := logging.SetupLogging(option.Config.LogDriver, logging.LogOptions(option.Config.LogOpt), "cilium-agent", option.Config.Debug); err != nil { log.Fatal(err) } option.LogRegisteredOptions(log) // Configure k8s as soon as possible so that k8s.IsEnabled() has the right // behavior. bootstrapStats.k8sInit.Start() k8s.Configure(option.Config.K8sAPIServer, option.Config.K8sKubeConfigPath, defaults.K8sClientQPSLimit, defaults.K8sClientBurst) bootstrapStats.k8sInit.End(true) for _, grp := range option.Config.DebugVerbose { switch grp { case argDebugVerboseFlow: log.Debugf("Enabling flow debug") flowdebug.Enable() case argDebugVerboseKvstore: kvstore.EnableTracing() case argDebugVerboseEnvoy: log.Debugf("Enabling Envoy tracing") envoy.EnableTracing() case argDebugVerboseDatapath: log.Debugf("Enabling datapath debug messages") debugDatapath = true case argDebugVerbosePolicy: option.Config.Opts.SetBool(option.DebugPolicy, true) default: log.Warningf("Unknown verbose debug group: %s", grp) } } // Enable policy debugging if debug is enabled. if option.Config.Debug { option.Config.Opts.SetBool(option.DebugPolicy, true) } common.RequireRootPrivilege("cilium-agent") log.Info(" _ _ _") log.Info(" ___|_| |_|_ _ _____") log.Info("| _| | | | | | |") log.Info("|___|_|_|_|___|_|_|_|") log.Infof("Cilium %s", version.Version) if option.Config.LogSystemLoadConfig { loadinfo.StartBackgroundLogger() } if option.Config.DisableEnvoyVersionCheck { log.Info("Envoy version check disabled") } else { envoyVersion := envoy.GetEnvoyVersion() log.Infof("%s", envoyVersion) envoyVersionArray := strings.Fields(envoyVersion) if len(envoyVersionArray) < 3 { log.Fatal("Truncated Envoy version string, cannot verify version match.") } // Make sure Envoy version matches ours if !strings.HasPrefix(envoyVersionArray[2], envoy.RequiredEnvoyVersionSHA) { log.Fatalf("Envoy version %s does not match with required version %s ,aborting.", envoyVersionArray[2], envoy.RequiredEnvoyVersionSHA) } } // This check is here instead of in DaemonConfig.Populate (invoked at the // start of this function as option.Config.Populate) to avoid an import loop. if option.Config.IdentityAllocationMode == option.IdentityAllocationModeCRD && !k8s.IsEnabled() && option.Config.DatapathMode != datapathOption.DatapathModeLBOnly { log.Fatal("CRD Identity allocation mode requires k8s to be configured.") } if option.Config.PProf { pprof.Enable(option.Config.PProfPort) } if option.Config.PreAllocateMaps { bpf.EnableMapPreAllocation() } scopedLog := log.WithFields(logrus.Fields{ logfields.Path + ".RunDir": option.Config.RunDir, logfields.Path + ".LibDir": option.Config.LibDir, }) option.Config.BpfDir = filepath.Join(option.Config.LibDir, defaults.BpfDir) scopedLog = scopedLog.WithField(logfields.Path+".BPFDir", defaults.BpfDir) if err := os.MkdirAll(option.Config.RunDir, defaults.RuntimePathRights); err != nil { scopedLog.WithError(err).Fatal("Could not create runtime directory") } if option.Config.RunDir != defaults.RuntimePath { if err := os.MkdirAll(defaults.RuntimePath, defaults.RuntimePathRights); err != nil { scopedLog.WithError(err).Fatal("Could not create default runtime directory") } } option.Config.StateDir = filepath.Join(option.Config.RunDir, defaults.StateDir) scopedLog = scopedLog.WithField(logfields.Path+".StateDir", option.Config.StateDir) if err := os.MkdirAll(option.Config.StateDir, defaults.StateDirRights); err != nil { scopedLog.WithError(err).Fatal("Could not create state directory") } if err := os.MkdirAll(option.Config.LibDir, defaults.RuntimePathRights); err != nil { scopedLog.WithError(err).Fatal("Could not create library directory") } // Restore permissions of executable files if err := restoreExecPermissions(option.Config.LibDir, `.*\.sh`); err != nil { scopedLog.WithError(err).Fatal("Unable to restore agent asset permissions") } if option.Config.MaxControllerInterval < 0 { scopedLog.Fatalf("Invalid %s value %d", option.MaxCtrlIntervalName, option.Config.MaxControllerInterval) } linuxdatapath.CheckMinRequirements() if err := pidfile.Write(defaults.PidFilePath); err != nil { log.WithField(logfields.Path, defaults.PidFilePath).WithError(err).Fatal("Failed to create Pidfile") } option.Config.AllowLocalhost = strings.ToLower(option.Config.AllowLocalhost) switch option.Config.AllowLocalhost { case option.AllowLocalhostAlways, option.AllowLocalhostAuto, option.AllowLocalhostPolicy: default: log.Fatalf("Invalid setting for --allow-localhost, must be { %s, %s, %s }", option.AllowLocalhostAuto, option.AllowLocalhostAlways, option.AllowLocalhostPolicy) } option.Config.ModePreFilter = strings.ToLower(option.Config.ModePreFilter) if option.Config.ModePreFilter == "generic" { option.Config.ModePreFilter = option.ModePreFilterGeneric } if option.Config.ModePreFilter != option.ModePreFilterNative && option.Config.ModePreFilter != option.ModePreFilterGeneric { log.Fatalf("Invalid setting for --prefilter-mode, must be { %s, generic }", option.ModePreFilterNative) } if option.Config.DevicePreFilter != "undefined" { option.Config.EnableXDPPrefilter = true found := false for _, dev := range option.Config.Devices { if dev == option.Config.DevicePreFilter { found = true break } } if !found { option.Config.Devices = append(option.Config.Devices, option.Config.DevicePreFilter) } if err := loader.SetXDPMode(option.Config.ModePreFilter); err != nil { scopedLog.WithError(err).Fatal("Cannot set prefilter XDP mode") } } scopedLog = log.WithField(logfields.Path, option.Config.SocketPath) socketDir := path.Dir(option.Config.SocketPath) if err := os.MkdirAll(socketDir, defaults.RuntimePathRights); err != nil { scopedLog.WithError(err).Fatal("Cannot mkdir directory for cilium socket") } if err := os.Remove(option.Config.SocketPath); !os.IsNotExist(err) && err != nil { scopedLog.WithError(err).Fatal("Cannot remove existing Cilium sock") } // The standard operation is to mount the BPF filesystem to the // standard location (/sys/fs/bpf). The user may choose to specify // the path to an already mounted filesystem instead. This is // useful if the daemon is being round inside a namespace and the // BPF filesystem is mapped into the slave namespace. bpf.CheckOrMountFS(option.Config.BPFRoot) cgroups.CheckOrMountCgrpFS(option.Config.CGroupRoot) option.Config.Opts.SetBool(option.Debug, debugDatapath) option.Config.Opts.SetBool(option.DebugLB, debugDatapath) option.Config.Opts.SetBool(option.DropNotify, true) option.Config.Opts.SetBool(option.TraceNotify, true) option.Config.Opts.SetBool(option.PolicyVerdictNotify, true) option.Config.Opts.SetBool(option.PolicyTracing, option.Config.EnableTracing) option.Config.Opts.SetBool(option.Conntrack, !option.Config.DisableConntrack) option.Config.Opts.SetBool(option.ConntrackAccounting, !option.Config.DisableConntrack) option.Config.Opts.SetBool(option.ConntrackLocal, false) option.Config.Opts.SetBool(option.PolicyAuditMode, option.Config.PolicyAuditMode) monitorAggregationLevel, err := option.ParseMonitorAggregationLevel(option.Config.MonitorAggregation) if err != nil { log.WithError(err).Fatalf("Failed to parse %s", option.MonitorAggregationName) } option.Config.Opts.SetValidated(option.MonitorAggregation, monitorAggregationLevel) policy.SetPolicyEnabled(option.Config.EnablePolicy) if option.Config.PolicyAuditMode { log.Warningf("%s is enabled. Network policy will not be enforced.", option.PolicyAuditMode) } if err := identity.AddUserDefinedNumericIdentitySet(option.Config.FixedIdentityMapping); err != nil { log.WithError(err).Fatal("Invalid fixed identities provided") } if !option.Config.EnableIPv4 && !option.Config.EnableIPv6 { log.Fatal("Either IPv4 or IPv6 addressing must be enabled") } if err := labelsfilter.ParseLabelPrefixCfg(option.Config.Labels, option.Config.LabelPrefixFile); err != nil { log.WithError(err).Fatal("Unable to parse Label prefix configuration") } _, r, err := net.ParseCIDR(option.Config.NAT46Range) if err != nil { log.WithError(err).WithField(logfields.V6Prefix, option.Config.NAT46Range).Fatal("Invalid NAT46 prefix") } option.Config.NAT46Prefix = r switch option.Config.DatapathMode { case datapathOption.DatapathModeVeth: if name := option.Config.IpvlanMasterDevice; name != "undefined" { log.WithField(logfields.IpvlanMasterDevice, name). Fatal("ipvlan master device cannot be set in the 'veth' datapath mode") } if option.Config.Tunnel == "" { option.Config.Tunnel = option.TunnelVXLAN } case datapathOption.DatapathModeIpvlan: if option.Config.Tunnel != "" && option.Config.TunnelingEnabled() { log.WithField(logfields.Tunnel, option.Config.Tunnel). Fatal("tunnel cannot be set in the 'ipvlan' datapath mode") } if len(option.Config.Devices) != 0 { log.WithField(logfields.Devices, option.Config.Devices). Fatal("device cannot be set in the 'ipvlan' datapath mode") } if option.Config.EnableIPSec { log.Fatal("Currently ipsec cannot be used in the 'ipvlan' datapath mode.") } option.Config.Tunnel = option.TunnelDisabled // We disallow earlier command line combination of --device with // --datapath-mode ipvlan. But given all the remaining logic is // shared with option.Config.Devices, override it here internally // with the specified ipvlan master device. Reason to have a // separate, more specific command line parameter here and in // the swagger API is that in future we might deprecate --device // parameter with e.g. some auto-detection mechanism, thus for // ipvlan it is desired to have a separate one, see PR #6608. iface := option.Config.IpvlanMasterDevice if iface == "undefined" { log.WithField(logfields.IpvlanMasterDevice, option.Config.Devices[0]). Fatal("ipvlan master device must be specified in the 'ipvlan' datapath mode") } option.Config.Devices = []string{iface} link, err := netlink.LinkByName(option.Config.Devices[0]) if err != nil { log.WithError(err).WithField(logfields.IpvlanMasterDevice, option.Config.Devices[0]). Fatal("Cannot find device interface") } option.Config.Ipvlan.MasterDeviceIndex = link.Attrs().Index option.Config.Ipvlan.OperationMode = connector.OperationModeL3 if option.Config.InstallIptRules { option.Config.Ipvlan.OperationMode = connector.OperationModeL3S } else { log.WithFields(logrus.Fields{ logfields.URL: "https://github.com/cilium/cilium/issues/12879", }).Warn("IPtables rule configuration has been disabled. This may affect policy and forwarding, see the URL for more details.") } case datapathOption.DatapathModeLBOnly: log.Info("Running in LB-only mode") option.Config.LoadBalancerPMTUDiscovery = option.Config.NodePortAcceleration != option.NodePortAccelerationDisabled option.Config.KubeProxyReplacement = option.KubeProxyReplacementPartial option.Config.EnableHostReachableServices = true option.Config.EnableHostPort = false option.Config.EnableNodePort = true option.Config.EnableExternalIPs = true option.Config.Tunnel = option.TunnelDisabled option.Config.EnableHealthChecking = false option.Config.EnableIPv4Masquerade = false option.Config.EnableIPv6Masquerade = false option.Config.InstallIptRules = false option.Config.EnableL7Proxy = false default: log.WithField(logfields.DatapathMode, option.Config.DatapathMode).Fatal("Invalid datapath mode") } if option.Config.EnableL7Proxy && !option.Config.InstallIptRules { log.Fatal("L7 proxy requires iptables rules (--install-iptables-rules=\"true\")") } if option.Config.EnableIPSec && option.Config.TunnelingEnabled() { if err := ipsec.ProbeXfrmStateOutputMask(); err != nil { log.WithError(err).Fatal("IPSec with tunneling requires support for xfrm state output masks (Linux 4.19 or later).") } } // IPAMENI IPSec is configured from Reinitialize() to pull in devices // that may be added or removed at runtime. if option.Config.EnableIPSec && !option.Config.TunnelingEnabled() && len(option.Config.EncryptInterface) == 0 && option.Config.IPAM != ipamOption.IPAMENI { link, err := linuxdatapath.NodeDeviceNameWithDefaultRoute() if err != nil { log.WithError(err).Fatal("Ipsec default interface lookup failed, consider \"encrypt-interface\" to manually configure interface.") } option.Config.EncryptInterface = append(option.Config.EncryptInterface, link) } if option.Config.TunnelingEnabled() && option.Config.EnableAutoDirectRouting { log.Fatalf("%s cannot be used with tunneling. Packets must be routed through the tunnel device.", option.EnableAutoDirectRoutingName) } initClockSourceOption() initSockmapOption() if option.Config.EnableHostFirewall { if option.Config.EnableIPSec { log.Fatal("IPSec cannot be used with the host firewall.") } if option.Config.EnableEndpointRoutes && !option.Config.EnableRemoteNodeIdentity { log.Fatalf("The host firewall requires remote-node identities (%s) when running with %s", option.EnableRemoteNodeIdentity, option.EnableEndpointRoutes) } } if option.Config.EnableBandwidthManager && option.Config.EnableIPSec { log.Warning("The bandwidth manager cannot be used with IPSec. Disabling the bandwidth manager.") option.Config.EnableBandwidthManager = false } if option.Config.EnableIPv6Masquerade && option.Config.EnableBPFMasquerade { log.Fatal("BPF masquerade is not supported for IPv6.") } // If there is one device specified, use it to derive better default // allocation prefixes node.InitDefaultPrefix(option.Config.DirectRoutingDevice) if option.Config.IPv6NodeAddr != "auto" { if ip := net.ParseIP(option.Config.IPv6NodeAddr); ip == nil { log.WithField(logfields.IPAddr, option.Config.IPv6NodeAddr).Fatal("Invalid IPv6 node address") } else { if !ip.IsGlobalUnicast() { log.WithField(logfields.IPAddr, ip).Fatal("Invalid IPv6 node address: not a global unicast address") } node.SetIPv6(ip) } } if option.Config.IPv4NodeAddr != "auto" { if ip := net.ParseIP(option.Config.IPv4NodeAddr); ip == nil { log.WithField(logfields.IPAddr, option.Config.IPv4NodeAddr).Fatal("Invalid IPv4 node address") } else { node.SetIPv4(ip) } } k8s.SidecarIstioProxyImageRegexp, err = regexp.Compile(option.Config.SidecarIstioProxyImage) if err != nil { log.WithError(err).Fatal("Invalid sidecar-istio-proxy-image regular expression") return } if option.Config.EnableIPv4FragmentsTracking { if !option.Config.EnableIPv4 { option.Config.EnableIPv4FragmentsTracking = false } else { supportedMapTypes := probes.NewProbeManager().GetMapTypes() if !supportedMapTypes.HaveLruHashMapType { option.Config.EnableIPv4FragmentsTracking = false log.Info("Disabled support for IPv4 fragments due to missing kernel support for BPF LRU maps") } } } if option.Config.EnableBPFTProxy { if h := probes.NewProbeManager().GetHelpers("sched_act"); h != nil { if _, ok := h["bpf_sk_assign"]; !ok { option.Config.EnableBPFTProxy = false log.Info("Disabled support for BPF TProxy due to missing kernel support for socket assign (Linux 5.7 or later)") } } } if option.Config.LocalRouterIPv4 != "" || option.Config.LocalRouterIPv6 != "" { // TODO(weil0ng): add a proper check for ipam in PR# 15429. if option.Config.TunnelingEnabled() { log.Fatalf("Cannot specify %s or %s in tunnel mode.", option.LocalRouterIPv4, option.LocalRouterIPv6) } if !option.Config.EnableEndpointRoutes { log.Fatalf("Cannot specify %s or %s without %s.", option.LocalRouterIPv4, option.LocalRouterIPv6, option.EnableEndpointRoutes) } if option.Config.EnableIPSec { log.Fatalf("Cannot specify %s or %s with %s.", option.LocalRouterIPv4, option.LocalRouterIPv6, option.EnableIPSecName) } } if option.Config.IPAM == ipamOption.IPAMAzure { option.Config.EgressMultiHomeIPRuleCompat = true log.WithFields(logrus.Fields{ "URL": "https://github.com/cilium/cilium/issues/14705", }).Infof( "Auto-set %q to `true` because the Azure datapath has not been migrated over to a new scheme. "+ "A future version of Cilium will support a newer Azure datapath. "+ "Connectivity is not affected.", option.EgressMultiHomeIPRuleCompat, ) } if option.Config.InstallNoConntrackIptRules { // InstallNoConntrackIptRules can only be enabled in direct // routing mode as in tunneling mode the encapsulated traffic is // already skipping netfilter conntrack. if option.Config.TunnelingEnabled() { log.Fatalf("%s requires the agent to run in direct routing mode.", option.InstallNoConntrackIptRules) } // Moreover InstallNoConntrackIptRules requires IPv4 support as // the native routing CIDR, used to select all pod traffic, can // only be an IPv4 CIDR at the moment. if !option.Config.EnableIPv4 { log.Fatalf("%s requires IPv4 support.", option.InstallNoConntrackIptRules) } } if option.Config.BGPAnnouncePodCIDR && (option.Config.IPAM != ipamOption.IPAMClusterPool && option.Config.IPAM != ipamOption.IPAMKubernetes) { log.Fatalf("BGP announcements for pod CIDRs is not supported with IPAM mode %q (only %q and %q are supported)", option.Config.IPAM, ipamOption.IPAMClusterPool, ipamOption.IPAMKubernetes) } // Ensure that the user does not turn on this mode unless it's for an IPAM // mode which support the bypass. if option.Config.BypassIPAvailabilityUponRestore { switch option.Config.IPAMMode() { case ipamOption.IPAMENI: log.Info( "Running with bypass of IP not available errors upon endpoint " + "restore. Be advised that this mode is intended to be " + "temporary to ease upgrades. Consider restarting the pods " + "which have IPs not from the pool.", ) default: option.Config.BypassIPAvailabilityUponRestore = false log.Warnf( "Bypassing IP allocation upon endpoint restore (%q) is enabled with"+ "unintended IPAM modes. This bypass is only intended "+ "to work for CRD-based IPAM modes such as ENI. Disabling "+ "bypass.", option.BypassIPAvailabilityUponRestore, ) } } } func (d *Daemon) initKVStore() { goopts := &kvstore.ExtraOptions{ ClusterSizeDependantInterval: d.nodeDiscovery.Manager.ClusterSizeDependantInterval, } controller.NewManager().UpdateController("kvstore-locks-gc", controller.ControllerParams{ DoFunc: func(ctx context.Context) error { kvstore.RunLockGC() return nil }, RunInterval: defaults.KVStoreStaleLockTimeout, Context: d.ctx, }, ) // If K8s is enabled we can do the service translation automagically by // looking at services from k8s and retrieve the service IP from that. // This makes cilium to not depend on kube dns to interact with etcd _, isETCDOperator := kvstore.IsEtcdOperator(option.Config.KVStore, option.Config.KVStoreOpt, option.Config.K8sNamespace) if k8s.IsEnabled() && isETCDOperator { // Wait services and endpoints cache are synced with k8s before setting // up etcd so we can perform the name resolution for etcd-operator // to the service IP as well perform the service -> backend IPs for // that service IP. d.k8sWatcher.WaitForCacheSync( watchers.K8sAPIGroupServiceV1Core, watchers.K8sAPIGroupEndpointV1Core, watchers.K8sAPIGroupEndpointSliceV1Discovery, watchers.K8sAPIGroupEndpointSliceV1Beta1Discovery, ) log := log.WithField(logfields.LogSubsys, "etcd") goopts.DialOption = []grpc.DialOption{ grpc.WithDialer(k8s.CreateCustomDialer(&d.k8sWatcher.K8sSvcCache, log)), } } if err := kvstore.Setup(context.TODO(), option.Config.KVStore, option.Config.KVStoreOpt, goopts); err != nil { addrkey := fmt.Sprintf("%s.address", option.Config.KVStore) addr := option.Config.KVStoreOpt[addrkey] log.WithError(err).WithFields(logrus.Fields{ "kvstore": option.Config.KVStore, "address": addr, }).Fatal("Unable to setup kvstore") } } func runDaemon() { datapathConfig := linuxdatapath.DatapathConfiguration{ HostDevice: option.Config.HostDevice, } log.Info("Initializing daemon") option.Config.RunMonitorAgent = true if err := enableIPForwarding(); err != nil { log.WithError(err).Fatal("Error when enabling sysctl parameters") } iptablesManager := &iptables.IptablesManager{} iptablesManager.Init() var wgAgent *wireguard.Agent if option.Config.EnableWireguard { switch { case option.Config.EnableIPSec: log.Fatalf("Wireguard (--%s) cannot be used with IPSec (--%s)", option.EnableWireguard, option.EnableIPSecName) case option.Config.EnableL7Proxy: log.Fatalf("Wireguard (--%s) is not compatible with L7 proxy (--%s)", option.EnableWireguard, option.EnableL7Proxy) } var err error privateKeyPath := filepath.Join(option.Config.StateDir, wireguardTypes.PrivKeyFilename) wgAgent, err = wireguard.NewAgent(privateKeyPath) if err != nil { log.WithError(err).Fatal("Failed to initialize wireguard") } cleaner.cleanupFuncs.Add(func() { _ = wgAgent.Close() }) } else { // Delete wireguard device from previous run (if such exists) link.DeleteByName(wireguardTypes.IfaceName) } if k8s.IsEnabled() { bootstrapStats.k8sInit.Start() if err := k8s.Init(option.Config); err != nil { log.WithError(err).Fatal("Unable to initialize Kubernetes subsystem") } bootstrapStats.k8sInit.End(true) } ctx, cancel := context.WithCancel(server.ServerCtx) d, restoredEndpoints, err := NewDaemon(ctx, cancel, WithDefaultEndpointManager(ctx, endpoint.CheckHealth), linuxdatapath.NewDatapath(datapathConfig, iptablesManager, wgAgent)) if err != nil { select { case <-server.ServerCtx.Done(): log.WithError(err).Debug("Error while creating daemon") default: log.WithError(err).Fatal("Error while creating daemon") } return } // This validation needs to be done outside of the agent until // datapath.NodeAddressing is used consistently across the code base. log.Info("Validating configured node address ranges") if err := node.ValidatePostInit(); err != nil { log.WithError(err).Fatal("postinit failed") } bootstrapStats.enableConntrack.Start() log.Info("Starting connection tracking garbage collector") gc.Enable(option.Config.EnableIPv4, option.Config.EnableIPv6, restoredEndpoints.restored, d.endpointManager) bootstrapStats.enableConntrack.End(true) bootstrapStats.k8sInit.Start() if k8s.IsEnabled() { // Wait only for certain caches, but not all! // (Check Daemon.InitK8sSubsystem() for more info) <-d.k8sCachesSynced } bootstrapStats.k8sInit.End(true) restoreComplete := d.initRestore(restoredEndpoints) if wgAgent != nil { if err := wgAgent.RestoreFinished(); err != nil { log.WithError(err).Error("Failed to set up wireguard peers") } } if d.endpointManager.HostEndpointExists() { d.endpointManager.InitHostEndpointLabels(d.ctx) } else { log.Info("Creating host endpoint") if err := d.endpointManager.AddHostEndpoint( d.ctx, d, d, d.l7Proxy, d.identityAllocator, "Create host endpoint", nodeTypes.GetName(), ); err != nil { log.WithError(err).Fatal("Unable to create host endpoint") } } if option.Config.EnableIPMasqAgent { ipmasqAgent, err := ipmasq.NewIPMasqAgent(option.Config.IPMasqAgentConfigPath) if err != nil { log.WithError(err).Fatal("Failed to create ip-masq-agent") } ipmasqAgent.Start() } if !option.Config.DryMode { go func() { if restoreComplete != nil { <-restoreComplete } d.dnsNameManager.CompleteBootstrap() ms := maps.NewMapSweeper(&EndpointMapManager{ EndpointManager: d.endpointManager, }) ms.CollectStaleMapGarbage() ms.RemoveDisabledMaps() }() d.endpointManager.Subscribe(d) defer d.endpointManager.Unsubscribe(d) } // Migrating the ENI datapath must happen before the API is served to // prevent endpoints from being created. It also must be before the health // initialization logic which creates the health endpoint, for the same // reasons as the API being served. We want to ensure that this migration // logic runs before any endpoint creates. if option.Config.IPAM == ipamOption.IPAMENI { migrated, failed := linuxrouting.NewMigrator( &eni.InterfaceDB{}, ).MigrateENIDatapath(option.Config.EgressMultiHomeIPRuleCompat) switch { case failed == -1: // No need to handle this case specifically because it is handled // in the call already. case migrated >= 0 && failed > 0: log.Errorf("Failed to migrate ENI datapath. "+ "%d endpoints were successfully migrated and %d failed to migrate completely. "+ "The original datapath is still in-place, however it is recommended to retry the migration.", migrated, failed) case migrated >= 0 && failed == 0: log.Infof("Migration of ENI datapath successful, %d endpoints were migrated and none failed.", migrated) } } bootstrapStats.healthCheck.Start() if option.Config.EnableHealthChecking { d.initHealth() } bootstrapStats.healthCheck.End(true) d.startStatusCollector() metricsErrs := initMetrics() d.startAgentHealthHTTPService() if option.Config.KubeProxyReplacementHealthzBindAddr != "" { if option.Config.KubeProxyReplacement != option.KubeProxyReplacementDisabled { d.startKubeProxyHealthzHTTPService(fmt.Sprintf("%s", option.Config.KubeProxyReplacementHealthzBindAddr)) } } bootstrapStats.initAPI.Start() srv := server.NewServer(d.instantiateAPI()) srv.EnabledListeners = []string{"unix"} srv.SocketPath = option.Config.SocketPath srv.ReadTimeout = apiTimeout srv.WriteTimeout = apiTimeout defer srv.Shutdown() srv.ConfigureAPI() bootstrapStats.initAPI.End(true) err = d.SendNotification(monitorAPI.StartMessage(time.Now())) if err != nil { log.WithError(err).Warn("Failed to send agent start monitor message") } if !d.datapath.Node().NodeNeighDiscoveryEnabled() { // Remove all non-GC'ed neighbor entries that might have previously set // by a Cilium instance. d.datapath.Node().NodeCleanNeighbors(false) } else { // If we came from an agent upgrade, migrate entries. d.datapath.Node().NodeCleanNeighbors(true) // Start periodical refresh of the neighbor table from the agent if needed. if option.Config.ARPPingRefreshPeriod != 0 && !option.Config.ARPPingKernelManaged { d.nodeDiscovery.Manager.StartNeighborRefresh(d.datapath.Node()) } } log.WithField("bootstrapTime", time.Since(bootstrapTimestamp)). Info("Daemon initialization completed") if option.Config.WriteCNIConfigurationWhenReady != "" { input, err := os.ReadFile(option.Config.ReadCNIConfiguration) if err != nil { log.WithError(err).Fatal("Unable to read CNI configuration file") } if err = os.WriteFile(option.Config.WriteCNIConfigurationWhenReady, input, 0644); err != nil { log.WithError(err).Fatalf("Unable to write CNI configuration file to %s", option.Config.WriteCNIConfigurationWhenReady) } else { log.Infof("Wrote CNI configuration file to %s", option.Config.WriteCNIConfigurationWhenReady) } } errs := make(chan error, 1) go func() { errs <- srv.Serve() }() if k8s.IsEnabled() { bootstrapStats.k8sInit.Start() k8s.Client().MarkNodeReady(d.k8sWatcher, nodeTypes.GetName()) bootstrapStats.k8sInit.End(true) } bootstrapStats.overall.End(true) bootstrapStats.updateMetrics() go d.launchHubble() err = option.Config.StoreInFile(option.Config.StateDir) if err != nil { log.WithError(err).Error("Unable to store Cilium's configuration") } err = option.StoreViperInFile(option.Config.StateDir) if err != nil { log.WithError(err).Error("Unable to store Viper's configuration") } select { case err := <-metricsErrs: if err != nil { log.WithError(err).Fatal("Cannot start metrics server") } case err := <-errs: if err != nil { log.WithError(err).Fatal("Error returned from non-returning Serve() call") } } } func (d *Daemon) instantiateAPI() *restapi.CiliumAPIAPI { swaggerSpec, err := loads.Analyzed(server.SwaggerJSON, "") if err != nil { log.WithError(err).Fatal("Cannot load swagger spec") } log.Info("Initializing Cilium API") restAPI := restapi.NewCiliumAPIAPI(swaggerSpec) restAPI.Logger = log.Infof // /healthz/ restAPI.DaemonGetHealthzHandler = NewGetHealthzHandler(d) // /cluster/nodes restAPI.DaemonGetClusterNodesHandler = NewGetClusterNodesHandler(d) // /config/ restAPI.DaemonGetConfigHandler = NewGetConfigHandler(d) restAPI.DaemonPatchConfigHandler = NewPatchConfigHandler(d) if option.Config.DatapathMode != datapathOption.DatapathModeLBOnly { // /endpoint/ restAPI.EndpointGetEndpointHandler = NewGetEndpointHandler(d) // /endpoint/{id} restAPI.EndpointGetEndpointIDHandler = NewGetEndpointIDHandler(d) restAPI.EndpointPutEndpointIDHandler = NewPutEndpointIDHandler(d) restAPI.EndpointPatchEndpointIDHandler = NewPatchEndpointIDHandler(d) restAPI.EndpointDeleteEndpointIDHandler = NewDeleteEndpointIDHandler(d) // /endpoint/{id}config/ restAPI.EndpointGetEndpointIDConfigHandler = NewGetEndpointIDConfigHandler(d) restAPI.EndpointPatchEndpointIDConfigHandler = NewPatchEndpointIDConfigHandler(d) // /endpoint/{id}/labels/ restAPI.EndpointGetEndpointIDLabelsHandler = NewGetEndpointIDLabelsHandler(d) restAPI.EndpointPatchEndpointIDLabelsHandler = NewPatchEndpointIDLabelsHandler(d) // /endpoint/{id}/log/ restAPI.EndpointGetEndpointIDLogHandler = NewGetEndpointIDLogHandler(d) // /endpoint/{id}/healthz restAPI.EndpointGetEndpointIDHealthzHandler = NewGetEndpointIDHealthzHandler(d) // /identity/ restAPI.PolicyGetIdentityHandler = newGetIdentityHandler(d) restAPI.PolicyGetIdentityIDHandler = newGetIdentityIDHandler(d.identityAllocator) // /identity/endpoints restAPI.PolicyGetIdentityEndpointsHandler = newGetIdentityEndpointsIDHandler(d) // /policy/ restAPI.PolicyGetPolicyHandler = newGetPolicyHandler(d.policy) restAPI.PolicyPutPolicyHandler = newPutPolicyHandler(d) restAPI.PolicyDeletePolicyHandler = newDeletePolicyHandler(d) restAPI.PolicyGetPolicySelectorsHandler = newGetPolicyCacheHandler(d) // /policy/resolve/ restAPI.PolicyGetPolicyResolveHandler = NewGetPolicyResolveHandler(d) // /lrp/ restAPI.ServiceGetLrpHandler = NewGetLrpHandler(d.redirectPolicyManager) } // /service/{id}/ restAPI.ServiceGetServiceIDHandler = NewGetServiceIDHandler(d.svc) restAPI.ServiceDeleteServiceIDHandler = NewDeleteServiceIDHandler(d.svc) restAPI.ServicePutServiceIDHandler = NewPutServiceIDHandler(d.svc) // /service/ restAPI.ServiceGetServiceHandler = NewGetServiceHandler(d.svc) // /recorder/{id}/ restAPI.RecorderGetRecorderIDHandler = NewGetRecorderIDHandler(d.rec) restAPI.RecorderDeleteRecorderIDHandler = NewDeleteRecorderIDHandler(d.rec) restAPI.RecorderPutRecorderIDHandler = NewPutRecorderIDHandler(d.rec) // /recorder/ restAPI.RecorderGetRecorderHandler = NewGetRecorderHandler(d.rec) // /recorder/masks restAPI.RecorderGetRecorderMasksHandler = NewGetRecorderMasksHandler(d.rec) // /prefilter/ restAPI.PrefilterGetPrefilterHandler = NewGetPrefilterHandler(d) restAPI.PrefilterDeletePrefilterHandler = NewDeletePrefilterHandler(d) restAPI.PrefilterPatchPrefilterHandler = NewPatchPrefilterHandler(d) if option.Config.DatapathMode != datapathOption.DatapathModeLBOnly { // /ipam/{ip}/ restAPI.IpamPostIpamHandler = NewPostIPAMHandler(d) restAPI.IpamPostIpamIPHandler = NewPostIPAMIPHandler(d) restAPI.IpamDeleteIpamIPHandler = NewDeleteIPAMIPHandler(d) } // /debuginfo restAPI.DaemonGetDebuginfoHandler = NewGetDebugInfoHandler(d) // /map restAPI.DaemonGetMapHandler = NewGetMapHandler(d) restAPI.DaemonGetMapNameHandler = NewGetMapNameHandler(d) // metrics restAPI.MetricsGetMetricsHandler = NewGetMetricsHandler(d) if option.Config.DatapathMode != datapathOption.DatapathModeLBOnly { // /fqdn/cache restAPI.PolicyGetFqdnCacheHandler = NewGetFqdnCacheHandler(d) restAPI.PolicyDeleteFqdnCacheHandler = NewDeleteFqdnCacheHandler(d) restAPI.PolicyGetFqdnCacheIDHandler = NewGetFqdnCacheIDHandler(d) restAPI.PolicyGetFqdnNamesHandler = NewGetFqdnNamesHandler(d) } // /ip/ restAPI.PolicyGetIPHandler = NewGetIPHandler() return restAPI } func initSockmapOption() { if !option.Config.SockopsEnable { return } if probes.NewProbeManager().GetMapTypes().HaveSockhashMapType { k := probes.NewProbeManager().GetHelpers("sock_ops") h := probes.NewProbeManager().GetHelpers("sk_msg") if h != nil && k != nil { return } } log.Warn("BPF Sock ops not supported by kernel. Disabling '--sockops-enable' feature.") option.Config.SockopsEnable = false } func initClockSourceOption()
{ option.Config.ClockSource = option.ClockSourceKtime option.Config.KernelHz = 1 // Known invalid non-zero to avoid div by zero. if !option.Config.DryMode { hz, err := probes.NewProbeManager().SystemKernelHz() if err != nil { log.WithError(err).Infof("Auto-disabling %q feature since KERNEL_HZ cannot be determined", option.EnableBPFClockProbe) option.Config.EnableBPFClockProbe = false } else { option.Config.KernelHz = hz } if option.Config.EnableBPFClockProbe { if h := probes.NewProbeManager().GetHelpers("xdp"); h != nil { if _, ok := h["bpf_jiffies64"]; ok { t, err := bpf.GetJtime() if err == nil && t > 0 { option.Config.ClockSource = option.ClockSourceJiffies } } } } } }
test_support.py
#!/usr/bin/env python # # Copyright 2007 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """Utilities to aid in testing mapreduces.""" import base64 import collections import logging import os import re from google.appengine.ext.mapreduce import main from google.appengine.ext.mapreduce import model from google.appengine.ext.webapp import mock_webapp _LOGGING_LEVEL = logging.ERROR logging.getLogger().setLevel(_LOGGING_LEVEL) def decode_task_payload(task): """Decodes POST task payload. This can only decode POST payload for a normal task. For huge task, use model.HugeTask.decode_payload. Args: task: a dict representing a taskqueue task as documented in taskqueue_stub. Returns: parameter_name -> parameter_value dict. If multiple parameter values are present, then parameter_value will be a list. """ if not task: return {} body = base64.b64decode(task["body"]) return model.HugeTask._decode_payload(body) def execute_task(task, retries=0, handlers_map=None): """Execute mapper's executor task. This will try to determine the correct mapper handler for the task, will set up all mock environment necessary for task execution, and execute the task itself. This function can be used for functional-style testing of functionality depending on mapper framework. Args: task: a taskqueue task. retries: the current retry of this task. handlers_map: a dict from url regex to handler. Returns: the handler instance used for this task. Raises: Exception: whatever the task raises. """ if not handlers_map: handlers_map = main.create_handlers_map() url = task["url"] handler = None params = [] for (re_str, handler_class) in handlers_map: re_str = "^" + re_str + "($|\\?)" m = re.match(re_str, url) if m: params = m.groups()[:-1] break else: raise Exception("Can't determine handler for %s" % task) request = mock_webapp.MockRequest() request.set_url(url) version = "mr-test-support-version.1" module = "mr-test-support-module" default_version_hostname = "mr-test-support.appspot.com" host = "%s.%s.%s" % (version.split(".")[0], module, default_version_hostname) if "CURRENT_VERSION_ID" not in os.environ: request.environ["CURRENT_VERSION_ID"] = version if "DEFAULT_VERSION_HOSTNAME" not in os.environ: request.environ["DEFAULT_VERSION_HOSTNAME"] = ( default_version_hostname) if "CURRENT_MODULE_ID" not in os.environ: request.environ["CURRENT_MODULE_ID"] = module if "HTTP_HOST" not in os.environ: request.environ["HTTP_HOST"] = host for k, v in task.get("headers", []): request.headers[k] = v environ_key = "HTTP_" + k.replace("-", "_").upper() request.environ[environ_key] = v request.headers["X-AppEngine-TaskExecutionCount"] = retries request.environ["HTTP_X_APPENGINE_TASKNAME"] = ( task.get("name", "default_task_name")) request.environ["HTTP_X_APPENGINE_QUEUENAME"] = ( task.get("queue_name", "default")) request.environ["PATH_INFO"] = request.path if task["method"] == "POST": request.body = base64.b64decode(task["body"]) for k, v in decode_task_payload(task).iteritems(): request.set(k, v) response = mock_webapp.MockResponse() saved_os_environ = os.environ copy_os_environ = dict(os.environ) copy_os_environ.update(request.environ) try: os.environ = copy_os_environ handler = handler_class(request, response) except TypeError: handler = handler_class() handler.initialize(request, response) finally: os.environ = saved_os_environ try: os.environ = copy_os_environ if task["method"] == "POST": handler.post(*params) elif task["method"] == "GET": handler.get(*params) else: raise Exception("Unsupported method: %s" % task.method) finally: os.environ = saved_os_environ if handler.response.status != 200: raise Exception("Handler failure: %s (%s). \nTask: %s\nHandler: %s" % (handler.response.status, handler.response.status_message, task, handler)) return handler def execute_all_tasks(taskqueue, queue="default", handlers_map=None, run_count=1):
def execute_until_empty(taskqueue, queue="default", handlers_map=None, run_count=1): """Execute taskqueue tasks until it becomes empty. Args: taskqueue: An instance of taskqueue stub. queue: Queue name to run all tasks from. handlers_map: see main.create_handlers_map. run_count: How many times to run each task (to test idempotency). Returns: task_run_counts: a dict from handler class to the number of tasks it handled. """ task_run_counts = collections.defaultdict(lambda: 0) while taskqueue.GetTasks(queue): new_counts = execute_all_tasks( taskqueue, queue, handlers_map, run_count=run_count) for handler_cls in new_counts: task_run_counts[handler_cls] += new_counts[handler_cls] return task_run_counts
"""Run and remove all tasks in the taskqueue. Args: taskqueue: An instance of taskqueue stub. queue: Queue name to run all tasks from. handlers_map: see main.create_handlers_map. run_count: How many times to run each task (to test idempotency). Returns: task_run_counts: a dict from handler class to the number of tasks it handled. """ tasks = taskqueue.GetTasks(queue) taskqueue.FlushQueue(queue) task_run_counts = collections.defaultdict(lambda: 0) for task in tasks: retries = 0 while True: try: for _ in range(run_count): handler = execute_task(task, retries, handlers_map=handlers_map) task_run_counts[handler.__class__] += 1 break except Exception, e: retries += 1 if retries > 100: logging.debug("Task %s failed for too many times. Giving up.", task["name"]) raise logging.debug( "Task %s is being retried for the %s time", task["name"], retries) logging.debug(e) return task_run_counts
surveyor.go
// Copyright 2016 The Mangos Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use file except in compliance with the License. // You may obtain a copy of the license at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Package surveyor implements the SURVEYOR protocol. This sends messages // out to RESPONDENT partners, and receives their responses. package surveyor import ( "encoding/binary" "sync" "time" "github.com/go-mangos/mangos" ) const defaultSurveyTime = time.Second type surveyor struct { sock mangos.ProtocolSocket peers map[uint32]*surveyorP raw bool nextID uint32 surveyID uint32 duration time.Duration timeout time.Time timer *time.Timer w mangos.Waiter init sync.Once ttl int sync.Mutex } type surveyorP struct { q chan *mangos.Message ep mangos.Endpoint x *surveyor } func (x *surveyor) Init(sock mangos.ProtocolSocket) { x.sock = sock x.peers = make(map[uint32]*surveyorP) x.sock.SetRecvError(mangos.ErrProtoState) x.timer = time.AfterFunc(x.duration, func() { x.sock.SetRecvError(mangos.ErrProtoState) }) x.timer.Stop() x.w.Init() x.w.Add() go x.sender() } func (x *surveyor) Shutdown(expire time.Time) { x.w.WaitAbsTimeout(expire) x.Lock() peers := x.peers x.peers = make(map[uint32]*surveyorP) x.Unlock() for id, peer := range peers { delete(peers, id) mangos.DrainChannel(peer.q, expire) close(peer.q) } } func (x *surveyor) sender() { defer x.w.Done() cq := x.sock.CloseChannel() for { var m *mangos.Message select { case m = <-x.sock.SendChannel(): case <-cq: return } x.Lock() for _, pe := range x.peers { m := m.Dup() select { case pe.q <- m: default: m.Free() } } x.Unlock() } } // When sending, we should have the survey ID in the header. func (peer *surveyorP) sender() { for { if m := <-peer.q; m == nil { break } else { if peer.ep.SendMsg(m) != nil { m.Free() return } } } } func (peer *surveyorP) receiver() { rq := peer.x.sock.RecvChannel() cq := peer.x.sock.CloseChannel() for { m := peer.ep.RecvMsg() if m == nil { return } if len(m.Body) < 4 { m.Free() continue } // Get survery ID -- this will be passed in the header up // to the application. It should include that in the response. m.Header = append(m.Header, m.Body[:4]...) m.Body = m.Body[4:] select { case rq <- m: case <-cq: return } } } func (x *surveyor) AddEndpoint(ep mangos.Endpoint) { peer := &surveyorP{ep: ep, x: x, q: make(chan *mangos.Message, 1)} x.Lock() x.peers[ep.GetID()] = peer go peer.receiver() go peer.sender() x.Unlock() } func (x *surveyor) RemoveEndpoint(ep mangos.Endpoint) { id := ep.GetID() x.Lock() peer := x.peers[id] delete(x.peers, id) x.Unlock() if peer != nil { close(peer.q) } } func (*surveyor) Number() uint16 { return mangos.ProtoSurveyor } func (*surveyor) PeerNumber() uint16 { return mangos.ProtoRespondent } func (*surveyor) Name() string { return "surveyor" } func (*surveyor) PeerName() string { return "respondent" } func (x *surveyor) SendHook(m *mangos.Message) bool { if x.raw { return true } x.Lock() x.surveyID = x.nextID | 0x80000000 x.nextID++ x.sock.SetRecvError(nil) v := x.surveyID m.Header = append(m.Header, byte(v>>24), byte(v>>16), byte(v>>8), byte(v)) if x.duration > 0 { x.timer.Reset(x.duration) } x.Unlock() return true } func (x *surveyor) RecvHook(m *mangos.Message) bool { if x.raw { return true } x.Lock() defer x.Unlock() if len(m.Header) < 4 { return false } if binary.BigEndian.Uint32(m.Header) != x.surveyID { return false } m.Header = m.Header[4:] return true } func (x *surveyor) SetOption(name string, val interface{}) error { var ok bool switch name { case mangos.OptionRaw: if x.raw, ok = val.(bool); !ok { return mangos.ErrBadValue } if x.raw { x.timer.Stop() x.sock.SetRecvError(nil) } else { x.sock.SetRecvError(mangos.ErrProtoState) } return nil case mangos.OptionSurveyTime: x.Lock() x.duration, ok = val.(time.Duration) x.Unlock() if !ok { return mangos.ErrBadValue } return nil case mangos.OptionTTL: // We don't do anything with this, but support it for // symmetry with the respondent socket. if ttl, ok := val.(int); !ok { return mangos.ErrBadValue } else if ttl < 1 || ttl > 255 { return mangos.ErrBadValue } else { x.ttl = ttl } return nil default: return mangos.ErrBadOption } } func (x *surveyor) GetOption(name string) (interface{}, error) { switch name { case mangos.OptionRaw: return x.raw, nil case mangos.OptionSurveyTime: x.Lock() d := x.duration x.Unlock() return d, nil case mangos.OptionTTL: return x.ttl, nil default: return nil, mangos.ErrBadOption } } // NewSocket allocates a new Socket using the SURVEYOR protocol. func
() (mangos.Socket, error) { return mangos.MakeSocket(&surveyor{duration: defaultSurveyTime}), nil }
NewSocket
cluster.go
// Copyright 2018 The etcd Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package tester import ( "context" "errors" "fmt" "io" "io/ioutil" "math/rand" "net/http" "net/url" "path/filepath" "strings" "sync" "time" "github.com/matheusd/etcd/functional/rpcpb" "github.com/matheusd/etcd/pkg/debugutil" "github.com/matheusd/etcd/pkg/fileutil" "github.com/prometheus/client_golang/prometheus/promhttp" "go.uber.org/zap" "golang.org/x/time/rate" "google.golang.org/grpc" ) // Cluster defines tester cluster. type Cluster struct { lg *zap.Logger agentConns []*grpc.ClientConn agentClients []rpcpb.TransportClient agentStreams []rpcpb.Transport_TransportClient agentRequests []*rpcpb.Request testerHTTPServer *http.Server Members []*rpcpb.Member `yaml:"agent-configs"` Tester *rpcpb.Tester `yaml:"tester-config"` cases []Case rateLimiter *rate.Limiter stresser Stresser checkers []Checker currentRevision int64 rd int cs int } var dialOpts = []grpc.DialOption{ grpc.WithInsecure(), grpc.WithTimeout(5 * time.Second), grpc.WithBlock(), } // NewCluster creates a client from a tester configuration. func
(lg *zap.Logger, fpath string) (*Cluster, error) { clus, err := read(lg, fpath) if err != nil { return nil, err } clus.agentConns = make([]*grpc.ClientConn, len(clus.Members)) clus.agentClients = make([]rpcpb.TransportClient, len(clus.Members)) clus.agentStreams = make([]rpcpb.Transport_TransportClient, len(clus.Members)) clus.agentRequests = make([]*rpcpb.Request, len(clus.Members)) clus.cases = make([]Case, 0) for i, ap := range clus.Members { var err error clus.agentConns[i], err = grpc.Dial(ap.AgentAddr, dialOpts...) if err != nil { return nil, err } clus.agentClients[i] = rpcpb.NewTransportClient(clus.agentConns[i]) clus.lg.Info("connected", zap.String("agent-address", ap.AgentAddr)) clus.agentStreams[i], err = clus.agentClients[i].Transport(context.Background()) if err != nil { return nil, err } clus.lg.Info("created stream", zap.String("agent-address", ap.AgentAddr)) } mux := http.NewServeMux() mux.Handle("/metrics", promhttp.Handler()) if clus.Tester.EnablePprof { for p, h := range debugutil.PProfHandlers() { mux.Handle(p, h) } } clus.testerHTTPServer = &http.Server{ Addr: clus.Tester.Addr, Handler: mux, } go clus.serveTesterServer() clus.updateCases() clus.rateLimiter = rate.NewLimiter( rate.Limit(int(clus.Tester.StressQPS)), int(clus.Tester.StressQPS), ) clus.setStresserChecker() return clus, nil } // EtcdClientEndpoints returns all etcd client endpoints. func (clus *Cluster) EtcdClientEndpoints() (css []string) { css = make([]string, len(clus.Members)) for i := range clus.Members { css[i] = clus.Members[i].EtcdClientEndpoint } return css } func (clus *Cluster) serveTesterServer() { clus.lg.Info( "started tester HTTP server", zap.String("tester-address", clus.Tester.Addr), ) err := clus.testerHTTPServer.ListenAndServe() clus.lg.Info( "tester HTTP server returned", zap.String("tester-address", clus.Tester.Addr), zap.Error(err), ) if err != nil && err != http.ErrServerClosed { clus.lg.Fatal("tester HTTP errored", zap.Error(err)) } } func (clus *Cluster) updateCases() { for _, cs := range clus.Tester.Cases { switch cs { case "SIGTERM_ONE_FOLLOWER": clus.cases = append(clus.cases, new_Case_SIGTERM_ONE_FOLLOWER(clus)) case "SIGTERM_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_SIGTERM_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT(clus)) case "SIGTERM_LEADER": clus.cases = append(clus.cases, new_Case_SIGTERM_LEADER(clus)) case "SIGTERM_LEADER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_SIGTERM_LEADER_UNTIL_TRIGGER_SNAPSHOT(clus)) case "SIGTERM_QUORUM": clus.cases = append(clus.cases, new_Case_SIGTERM_QUORUM(clus)) case "SIGTERM_ALL": clus.cases = append(clus.cases, new_Case_SIGTERM_ALL(clus)) case "SIGQUIT_AND_REMOVE_ONE_FOLLOWER": clus.cases = append(clus.cases, new_Case_SIGQUIT_AND_REMOVE_ONE_FOLLOWER(clus)) case "SIGQUIT_AND_REMOVE_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_SIGQUIT_AND_REMOVE_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT(clus)) case "SIGQUIT_AND_REMOVE_LEADER": clus.cases = append(clus.cases, new_Case_SIGQUIT_AND_REMOVE_LEADER(clus)) case "SIGQUIT_AND_REMOVE_LEADER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_SIGQUIT_AND_REMOVE_LEADER_UNTIL_TRIGGER_SNAPSHOT(clus)) case "SIGQUIT_AND_REMOVE_QUORUM_AND_RESTORE_LEADER_SNAPSHOT_FROM_SCRATCH": clus.cases = append(clus.cases, new_Case_SIGQUIT_AND_REMOVE_QUORUM_AND_RESTORE_LEADER_SNAPSHOT_FROM_SCRATCH(clus)) case "BLACKHOLE_PEER_PORT_TX_RX_ONE_FOLLOWER": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_ONE_FOLLOWER(clus)) case "BLACKHOLE_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT()) case "BLACKHOLE_PEER_PORT_TX_RX_LEADER": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_LEADER(clus)) case "BLACKHOLE_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT()) case "BLACKHOLE_PEER_PORT_TX_RX_QUORUM": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_QUORUM(clus)) case "BLACKHOLE_PEER_PORT_TX_RX_ALL": clus.cases = append(clus.cases, new_Case_BLACKHOLE_PEER_PORT_TX_RX_ALL(clus)) case "DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER(clus, true)) case "DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ONE_FOLLOWER_UNTIL_TRIGGER_SNAPSHOT(clus, true)) case "DELAY_PEER_PORT_TX_RX_LEADER": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_LEADER(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_LEADER": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_LEADER(clus, true)) case "DELAY_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_LEADER_UNTIL_TRIGGER_SNAPSHOT(clus, true)) case "DELAY_PEER_PORT_TX_RX_QUORUM": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_QUORUM(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_QUORUM": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_QUORUM(clus, true)) case "DELAY_PEER_PORT_TX_RX_ALL": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ALL(clus, false)) case "RANDOM_DELAY_PEER_PORT_TX_RX_ALL": clus.cases = append(clus.cases, new_Case_DELAY_PEER_PORT_TX_RX_ALL(clus, true)) case "NO_FAIL_WITH_STRESS": clus.cases = append(clus.cases, new_Case_NO_FAIL_WITH_STRESS(clus)) case "NO_FAIL_WITH_NO_STRESS_FOR_LIVENESS": clus.cases = append(clus.cases, new_Case_NO_FAIL_WITH_NO_STRESS_FOR_LIVENESS(clus)) case "EXTERNAL": clus.cases = append(clus.cases, new_Case_EXTERNAL(clus.Tester.ExternalExecPath)) case "FAILPOINTS": fpFailures, fperr := failpointFailures(clus) if len(fpFailures) == 0 { clus.lg.Info("no failpoints found!", zap.Error(fperr)) } clus.cases = append(clus.cases, fpFailures...) } } } func (clus *Cluster) listCases() (css []string) { css = make([]string, len(clus.cases)) for i := range clus.cases { css[i] = clus.cases[i].Desc() } return css } // UpdateDelayLatencyMs updates delay latency with random value // within election timeout. func (clus *Cluster) UpdateDelayLatencyMs() { rand.Seed(time.Now().UnixNano()) clus.Tester.UpdatedDelayLatencyMs = uint32(rand.Int63n(clus.Members[0].Etcd.ElectionTimeoutMs)) minLatRv := clus.Tester.DelayLatencyMsRv + clus.Tester.DelayLatencyMsRv/5 if clus.Tester.UpdatedDelayLatencyMs <= minLatRv { clus.Tester.UpdatedDelayLatencyMs += minLatRv } } func (clus *Cluster) setStresserChecker() { css := &compositeStresser{} lss := []*leaseStresser{} rss := []*runnerStresser{} for _, m := range clus.Members { sss := newStresser(clus, m) css.stressers = append(css.stressers, &compositeStresser{sss}) for _, s := range sss { if v, ok := s.(*leaseStresser); ok { lss = append(lss, v) clus.lg.Info("added lease stresser", zap.String("endpoint", m.EtcdClientEndpoint)) } if v, ok := s.(*runnerStresser); ok { rss = append(rss, v) clus.lg.Info("added lease stresser", zap.String("endpoint", m.EtcdClientEndpoint)) } } } clus.stresser = css for _, cs := range clus.Tester.Checkers { switch cs { case "KV_HASH": clus.checkers = append(clus.checkers, newKVHashChecker(clus)) case "LEASE_EXPIRE": for _, ls := range lss { clus.checkers = append(clus.checkers, newLeaseExpireChecker(ls)) } case "RUNNER": for _, rs := range rss { clus.checkers = append(clus.checkers, newRunnerChecker(rs.etcdClientEndpoint, rs.errc)) } case "NO_CHECK": clus.checkers = append(clus.checkers, newNoChecker()) } } clus.lg.Info("updated stressers") } func (clus *Cluster) runCheckers(exceptions ...rpcpb.Checker) (err error) { defer func() { if err != nil { return } if err = clus.updateRevision(); err != nil { clus.lg.Warn( "updateRevision failed", zap.Error(err), ) return } }() exs := make(map[rpcpb.Checker]struct{}) for _, e := range exceptions { exs[e] = struct{}{} } for _, chk := range clus.checkers { clus.lg.Warn( "consistency check START", zap.String("checker", chk.Type().String()), zap.Strings("client-endpoints", chk.EtcdClientEndpoints()), ) err = chk.Check() clus.lg.Warn( "consistency check END", zap.String("checker", chk.Type().String()), zap.Strings("client-endpoints", chk.EtcdClientEndpoints()), zap.Error(err), ) if err != nil { _, ok := exs[chk.Type()] if !ok { return err } clus.lg.Warn( "consistency check SKIP FAIL", zap.String("checker", chk.Type().String()), zap.Strings("client-endpoints", chk.EtcdClientEndpoints()), zap.Error(err), ) } } return nil } // Send_INITIAL_START_ETCD bootstraps etcd cluster the very first time. // After this, just continue to call kill/restart. func (clus *Cluster) Send_INITIAL_START_ETCD() error { // this is the only time that creates request from scratch return clus.broadcast(rpcpb.Operation_INITIAL_START_ETCD) } // send_SIGQUIT_ETCD_AND_ARCHIVE_DATA sends "send_SIGQUIT_ETCD_AND_ARCHIVE_DATA" operation. func (clus *Cluster) send_SIGQUIT_ETCD_AND_ARCHIVE_DATA() error { return clus.broadcast(rpcpb.Operation_SIGQUIT_ETCD_AND_ARCHIVE_DATA) } // send_RESTART_ETCD sends restart operation. func (clus *Cluster) send_RESTART_ETCD() error { return clus.broadcast(rpcpb.Operation_RESTART_ETCD) } func (clus *Cluster) broadcast(op rpcpb.Operation) error { var wg sync.WaitGroup wg.Add(len(clus.agentStreams)) errc := make(chan error, len(clus.agentStreams)) for i := range clus.agentStreams { go func(idx int, o rpcpb.Operation) { defer wg.Done() errc <- clus.sendOp(idx, o) }(i, op) } wg.Wait() close(errc) errs := []string{} for err := range errc { if err == nil { continue } if err != nil { destroyed := false if op == rpcpb.Operation_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT { if err == io.EOF { destroyed = true } if strings.Contains(err.Error(), "rpc error: code = Unavailable desc = transport is closing") { // agent server has already closed; // so this error is expected destroyed = true } if strings.Contains(err.Error(), "desc = os: process already finished") { destroyed = true } } if !destroyed { errs = append(errs, err.Error()) } } } if len(errs) == 0 { return nil } return errors.New(strings.Join(errs, ", ")) } func (clus *Cluster) sendOp(idx int, op rpcpb.Operation) error { _, err := clus.sendOpWithResp(idx, op) return err } func (clus *Cluster) sendOpWithResp(idx int, op rpcpb.Operation) (*rpcpb.Response, error) { // maintain the initial member object // throughout the test time clus.agentRequests[idx] = &rpcpb.Request{ Operation: op, Member: clus.Members[idx], Tester: clus.Tester, } err := clus.agentStreams[idx].Send(clus.agentRequests[idx]) clus.lg.Info( "sent request", zap.String("operation", op.String()), zap.String("to", clus.Members[idx].EtcdClientEndpoint), zap.Error(err), ) if err != nil { return nil, err } resp, err := clus.agentStreams[idx].Recv() if resp != nil { clus.lg.Info( "received response", zap.String("operation", op.String()), zap.String("from", clus.Members[idx].EtcdClientEndpoint), zap.Bool("success", resp.Success), zap.String("status", resp.Status), zap.Error(err), ) } else { clus.lg.Info( "received empty response", zap.String("operation", op.String()), zap.String("from", clus.Members[idx].EtcdClientEndpoint), zap.Error(err), ) } if err != nil { return nil, err } if !resp.Success { return nil, errors.New(resp.Status) } m, secure := clus.Members[idx], false for _, cu := range m.Etcd.AdvertiseClientURLs { u, err := url.Parse(cu) if err != nil { return nil, err } if u.Scheme == "https" { // TODO: handle unix secure = true } } // store TLS assets from agents/servers onto disk if secure && (op == rpcpb.Operation_INITIAL_START_ETCD || op == rpcpb.Operation_RESTART_ETCD) { dirClient := filepath.Join( clus.Tester.DataDir, clus.Members[idx].Etcd.Name, "fixtures", "client", ) if err = fileutil.TouchDirAll(dirClient); err != nil { return nil, err } clientCertData := []byte(resp.Member.ClientCertData) if len(clientCertData) == 0 { return nil, fmt.Errorf("got empty client cert from %q", m.EtcdClientEndpoint) } clientCertPath := filepath.Join(dirClient, "cert.pem") if err = ioutil.WriteFile(clientCertPath, clientCertData, 0644); err != nil { // overwrite if exists return nil, err } resp.Member.ClientCertPath = clientCertPath clus.lg.Info( "saved client cert file", zap.String("path", clientCertPath), ) clientKeyData := []byte(resp.Member.ClientKeyData) if len(clientKeyData) == 0 { return nil, fmt.Errorf("got empty client key from %q", m.EtcdClientEndpoint) } clientKeyPath := filepath.Join(dirClient, "key.pem") if err = ioutil.WriteFile(clientKeyPath, clientKeyData, 0644); err != nil { // overwrite if exists return nil, err } resp.Member.ClientKeyPath = clientKeyPath clus.lg.Info( "saved client key file", zap.String("path", clientKeyPath), ) clientTrustedCAData := []byte(resp.Member.ClientTrustedCAData) if len(clientTrustedCAData) != 0 { // TODO: disable this when auto TLS is deprecated clientTrustedCAPath := filepath.Join(dirClient, "ca.pem") if err = ioutil.WriteFile(clientTrustedCAPath, clientTrustedCAData, 0644); err != nil { // overwrite if exists return nil, err } resp.Member.ClientTrustedCAPath = clientTrustedCAPath clus.lg.Info( "saved client trusted CA file", zap.String("path", clientTrustedCAPath), ) } // no need to store peer certs for tester clients clus.Members[idx] = resp.Member } return resp, nil } // Send_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT terminates all tester connections to agents and etcd servers. func (clus *Cluster) Send_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT() { err := clus.broadcast(rpcpb.Operation_SIGQUIT_ETCD_AND_REMOVE_DATA_AND_STOP_AGENT) if err != nil { clus.lg.Warn("destroying etcd/agents FAIL", zap.Error(err)) } else { clus.lg.Info("destroying etcd/agents PASS") } for i, conn := range clus.agentConns { err := conn.Close() clus.lg.Info("closed connection to agent", zap.String("agent-address", clus.Members[i].AgentAddr), zap.Error(err)) } if clus.testerHTTPServer != nil { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) err := clus.testerHTTPServer.Shutdown(ctx) cancel() clus.lg.Info("closed tester HTTP server", zap.String("tester-address", clus.Tester.Addr), zap.Error(err)) } } // WaitHealth ensures all members are healthy // by writing a test key to etcd cluster. func (clus *Cluster) WaitHealth() error { var err error // wait 60s to check cluster health. // TODO: set it to a reasonable value. It is set that high because // follower may use long time to catch up the leader when reboot under // reasonable workload (https://github.com/coreos/etcd/issues/2698) for i := 0; i < 60; i++ { for _, m := range clus.Members { if err = m.WriteHealthKey(); err != nil { clus.lg.Warn( "health check FAIL", zap.Int("retries", i), zap.String("endpoint", m.EtcdClientEndpoint), zap.Error(err), ) break } clus.lg.Info( "health check PASS", zap.Int("retries", i), zap.String("endpoint", m.EtcdClientEndpoint), ) } if err == nil { clus.lg.Info("health check ALL PASS") return nil } time.Sleep(time.Second) } return err } // GetLeader returns the index of leader and error if any. func (clus *Cluster) GetLeader() (int, error) { for i, m := range clus.Members { isLeader, err := m.IsLeader() if isLeader || err != nil { return i, err } } return 0, fmt.Errorf("no leader found") } // maxRev returns the maximum revision found on the cluster. func (clus *Cluster) maxRev() (rev int64, err error) { ctx, cancel := context.WithTimeout(context.TODO(), time.Second) defer cancel() revc, errc := make(chan int64, len(clus.Members)), make(chan error, len(clus.Members)) for i := range clus.Members { go func(m *rpcpb.Member) { mrev, merr := m.Rev(ctx) revc <- mrev errc <- merr }(clus.Members[i]) } for i := 0; i < len(clus.Members); i++ { if merr := <-errc; merr != nil { err = merr } if mrev := <-revc; mrev > rev { rev = mrev } } return rev, err } func (clus *Cluster) getRevisionHash() (map[string]int64, map[string]int64, error) { revs := make(map[string]int64) hashes := make(map[string]int64) for _, m := range clus.Members { rev, hash, err := m.RevHash() if err != nil { return nil, nil, err } revs[m.EtcdClientEndpoint] = rev hashes[m.EtcdClientEndpoint] = hash } return revs, hashes, nil } func (clus *Cluster) compactKV(rev int64, timeout time.Duration) (err error) { if rev <= 0 { return nil } for i, m := range clus.Members { clus.lg.Info( "compact START", zap.String("endpoint", m.EtcdClientEndpoint), zap.Int64("compact-revision", rev), zap.Duration("timeout", timeout), ) now := time.Now() cerr := m.Compact(rev, timeout) succeed := true if cerr != nil { if strings.Contains(cerr.Error(), "required revision has been compacted") && i > 0 { clus.lg.Info( "compact error is ignored", zap.String("endpoint", m.EtcdClientEndpoint), zap.Int64("compact-revision", rev), zap.Error(cerr), ) } else { clus.lg.Warn( "compact FAIL", zap.String("endpoint", m.EtcdClientEndpoint), zap.Int64("compact-revision", rev), zap.Error(cerr), ) err = cerr succeed = false } } if succeed { clus.lg.Info( "compact PASS", zap.String("endpoint", m.EtcdClientEndpoint), zap.Int64("compact-revision", rev), zap.Duration("timeout", timeout), zap.Duration("took", time.Since(now)), ) } } return err } func (clus *Cluster) checkCompact(rev int64) error { if rev == 0 { return nil } for _, m := range clus.Members { if err := m.CheckCompact(rev); err != nil { return err } } return nil } func (clus *Cluster) defrag() error { for _, m := range clus.Members { if err := m.Defrag(); err != nil { clus.lg.Warn( "defrag FAIL", zap.String("endpoint", m.EtcdClientEndpoint), zap.Error(err), ) return err } clus.lg.Info( "defrag PASS", zap.String("endpoint", m.EtcdClientEndpoint), ) } clus.lg.Info( "defrag ALL PASS", zap.Int("round", clus.rd), zap.Int("case", clus.cs), zap.Int("case-total", len(clus.cases)), ) return nil } // GetCaseDelayDuration computes failure delay duration. func (clus *Cluster) GetCaseDelayDuration() time.Duration { return time.Duration(clus.Tester.CaseDelayMs) * time.Millisecond } // Report reports the number of modified keys. func (clus *Cluster) Report() int64 { return clus.stresser.ModifiedKeys() }
NewCluster
base.py
from __future__ import print_function import numpy as np class BaseModel(object): """ base dictionary learning model for classification """ # def __init__(self) def
(self, data): raise NotImplementedError def evaluate(self, data, label): pred = self.predict(data) acc = np.sum(pred == label)/float(len(label)) print('accuracy = {:.2f} %'.format(100 * acc)) return acc
predict
contract.rs
#[cfg(not(feature = "library"))] use cosmwasm_std::entry_point; use cosmwasm_std::{ from_binary, to_binary, Addr, BankMsg, Binary, Deps, DepsMut, Env, MessageInfo, Response, StdResult, SubMsg, WasmMsg, }; use cw2::set_contract_version; use cw20::{Balance, Cw20Coin, Cw20CoinVerified, Cw20ExecuteMsg, Cw20ReceiveMsg}; use crate::error::ContractError; use crate::msg::{ CreateMsg, DetailsResponse, ExecuteMsg, InstantiateMsg, ListResponse, QueryMsg, ReceiveMsg, }; use crate::state::{all_escrow_ids, Escrow, GenericBalance, ESCROWS}; // version info for migration info const CONTRACT_NAME: &str = "crates.io:cw20-escrow"; const CONTRACT_VERSION: &str = env!("CARGO_PKG_VERSION"); #[cfg_attr(not(feature = "library"), entry_point)] pub fn instantiate( deps: DepsMut, _env: Env, _info: MessageInfo, _msg: InstantiateMsg, ) -> StdResult<Response> { set_contract_version(deps.storage, CONTRACT_NAME, CONTRACT_VERSION)?; // no setup Ok(Response::default()) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn execute( deps: DepsMut, env: Env, info: MessageInfo, msg: ExecuteMsg, ) -> Result<Response, ContractError> { match msg { ExecuteMsg::Create(msg) => { execute_create(deps, msg, Balance::from(info.funds), &info.sender) } ExecuteMsg::Approve { id } => execute_approve(deps, env, info, id), ExecuteMsg::TopUp { id } => execute_top_up(deps, id, Balance::from(info.funds)), ExecuteMsg::Refund { id } => execute_refund(deps, env, info, id), ExecuteMsg::Receive(msg) => execute_receive(deps, info, msg), } } pub fn execute_receive( deps: DepsMut, info: MessageInfo, wrapper: Cw20ReceiveMsg, ) -> Result<Response, ContractError> { let msg: ReceiveMsg = from_binary(&wrapper.msg)?; let balance = Balance::Cw20(Cw20CoinVerified { address: info.sender, amount: wrapper.amount, }); let api = deps.api; match msg { ReceiveMsg::Create(msg) => { execute_create(deps, msg, balance, &api.addr_validate(&wrapper.sender)?) } ReceiveMsg::TopUp { id } => execute_top_up(deps, id, balance), } } pub fn execute_create( deps: DepsMut, msg: CreateMsg, balance: Balance, sender: &Addr, ) -> Result<Response, ContractError> { if balance.is_empty() { return Err(ContractError::EmptyBalance {}); } let mut cw20_whitelist = msg.addr_whitelist(deps.api)?; let escrow_balance = match balance { Balance::Native(balance) => GenericBalance { native: balance.0, cw20: vec![], }, Balance::Cw20(token) => { // make sure the token sent is on the whitelist by default if !cw20_whitelist.iter().any(|t| t == &token.address) { cw20_whitelist.push(token.address.clone()) } GenericBalance { native: vec![], cw20: vec![token], } } }; let escrow = Escrow { arbiter: deps.api.addr_validate(&msg.arbiter)?, recipient: deps.api.addr_validate(&msg.recipient)?, source: sender.clone(), end_height: msg.end_height, end_time: msg.end_time, balance: escrow_balance, cw20_whitelist, }; // try to store it, fail if the id was already in use ESCROWS.update(deps.storage, &msg.id, |existing| match existing { None => Ok(escrow), Some(_) => Err(ContractError::AlreadyInUse {}), })?; let res = Response::new().add_attributes(vec![("action", "create"), ("id", msg.id.as_str())]); Ok(res) } pub fn execute_top_up( deps: DepsMut, id: String, balance: Balance, ) -> Result<Response, ContractError> { if balance.is_empty() { return Err(ContractError::EmptyBalance {}); } // this fails is no escrow there let mut escrow = ESCROWS.load(deps.storage, &id)?; if let Balance::Cw20(token) = &balance { // ensure the token is on the whitelist if !escrow.cw20_whitelist.iter().any(|t| t == &token.address) { return Err(ContractError::NotInWhitelist {}); } }; escrow.balance.add_tokens(balance); // and save ESCROWS.save(deps.storage, &id, &escrow)?; let res = Response::new().add_attributes(vec![("action", "top_up"), ("id", id.as_str())]); Ok(res) } pub fn execute_approve( deps: DepsMut, env: Env, info: MessageInfo, id: String, ) -> Result<Response, ContractError> { // this fails is no escrow there let escrow = ESCROWS.load(deps.storage, &id)?; if info.sender != escrow.arbiter { Err(ContractError::Unauthorized {}) } else if escrow.is_expired(&env) { Err(ContractError::Expired {}) } else { // we delete the escrow ESCROWS.remove(deps.storage, &id); // send all tokens out let messages: Vec<SubMsg> = send_tokens(&escrow.recipient, &escrow.balance)?; Ok(Response::new() .add_attribute("action", "approve") .add_attribute("id", id) .add_attribute("to", escrow.recipient) .add_submessages(messages)) } } pub fn execute_refund( deps: DepsMut, env: Env, info: MessageInfo, id: String, ) -> Result<Response, ContractError> { // this fails is no escrow there let escrow = ESCROWS.load(deps.storage, &id)?; // the arbiter can send anytime OR anyone can send after expiration if !escrow.is_expired(&env) && info.sender != escrow.arbiter { Err(ContractError::Unauthorized {}) } else { // we delete the escrow ESCROWS.remove(deps.storage, &id); // send all tokens out let messages = send_tokens(&escrow.source, &escrow.balance)?; Ok(Response::new() .add_attribute("action", "refund") .add_attribute("id", id) .add_attribute("to", escrow.source) .add_submessages(messages)) } } fn send_tokens(to: &Addr, balance: &GenericBalance) -> StdResult<Vec<SubMsg>> { let native_balance = &balance.native; let mut msgs: Vec<SubMsg> = if native_balance.is_empty() { vec![] } else { vec![SubMsg::new(BankMsg::Send { to_address: to.into(), amount: native_balance.to_vec(), })] }; let cw20_balance = &balance.cw20; let cw20_msgs: StdResult<Vec<_>> = cw20_balance .iter() .map(|c| { let msg = Cw20ExecuteMsg::Transfer { recipient: to.into(), amount: c.amount, }; let exec = SubMsg::new(WasmMsg::Execute { contract_addr: c.address.to_string(), msg: to_binary(&msg)?, funds: vec![], }); Ok(exec) }) .collect(); msgs.append(&mut cw20_msgs?); Ok(msgs) } #[cfg_attr(not(feature = "library"), entry_point)] pub fn query(deps: Deps, _env: Env, msg: QueryMsg) -> StdResult<Binary> { match msg { QueryMsg::List {} => to_binary(&query_list(deps)?), QueryMsg::Details { id } => to_binary(&query_details(deps, id)?), } } fn query_details(deps: Deps, id: String) -> StdResult<DetailsResponse> { let escrow = ESCROWS.load(deps.storage, &id)?; let cw20_whitelist = escrow.human_whitelist(); // transform tokens let native_balance = escrow.balance.native; let cw20_balance: StdResult<Vec<_>> = escrow .balance .cw20 .into_iter() .map(|token| { Ok(Cw20Coin { address: token.address.into(), amount: token.amount, }) }) .collect(); let details = DetailsResponse { id, arbiter: escrow.arbiter.into(), recipient: escrow.recipient.into(), source: escrow.source.into(), end_height: escrow.end_height, end_time: escrow.end_time, native_balance, cw20_balance: cw20_balance?, cw20_whitelist, }; Ok(details) } fn query_list(deps: Deps) -> StdResult<ListResponse> { Ok(ListResponse { escrows: all_escrow_ids(deps.storage)?, }) } #[cfg(test)] mod tests { use cosmwasm_std::testing::{mock_dependencies, mock_env, mock_info}; use cosmwasm_std::{coin, coins, CosmosMsg, StdError, Uint128}; use crate::msg::ExecuteMsg::TopUp; use super::*; #[test] fn happy_path_native() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); // create an escrow let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: Some(123456), cw20_whitelist: None, }; let sender = String::from("source"); let balance = coins(100, "tokens"); let info = mock_info(&sender, &balance); let msg = ExecuteMsg::Create(create.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // ensure the details is what we expect let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); assert_eq!( details, DetailsResponse { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), source: String::from("source"), end_height: Some(123456), end_time: None, native_balance: balance.clone(), cw20_balance: vec![], cw20_whitelist: vec![], } ); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(1, res.messages.len()); assert_eq!(("action", "approve"), res.attributes[0]); assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: create.recipient, amount: balance, })) ); // second attempt fails (not found) let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); } #[test] fn happy_path_cw20() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len());
// create an escrow let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: None, cw20_whitelist: Some(vec![String::from("other-token")]), }; let receive = Cw20ReceiveMsg { sender: String::from("source"), amount: Uint128::new(100), msg: to_binary(&ExecuteMsg::Create(create.clone())).unwrap(), }; let token_contract = String::from("my-cw20-token"); let info = mock_info(&token_contract, &[]); let msg = ExecuteMsg::Receive(receive.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // ensure the whitelist is what we expect let details = query_details(deps.as_ref(), "foobar".to_string()).unwrap(); assert_eq!( details, DetailsResponse { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), source: String::from("source"), end_height: None, end_time: None, native_balance: vec![], cw20_balance: vec![Cw20Coin { address: String::from("my-cw20-token"), amount: Uint128::new(100), }], cw20_whitelist: vec![String::from("other-token"), String::from("my-cw20-token")], } ); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(1, res.messages.len()); assert_eq!(("action", "approve"), res.attributes[0]); let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient, amount: receive.amount, }; assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: token_contract, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); // second attempt fails (not found) let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let err = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap_err(); assert!(matches!(err, ContractError::Std(StdError::NotFound { .. }))); } #[test] fn add_tokens_proper() { let mut tokens = GenericBalance::default(); tokens.add_tokens(Balance::from(vec![coin(123, "atom"), coin(789, "eth")])); tokens.add_tokens(Balance::from(vec![coin(456, "atom"), coin(12, "btc")])); assert_eq!( tokens.native, vec![coin(579, "atom"), coin(789, "eth"), coin(12, "btc")] ); } #[test] fn add_cw_tokens_proper() { let mut tokens = GenericBalance::default(); let bar_token = Addr::unchecked("bar_token"); let foo_token = Addr::unchecked("foo_token"); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: foo_token.clone(), amount: Uint128::new(12345), })); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: bar_token.clone(), amount: Uint128::new(777), })); tokens.add_tokens(Balance::Cw20(Cw20CoinVerified { address: foo_token.clone(), amount: Uint128::new(23400), })); assert_eq!( tokens.cw20, vec![ Cw20CoinVerified { address: foo_token, amount: Uint128::new(35745), }, Cw20CoinVerified { address: bar_token, amount: Uint128::new(777), } ] ); } #[test] fn top_up_mixed_tokens() { let mut deps = mock_dependencies(); // instantiate an empty contract let instantiate_msg = InstantiateMsg {}; let info = mock_info(&String::from("anyone"), &[]); let res = instantiate(deps.as_mut(), mock_env(), info, instantiate_msg).unwrap(); assert_eq!(0, res.messages.len()); // only accept these tokens let whitelist = vec![String::from("bar_token"), String::from("foo_token")]; // create an escrow with 2 native tokens let create = CreateMsg { id: "foobar".to_string(), arbiter: String::from("arbitrate"), recipient: String::from("recd"), end_time: None, end_height: None, cw20_whitelist: Some(whitelist), }; let sender = String::from("source"); let balance = vec![coin(100, "fee"), coin(200, "stake")]; let info = mock_info(&sender, &balance); let msg = ExecuteMsg::Create(create.clone()); let res = execute(deps.as_mut(), mock_env(), info, msg).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "create"), res.attributes[0]); // top it up with 2 more native tokens let extra_native = vec![coin(250, "random"), coin(300, "stake")]; let info = mock_info(&sender, &extra_native); let top_up = ExecuteMsg::TopUp { id: create.id.clone(), }; let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // top up with one foreign token let bar_token = String::from("bar_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(7890), msg: to_binary(&base).unwrap(), }); let info = mock_info(&bar_token, &[]); let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // top with a foreign token not on the whitelist // top up with one foreign token let baz_token = String::from("baz_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(7890), msg: to_binary(&base).unwrap(), }); let info = mock_info(&baz_token, &[]); let err = execute(deps.as_mut(), mock_env(), info, top_up).unwrap_err(); assert_eq!(err, ContractError::NotInWhitelist {}); // top up with second foreign token let foo_token = String::from("foo_token"); let base = TopUp { id: create.id.clone(), }; let top_up = ExecuteMsg::Receive(Cw20ReceiveMsg { sender: String::from("random"), amount: Uint128::new(888), msg: to_binary(&base).unwrap(), }); let info = mock_info(&foo_token, &[]); let res = execute(deps.as_mut(), mock_env(), info, top_up).unwrap(); assert_eq!(0, res.messages.len()); assert_eq!(("action", "top_up"), res.attributes[0]); // approve it let id = create.id.clone(); let info = mock_info(&create.arbiter, &[]); let res = execute(deps.as_mut(), mock_env(), info, ExecuteMsg::Approve { id }).unwrap(); assert_eq!(("action", "approve"), res.attributes[0]); assert_eq!(3, res.messages.len()); // first message releases all native coins assert_eq!( res.messages[0], SubMsg::new(CosmosMsg::Bank(BankMsg::Send { to_address: create.recipient.clone(), amount: vec![coin(100, "fee"), coin(500, "stake"), coin(250, "random")], })) ); // second one release bar cw20 token let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient.clone(), amount: Uint128::new(7890), }; assert_eq!( res.messages[1], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: bar_token, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); // third one release foo cw20 token let send_msg = Cw20ExecuteMsg::Transfer { recipient: create.recipient, amount: Uint128::new(888), }; assert_eq!( res.messages[2], SubMsg::new(CosmosMsg::Wasm(WasmMsg::Execute { contract_addr: foo_token, msg: to_binary(&send_msg).unwrap(), funds: vec![] })) ); } }
CreateRelationalDatabaseFromSnapshotCommand.ts
import { LightsailClientResolvedConfig, ServiceInputTypes, ServiceOutputTypes } from "../LightsailClient"; import { CreateRelationalDatabaseFromSnapshotRequest, CreateRelationalDatabaseFromSnapshotResult } from "../models/index"; import { deserializeAws_json1_1CreateRelationalDatabaseFromSnapshotCommand, serializeAws_json1_1CreateRelationalDatabaseFromSnapshotCommand } from "../protocols/Aws_json1_1"; import { getSerdePlugin } from "@aws-sdk/middleware-serde"; import { HttpRequest as __HttpRequest, HttpResponse as __HttpResponse } from "@aws-sdk/protocol-http"; import { Command as $Command } from "@aws-sdk/smithy-client"; import { FinalizeHandlerArguments, Handler, HandlerExecutionContext, MiddlewareStack, HttpHandlerOptions as __HttpHandlerOptions, MetadataBearer as __MetadataBearer, SerdeContext as __SerdeContext } from "@aws-sdk/types"; export type CreateRelationalDatabaseFromSnapshotCommandInput = CreateRelationalDatabaseFromSnapshotRequest; export type CreateRelationalDatabaseFromSnapshotCommandOutput = CreateRelationalDatabaseFromSnapshotResult & __MetadataBearer; export class CreateRelationalDatabaseFromSnapshotCommand extends $Command< CreateRelationalDatabaseFromSnapshotCommandInput, CreateRelationalDatabaseFromSnapshotCommandOutput, LightsailClientResolvedConfig > { // Start section: command_properties // End section: command_properties constructor( readonly input: CreateRelationalDatabaseFromSnapshotCommandInput ) { // Start section: command_constructor super(); // End section: command_constructor } resolveMiddleware( clientStack: MiddlewareStack<ServiceInputTypes, ServiceOutputTypes>, configuration: LightsailClientResolvedConfig, options?: __HttpHandlerOptions ): Handler< CreateRelationalDatabaseFromSnapshotCommandInput, CreateRelationalDatabaseFromSnapshotCommandOutput > { this.middlewareStack.use( getSerdePlugin(configuration, this.serialize, this.deserialize) ); const stack = clientStack.concat(this.middlewareStack); const handlerExecutionContext: HandlerExecutionContext = { logger: {} as any
requestHandler.handle(request.request as __HttpRequest, options || {}), handlerExecutionContext ); } private serialize( input: CreateRelationalDatabaseFromSnapshotCommandInput, context: __SerdeContext ): Promise<__HttpRequest> { return serializeAws_json1_1CreateRelationalDatabaseFromSnapshotCommand( input, context ); } private deserialize( output: __HttpResponse, context: __SerdeContext ): Promise<CreateRelationalDatabaseFromSnapshotCommandOutput> { return deserializeAws_json1_1CreateRelationalDatabaseFromSnapshotCommand( output, context ); } // Start section: command_body_extra // End section: command_body_extra }
}; const { requestHandler } = configuration; return stack.resolve( (request: FinalizeHandlerArguments<any>) =>
networkWatcher.go
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** package network import ( "context" "reflect" "github.com/pkg/errors" "github.com/pulumi/pulumi/sdk/v3/go/pulumi" ) // Network watcher in a resource group. // API Version: 2020-11-01. type NetworkWatcher struct { pulumi.CustomResourceState // A unique read-only string that changes whenever the resource is updated. Etag pulumi.StringOutput `pulumi:"etag"` // Resource location. Location pulumi.StringPtrOutput `pulumi:"location"` // Resource name. Name pulumi.StringOutput `pulumi:"name"` // The provisioning state of the network watcher resource. ProvisioningState pulumi.StringOutput `pulumi:"provisioningState"` // Resource tags. Tags pulumi.StringMapOutput `pulumi:"tags"` // Resource type. Type pulumi.StringOutput `pulumi:"type"` } // NewNetworkWatcher registers a new resource with the given unique name, arguments, and options. func NewNetworkWatcher(ctx *pulumi.Context, name string, args *NetworkWatcherArgs, opts ...pulumi.ResourceOption) (*NetworkWatcher, error) { if args == nil { return nil, errors.New("missing one or more required arguments") } if args.ResourceGroupName == nil { return nil, errors.New("invalid value for required argument 'ResourceGroupName'") } aliases := pulumi.Aliases([]pulumi.Alias{ { Type: pulumi.String("azure-nextgen:network:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20160901:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20160901:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20161201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20161201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20170301:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20170301:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20170601:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20170601:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20170801:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20170801:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20170901:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20170901:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20171001:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20171001:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20171101:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20171101:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180101:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180101:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180401:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180401:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180601:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180601:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180701:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180701:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20180801:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20180801:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20181001:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20181001:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20181101:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20181101:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20181201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20181201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190401:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190401:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190601:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190601:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190701:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190701:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190801:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190801:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20190901:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20190901:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20191101:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20191101:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20191201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20191201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200301:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200301:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200401:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200401:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200501:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200501:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200601:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200601:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200701:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200701:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20200801:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20200801:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20201101:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20201101:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20210201:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20210201:NetworkWatcher"), }, { Type: pulumi.String("azure-native:network/v20210301:NetworkWatcher"), }, { Type: pulumi.String("azure-nextgen:network/v20210301:NetworkWatcher"), }, }) opts = append(opts, aliases) var resource NetworkWatcher err := ctx.RegisterResource("azure-native:network:NetworkWatcher", name, args, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // GetNetworkWatcher gets an existing NetworkWatcher resource's state with the given name, ID, and optional // state properties that are used to uniquely qualify the lookup (nil if not required). func GetNetworkWatcher(ctx *pulumi.Context, name string, id pulumi.IDInput, state *NetworkWatcherState, opts ...pulumi.ResourceOption) (*NetworkWatcher, error) { var resource NetworkWatcher err := ctx.ReadResource("azure-native:network:NetworkWatcher", name, id, state, &resource, opts...) if err != nil { return nil, err } return &resource, nil } // Input properties used for looking up and filtering NetworkWatcher resources. type networkWatcherState struct { } type NetworkWatcherState struct { } func (NetworkWatcherState) ElementType() reflect.Type { return reflect.TypeOf((*networkWatcherState)(nil)).Elem() } type networkWatcherArgs struct { // Resource ID. Id *string `pulumi:"id"` // Resource location. Location *string `pulumi:"location"` // The name of the network watcher. NetworkWatcherName *string `pulumi:"networkWatcherName"` // The name of the resource group. ResourceGroupName string `pulumi:"resourceGroupName"` // Resource tags. Tags map[string]string `pulumi:"tags"` } // The set of arguments for constructing a NetworkWatcher resource. type NetworkWatcherArgs struct { // Resource ID. Id pulumi.StringPtrInput // Resource location. Location pulumi.StringPtrInput // The name of the network watcher. NetworkWatcherName pulumi.StringPtrInput // The name of the resource group. ResourceGroupName pulumi.StringInput // Resource tags. Tags pulumi.StringMapInput } func (NetworkWatcherArgs) ElementType() reflect.Type { return reflect.TypeOf((*networkWatcherArgs)(nil)).Elem() } type NetworkWatcherInput interface { pulumi.Input ToNetworkWatcherOutput() NetworkWatcherOutput ToNetworkWatcherOutputWithContext(ctx context.Context) NetworkWatcherOutput }
return reflect.TypeOf((*NetworkWatcher)(nil)) } func (i *NetworkWatcher) ToNetworkWatcherOutput() NetworkWatcherOutput { return i.ToNetworkWatcherOutputWithContext(context.Background()) } func (i *NetworkWatcher) ToNetworkWatcherOutputWithContext(ctx context.Context) NetworkWatcherOutput { return pulumi.ToOutputWithContext(ctx, i).(NetworkWatcherOutput) } type NetworkWatcherOutput struct{ *pulumi.OutputState } func (NetworkWatcherOutput) ElementType() reflect.Type { return reflect.TypeOf((*NetworkWatcher)(nil)) } func (o NetworkWatcherOutput) ToNetworkWatcherOutput() NetworkWatcherOutput { return o } func (o NetworkWatcherOutput) ToNetworkWatcherOutputWithContext(ctx context.Context) NetworkWatcherOutput { return o } func init() { pulumi.RegisterOutputType(NetworkWatcherOutput{}) }
func (*NetworkWatcher) ElementType() reflect.Type {
build_options.rs
use crate::build_context::{BridgeModel, ProjectLayout}; use crate::BuildContext; use crate::CargoToml; use crate::Manylinux; use crate::Metadata21; use crate::PythonInterpreter; use crate::Target; use cargo_metadata::{Metadata, MetadataCommand, Node}; use failure::{bail, err_msg, format_err, Error, ResultExt}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::path::PathBuf; use structopt::StructOpt; /// High level API for building wheels from a crate which is also used for the CLI #[derive(Debug, Serialize, Deserialize, StructOpt, Clone, Eq, PartialEq)] #[serde(default)] pub struct BuildOptions { // The {n} are workarounds for https://github.com/TeXitoi/structopt/issues/163 /// Control the platform tag on linux. /// /// - `1`: Use the manylinux1 tag and check for compliance{n} /// - `1-unchecked`: Use the manylinux1 tag without checking for compliance{n} /// - `2010`: Use the manylinux2010 tag and check for compliance{n} /// - `2010-unchecked`: Use the manylinux1 tag without checking for compliance{n} /// - `off`: Use the native linux tag (off) /// /// This option is ignored on all non-linux platforms #[structopt( long, possible_values = &["1", "1-unchecked", "2010", "2010-unchecked", "off"], case_insensitive = true, default_value = "1" )] pub manylinux: Manylinux, #[structopt(short, long)] /// The python versions to build wheels for, given as the names of the /// interpreters. Uses autodiscovery if not explicitly set. pub interpreter: Option<Vec<PathBuf>>, /// Which kind of bindings to use. Possible values are pyo3, rust-cpython, cffi and bin #[structopt(short, long)] pub bindings: Option<String>, #[structopt( short = "m", long = "manifest-path", parse(from_os_str), default_value = "Cargo.toml", name = "PATH" )] /// The path to the Cargo.toml pub manifest_path: PathBuf, /// The directory to store the built wheels in. Defaults to a new "wheels" /// directory in the project's target directory #[structopt(short, long, parse(from_os_str))] pub out: Option<PathBuf>, /// [deprecated, use --manylinux instead] Don't check for manylinux compliance #[structopt(long = "skip-auditwheel")] pub skip_auditwheel: bool, /// The --target option for cargo #[structopt(long, name = "TRIPLE")] pub target: Option<String>, /// Extra arguments that will be passed to cargo as `cargo rustc [...] [arg1] [arg2] --` /// /// Use as `--cargo-extra-args="--my-arg"` #[structopt(long = "cargo-extra-args")] pub cargo_extra_args: Vec<String>, /// Extra arguments that will be passed to rustc as `cargo rustc [...] -- [arg1] [arg2]` /// /// Use as `--rustc-extra-args="--my-arg"` #[structopt(long = "rustc-extra-args")] pub rustc_extra_args: Vec<String>, } impl Default for BuildOptions { fn default() -> Self { BuildOptions { manylinux: Manylinux::Manylinux1, interpreter: Some(vec![]), bindings: None, manifest_path: PathBuf::from("Cargo.toml"), out: None, skip_auditwheel: false, target: None, cargo_extra_args: Vec::new(), rustc_extra_args: Vec::new(), } } } impl BuildOptions { /// Tries to fill the missing metadata for a BuildContext by querying cargo and python pub fn into_build_context(self, release: bool, strip: bool) -> Result<BuildContext, Error> { let manifest_file = self .manifest_path .canonicalize() .context(format_err!("Can't find {}", self.manifest_path.display()))?; if !manifest_file.is_file() { bail!( "{} (resolved to {}) is not the path to a Cargo.toml", self.manifest_path.display(), manifest_file.display() ); }; let cargo_toml = CargoToml::from_path(&manifest_file)?; let manifest_dir = manifest_file.parent().unwrap(); let metadata21 = Metadata21::from_cargo_toml(&cargo_toml, &manifest_dir) .context("Failed to parse Cargo.toml into python metadata")?; let scripts = cargo_toml.scripts(); // If the package name contains minuses, you must declare a module with // underscores as lib name let module_name = cargo_toml .lib .as_ref() .and_then(|lib| lib.name.as_ref()) .unwrap_or_else(|| &cargo_toml.package.name) .to_owned(); let project_layout = ProjectLayout::determine(manifest_dir, &module_name)?; let target = Target::from_target_triple(self.target.clone())?; let mut cargo_extra_args = split_extra_args(&self.cargo_extra_args)?; if let Some(target) = self.target { cargo_extra_args.extend_from_slice(&["--target".to_string(), target]); } let cargo_metadata_extra_args = extra_feature_args(&cargo_extra_args); let cargo_metadata = MetadataCommand::new() .manifest_path(&self.manifest_path) .other_options(cargo_metadata_extra_args) .exec() .context("Cargo metadata failed")?; let wheel_dir = match self.out { Some(ref dir) => dir.clone(), None => PathBuf::from(&cargo_metadata.target_directory).join("wheels"), }; let bridge = find_bridge(&cargo_metadata, self.bindings.as_ref().map(|x| &**x))?; if bridge != BridgeModel::Bin && module_name.contains('-') { bail!( "The module name must not contains a minus \ (Make sure you have set an appropriate [lib] name in your Cargo.toml)" ); } let interpreter = match self.interpreter { // Only build a source ditribution Some(ref interpreter) if interpreter.is_empty() => vec![], // User given list of interpreters Some(interpreter) => find_interpreter(&bridge, &interpreter, &target)?, // Auto-detect interpreters None => find_interpreter(&bridge, &[], &target)?, }; let rustc_extra_args = split_extra_args(&self.rustc_extra_args)?; let manylinux = if self.skip_auditwheel { eprintln!("⚠ --skip-auditwheel is deprecated, use --manylinux=1-unchecked"); Manylinux::Manylinux1Unchecked } else { self.manylinux }; Ok(BuildContext { target, bridge, project_layout, metadata21, scripts, module_name, manifest_path: self.manifest_path, out: wheel_dir, release, strip, manylinux, cargo_extra_args, rustc_extra_args, interpreter, cargo_metadata, }) } } /// Tries to determine the [BridgeModel] for the target crate pub fn find_bridge(cargo_metadata: &Metadata, bridge: Option<&str>) -> Result<BridgeModel, Error> { let resolve = cargo_metadata .resolve .as_ref() .ok_or_else(|| format_err!("Expected to get a dependency graph from cargo"))?; let deps: HashMap<&str, &Node> = resolve .nodes .iter() .map(|node| (cargo_metadata[&node.id].name.as_ref(), node)) .collect(); if let Some(bindings) = bridge { if bindings == "cffi" { Ok(BridgeModel::Cffi) } else if bindings == "bin" { Ok(BridgeModel::Bin) } else { if !deps.contains_key(bindings) { bail!( "The bindings crate {} was not found in the dependencies list", bindings ); } Ok(BridgeModel::Bindings(bindings.to_string())) } } else if let Some(node) = deps.get("pyo3") { println!("🔗 Found pyo3 bindings"); if !node.features.contains(&"extension-module".to_string()) { let version = cargo_metadata[&node.id].version.to_string(); println!( "⚠ Warning: You're building a library without activating pyo3's \ `extension-module` feature. \ See https://pyo3.rs/{}/building-and-distribution.html#linking", version ); } Ok(BridgeModel::Bindings("pyo3".to_string())) } else if deps.contains_key("cpython") { println!("🔗 Found rust-cpython bindings"); Ok(BridgeModel::Bindings("rust_cpython".to_string())) } else { let package_id = resolve.root.as_ref().unwrap(); let package = cargo_metadata .packages .iter() .find(|p| &p.id == package_id) .unwrap(); if package.targets.len() == 1 { let target = &package.targets[0]; if target .crate_types .iter() .any(|crate_type| crate_type == "cdylib") { return Ok(BridgeModel::Cffi); } if target .crate_types .iter() .any(|crate_type| crate_type == "bin") { return Ok(BridgeModel::Bin); } } bail!("Couldn't find any bindings; Please specify them with --bindings/-b") } } /// Finds the appropriate amount for python versions for each [BridgeModel]. /// /// This means all for bindings, one for cffi and zero for bin. pub fn find_interpreter( bridge: &BridgeModel, interpreter: &[PathBuf], target: &Target, ) -> Result<Vec<PythonInterpreter>, Error> { match bridge { BridgeModel::Bindings(_) => { let interpreter = if !interpreter.is_empty() { PythonInterpreter::check_executables(&interpreter, &target, &bridge) .context("The given list of python interpreters is invalid")? } else { PythonInterpreter::find_all(&target, &bridge) .context("Finding python interpreters failed")? }; if interpreter.is_empty() { bail!("Couldn't find any python interpreters. Please specify at least one with -i"); } println!( "🐍 Found {}", interpreter .iter() .map(ToString::to_string) .collect::<Vec<String>>() .join(", ") ); Ok(interpreter) } BridgeModel::Cffi => { let executable = if interpreter.is_empty() { target.get_python() } else if interpreter.len() == 1 { interpreter[0].clone() } else { bail!("You can only specify one python interpreter for cffi compilation"); }; let err_message = "Failed to find python interpreter for generating cffi bindings"; let interpreter = PythonInterpreter::check_executable(executable, &target, &bridge) .context(err_msg(err_message))? .ok_or_else(|| err_msg(err_message))?; println!("🐍 Using {} to generate the cffi bindings", interpreter); Ok(vec![interpreter]) } BridgeModel::Bin => Ok(vec![]), } } /// Helper function that calls shlex on all extra args given fn split_extra_args(given_args: &[String]) -> Result<Vec<String>, Error> { let mut splitted_args = vec![]; for arg in given_args { match shlex::split(&arg) { Some(split) => splitted_args.extend(split), None => { bail!( "Couldn't split argument from `--cargo-extra-args`: '{}'", arg ); } } } Ok(splitted_args) } /// We need to pass feature flags to cargo metadata /// (s. https://github.com/PyO3/maturin/issues/211), but we can't pass /// all the extra args, as e.g. `--target` isn't supported. /// So we try to extract all the arguments related to features and /// hope that that's sufficient fn extra_feature_args(cargo_extra_args: &[String]) -> Vec<String> { let mut cargo_metadata_extra_args = vec![]; let mut feature_args = false; for arg in cargo_extra_args { if feature_args { if arg.starts_with('-') { feature_args = false; } else { cargo_metadata_extra_args.push(arg.clone()); } } if arg == "--features" { cargo_metadata_extra_args.push(arg.clone()); feature_args = true; } else if arg == "--all-features" || arg == "--no-default-features" || arg.starts_with("--features") { cargo_metadata_extra_args.push(arg.clone()); } } cargo_metadata_extra_args } #[cfg(test)] mod test { use std::path::Path; use super::*; #[test] fn test_find_bridge_pyo3() { let pyo3_pure = MetadataCommand::new() .manifest_path(&Path::new("test-crates/pyo3-pure").join("Cargo.toml")) .exec() .unwrap(); assert!(match find_bridge(&pyo3_pure, None).unwrap() { BridgeModel::Bindings(_) => true, _ => false, }); assert!(match find_bridge(&pyo3_pure, Some("pyo3")).unwrap() { BridgeModel::Bindings(_) => true, _ => false, }); assert!(find_bridge(&pyo3_pure, Some("rust-cpython")).is_err()); } #[test] fn test_find_bridge_pyo3_feature() { let pyo3_pure = MetadataCommand::new() .manifest_path(&Path::new("test-crates/pyo3-feature").join("Cargo.toml")) .exec() .unwrap(); assert!(find_bridge(&pyo3_pure, None).is_err()); let pyo3_pure = MetadataCommand::new() .manifest_path(&Path::new("test-crates/pyo3-feature").join("Cargo.toml")) .other_options(&["--features=pyo3".to_string()]) .exec() .unwrap(); assert!(match find_bridge(&pyo3_pure, None).unwrap() { BridgeModel::Bindings(_) => true, _ => false, }); } #[test] fn test_find_bridge_cffi() { let cf
fn test_find_bridge_bin() { let hello_world = MetadataCommand::new() .manifest_path(&Path::new("test-crates/hello-world").join("Cargo.toml")) .exec() .unwrap(); assert_eq!( find_bridge(&hello_world, Some("bin")).unwrap(), BridgeModel::Bin ); assert_eq!(find_bridge(&hello_world, None).unwrap(), BridgeModel::Bin); assert!(find_bridge(&hello_world, Some("rust-cpython")).is_err()); assert!(find_bridge(&hello_world, Some("pyo3")).is_err()); } #[test] fn test_argument_splitting() { let mut options = BuildOptions::default(); options.cargo_extra_args.push("--features log".to_string()); options.bindings = Some("bin".to_string()); let context = options.into_build_context(false, false).unwrap(); assert_eq!(context.cargo_extra_args, vec!["--features", "log"]) } #[test] fn test_extra_feature_args() { let cargo_extra_args = "--no-default-features --features a b --target x86_64-unknown-linux-musl --features=c --lib"; let cargo_extra_args = split_extra_args(&[cargo_extra_args.to_string()]).unwrap(); let cargo_metadata_extra_args = extra_feature_args(&cargo_extra_args); assert_eq!( cargo_metadata_extra_args, vec![ "--no-default-features", "--features", "a", "b", "--features=c" ] ); } }
fi_pure = MetadataCommand::new() .manifest_path(&Path::new("test-crates/cffi-pure").join("Cargo.toml")) .exec() .unwrap(); assert_eq!( find_bridge(&cffi_pure, Some("cffi")).unwrap(), BridgeModel::Cffi ); assert_eq!(find_bridge(&cffi_pure, None).unwrap(), BridgeModel::Cffi); assert!(find_bridge(&cffi_pure, Some("rust-cpython")).is_err()); assert!(find_bridge(&cffi_pure, Some("pyo3")).is_err()); } #[test]
__init__.py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class interface(PybindBase):
""" This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-system-watermark - based on the path /system-config/interface. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__utilization_watermark',) _yang_name = 'interface' _rest_name = 'interface' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__utilization_watermark = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="utilization-watermark", rest_name="utilization-watermark", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Enable Port utilization watermark (Default: Enabled)', u'cli-show-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-watermark', defining_module='brocade-system-watermark', yang_type='empty', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'system-config', u'interface'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'system', u'interface'] def _get_utilization_watermark(self): """ Getter method for utilization_watermark, mapped from YANG variable /system_config/interface/utilization_watermark (empty) """ return self.__utilization_watermark def _set_utilization_watermark(self, v, load=False): """ Setter method for utilization_watermark, mapped from YANG variable /system_config/interface/utilization_watermark (empty) If this variable is read-only (config: false) in the source YANG file, then _set_utilization_watermark is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_utilization_watermark() directly. """ if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=YANGBool, is_leaf=True, yang_name="utilization-watermark", rest_name="utilization-watermark", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Enable Port utilization watermark (Default: Enabled)', u'cli-show-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-watermark', defining_module='brocade-system-watermark', yang_type='empty', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """utilization_watermark must be of a type compatible with empty""", 'defined-type': "empty", 'generated-type': """YANGDynClass(base=YANGBool, is_leaf=True, yang_name="utilization-watermark", rest_name="utilization-watermark", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Enable Port utilization watermark (Default: Enabled)', u'cli-show-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-watermark', defining_module='brocade-system-watermark', yang_type='empty', is_config=True)""", }) self.__utilization_watermark = t if hasattr(self, '_set'): self._set() def _unset_utilization_watermark(self): self.__utilization_watermark = YANGDynClass(base=YANGBool, is_leaf=True, yang_name="utilization-watermark", rest_name="utilization-watermark", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'cli-full-command': None, u'info': u'Enable Port utilization watermark (Default: Enabled)', u'cli-show-no': None}}, namespace='urn:brocade.com:mgmt:brocade-system-watermark', defining_module='brocade-system-watermark', yang_type='empty', is_config=True) utilization_watermark = __builtin__.property(_get_utilization_watermark, _set_utilization_watermark) _pyangbind_elements = {'utilization_watermark': utilization_watermark, }
app.test.ts
import { expect } from "chai"; import request from "supertest"; import { describe, it } from "mocha"; import { createApp } from "../src/backend/config/app"; //import { getHandlers } from "../src/backend/controllers/user_controllet"; import { createDbConnection } from "../src/backend/config/db"; import { getConnection, Connection } from "typeorm"; describe("User controller", function () { let conn : Connection | undefined = undefined; // Create connection to DB before tests are executed before(async () => { conn = await createDbConnection(); }) // Clean up tables before each test beforeEach(async () => { return await getConnection().synchronize(true); }); // Close database connection after(async () => { if (conn !== undefined) { return await conn.close(); } }); // This is an example of an unit test it("Should be able to create an user", function (done) { const credentials = { email: "[email protected]", password: "mysecret" }; const mockUserRepository: any = { save: (newUser: any) => Promise.resolve({ id: 1, email: newUser.email, password: newUser.password }) }; const mockRequest: any = { body: credentials }; const mockResponse: any = { json: (data: any) => { return { send: () => { expect(data.ok).to.eq("ok"); done(); } }; } }; //const handlers = getHandlers(mockUserRepository); //handlers.createUser(mockRequest, mockResponse); }); // This is an example of an integration tests it("HTTP POST /api/v1/user", function (done) { (async () => { const app = await createApp(conn); const credentials = { email: "[email protected]", password: "mysecret" }; request(app) .post("/api/v1/users") .send(credentials) .set("Accept", "application/json") .expect(200) .expect(function(res) { expect(res.body.ok).to.eq("ok"); }) .end(function(err, res) { if (err) throw err; done(); }); })(); });
});
ogv-decoder-audio-vorbis.js
var OGVDecoderAudioVorbis = function(Module) { Module = Module || {}; var options=Module;Module={print:(function(str){console.log(str)})};if(options["memoryLimit"]){Module["TOTAL_MEMORY"]=options["memoryLimit"]}var Module;if(!Module)Module=(typeof OGVDecoderAudioVorbis!=="undefined"?OGVDecoderAudioVorbis:null)||{};var moduleOverrides={};for(var key in Module){if(Module.hasOwnProperty(key)){moduleOverrides[key]=Module[key]}}var ENVIRONMENT_IS_WEB=false;var ENVIRONMENT_IS_WORKER=false;var ENVIRONMENT_IS_NODE=false;var ENVIRONMENT_IS_SHELL=false;if(Module["ENVIRONMENT"]){if(Module["ENVIRONMENT"]==="WEB"){ENVIRONMENT_IS_WEB=true}else if(Module["ENVIRONMENT"]==="WORKER"){ENVIRONMENT_IS_WORKER=true}else if(Module["ENVIRONMENT"]==="NODE"){ENVIRONMENT_IS_NODE=true}else if(Module["ENVIRONMENT"]==="SHELL"){ENVIRONMENT_IS_SHELL=true}else{throw new Error("The provided Module['ENVIRONMENT'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.")}}else{ENVIRONMENT_IS_WEB=typeof window==="object";ENVIRONMENT_IS_WORKER=typeof importScripts==="function";ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof require==="function"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER;ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER}if(ENVIRONMENT_IS_NODE){if(!Module["print"])Module["print"]=console.log;if(!Module["printErr"])Module["printErr"]=console.warn;var nodeFS;var nodePath;Module["read"]=function read(filename,binary){if(!nodeFS)nodeFS=require("fs");if(!nodePath)nodePath=require("path");filename=nodePath["normalize"](filename);var ret=nodeFS["readFileSync"](filename);if(!ret&&filename!=nodePath["resolve"](filename)){filename=path.join(__dirname,"..","src",filename);ret=nodeFS["readFileSync"](filename)}if(ret&&!binary)ret=ret.toString();return ret};Module["readBinary"]=function readBinary(filename){var ret=Module["read"](filename,true);if(!ret.buffer){ret=new Uint8Array(ret)}assert(ret.buffer);return ret};Module["load"]=function load(f){globalEval(read(f))};if(!Module["thisProgram"]){if(process["argv"].length>1){Module["thisProgram"]=process["argv"][1].replace(/\\/g,"/")}else{Module["thisProgram"]="unknown-program"}}Module["arguments"]=process["argv"].slice(2);if(typeof module!=="undefined"){module["exports"]=Module}process["on"]("uncaughtException",(function(ex){if(!(ex instanceof ExitStatus)){throw ex}}));Module["inspect"]=(function(){return"[Emscripten Module object]"})}else if(ENVIRONMENT_IS_SHELL){if(!Module["print"])Module["print"]=print;if(typeof printErr!="undefined")Module["printErr"]=printErr;if(typeof read!="undefined"){Module["read"]=read}else{Module["read"]=function read(){throw"no read() available (jsc?)"}}Module["readBinary"]=function readBinary(f){if(typeof readbuffer==="function"){return new Uint8Array(readbuffer(f))}var data=read(f,"binary");assert(typeof data==="object");return data};if(typeof scriptArgs!="undefined"){Module["arguments"]=scriptArgs}else if(typeof arguments!="undefined"){Module["arguments"]=arguments}}else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){Module["read"]=function read(url){var xhr=new XMLHttpRequest;xhr.open("GET",url,false);xhr.send(null);return xhr.responseText};Module["readAsync"]=function readAsync(url,onload,onerror){var xhr=new XMLHttpRequest;xhr.open("GET",url,true);xhr.responseType="arraybuffer";xhr.onload=function xhr_onload(){if(xhr.status==200||xhr.status==0&&xhr.response){onload(xhr.response)}else{onerror()}};xhr.onerror=onerror;xhr.send(null)};if(typeof arguments!="undefined"){Module["arguments"]=arguments}if(typeof console!=="undefined"){if(!Module["print"])Module["print"]=function print(x){console.log(x)};if(!Module["printErr"])Module["printErr"]=function printErr(x){console.warn(x)}}else{var TRY_USE_DUMP=false;if(!Module["print"])Module["print"]=TRY_USE_DUMP&&typeof dump!=="undefined"?(function(x){dump(x)}):(function(x){})}if(ENVIRONMENT_IS_WORKER){Module["load"]=importScripts}if(typeof Module["setWindowTitle"]==="undefined"){Module["setWindowTitle"]=(function(title){document.title=title})}}else{throw"Unknown runtime environment. Where are we?"}function globalEval(x){eval.call(null,x)}if(!Module["load"]&&Module["read"]){Module["load"]=function load(f){globalEval(Module["read"](f))}}if(!Module["print"]){Module["print"]=(function(){})}if(!Module["printErr"]){Module["printErr"]=Module["print"]}if(!Module["arguments"]){Module["arguments"]=[]}if(!Module["thisProgram"]){Module["thisProgram"]="./this.program"}Module.print=Module["print"];Module.printErr=Module["printErr"];Module["preRun"]=[];Module["postRun"]=[];for(var key in moduleOverrides){if(moduleOverrides.hasOwnProperty(key)){Module[key]=moduleOverrides[key]}}moduleOverrides=undefined;var Runtime={setTempRet0:(function(value){tempRet0=value}),getTempRet0:(function(){return tempRet0}),stackSave:(function(){return STACKTOP}),stackRestore:(function(stackTop){STACKTOP=stackTop}),getNativeTypeSize:(function(type){switch(type){case"i1":case"i8":return 1;case"i16":return 2;case"i32":return 4;case"i64":return 8;case"float":return 4;case"double":return 8;default:{if(type[type.length-1]==="*"){return Runtime.QUANTUM_SIZE}else if(type[0]==="i"){var bits=parseInt(type.substr(1));assert(bits%8===0);return bits/8}else{return 0}}}}),getNativeFieldSize:(function(type){return Math.max(Runtime.getNativeTypeSize(type),Runtime.QUANTUM_SIZE)}),STACK_ALIGN:16,prepVararg:(function(ptr,type){if(type==="double"||type==="i64"){if(ptr&7){assert((ptr&7)===4);ptr+=4}}else{assert((ptr&3)===0)}return ptr}),getAlignSize:(function(type,size,vararg){if(!vararg&&(type=="i64"||type=="double"))return 8;if(!type)return Math.min(size,8);return Math.min(size||(type?Runtime.getNativeFieldSize(type):0),Runtime.QUANTUM_SIZE)}),dynCall:(function(sig,ptr,args){if(args&&args.length){if(!args.splice)args=Array.prototype.slice.call(args);args.splice(0,0,ptr);return Module["dynCall_"+sig].apply(null,args)}else{return Module["dynCall_"+sig].call(null,ptr)}}),functionPointers:[],addFunction:(function(func){for(var i=0;i<Runtime.functionPointers.length;i++){if(!Runtime.functionPointers[i]){Runtime.functionPointers[i]=func;return 2*(1+i)}}throw"Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS."}),removeFunction:(function(index){Runtime.functionPointers[(index-2)/2]=null}),warnOnce:(function(text){if(!Runtime.warnOnce.shown)Runtime.warnOnce.shown={};if(!Runtime.warnOnce.shown[text]){Runtime.warnOnce.shown[text]=1;Module.printErr(text)}}),funcWrappers:{},getFuncWrapper:(function(func,sig){assert(sig);if(!Runtime.funcWrappers[sig]){Runtime.funcWrappers[sig]={}}var sigCache=Runtime.funcWrappers[sig];if(!sigCache[func]){sigCache[func]=function dynCall_wrapper(){return Runtime.dynCall(sig,func,arguments)}}return sigCache[func]}),getCompilerSetting:(function(name){throw"You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work"}),stackAlloc:(function(size){var ret=STACKTOP;STACKTOP=STACKTOP+size|0;STACKTOP=STACKTOP+15&-16;return ret}),staticAlloc:(function(size){var ret=STATICTOP;STATICTOP=STATICTOP+size|0;STATICTOP=STATICTOP+15&-16;return ret}),dynamicAlloc:(function(size){var ret=DYNAMICTOP;DYNAMICTOP=DYNAMICTOP+size|0;DYNAMICTOP=DYNAMICTOP+15&-16;if(DYNAMICTOP>=TOTAL_MEMORY){var success=enlargeMemory();if(!success){DYNAMICTOP=ret;return 0}}return ret}),alignMemory:(function(size,quantum){var ret=size=Math.ceil(size/(quantum?quantum:16))*(quantum?quantum:16);return ret}),makeBigInt:(function(low,high,unsigned){var ret=unsigned?+(low>>>0)+ +(high>>>0)*+4294967296:+(low>>>0)+ +(high|0)*+4294967296;return ret}),GLOBAL_BASE:8,QUANTUM_SIZE:4,__dummy__:0};Module["Runtime"]=Runtime;var ABORT=false;var EXITSTATUS=0;function assert(condition,text){if(!condition){abort("Assertion failed: "+text)}}function getCFunc(ident){var func=Module["_"+ident];if(!func){try{func=eval("_"+ident)}catch(e){}}assert(func,"Cannot call unknown function "+ident+" (perhaps LLVM optimizations or closure removed it?)");return func}var cwrap,ccall;((function(){var JSfuncs={"stackSave":(function(){Runtime.stackSave()}),"stackRestore":(function(){Runtime.stackRestore()}),"arrayToC":(function(arr){var ret=Runtime.stackAlloc(arr.length);writeArrayToMemory(arr,ret);return ret}),"stringToC":(function(str){var ret=0;if(str!==null&&str!==undefined&&str!==0){ret=Runtime.stackAlloc((str.length<<2)+1);writeStringToMemory(str,ret)}return ret})};var toC={"string":JSfuncs["stringToC"],"array":JSfuncs["arrayToC"]};ccall=function ccallFunc(ident,returnType,argTypes,args,opts){var func=getCFunc(ident);var cArgs=[];var stack=0;if(args){for(var i=0;i<args.length;i++){var converter=toC[argTypes[i]];if(converter){if(stack===0)stack=Runtime.stackSave();cArgs[i]=converter(args[i])}else{cArgs[i]=args[i]}}}var ret=func.apply(null,cArgs);if(returnType==="string")ret=Pointer_stringify(ret);if(stack!==0){if(opts&&opts.async){EmterpreterAsync.asyncFinalizers.push((function(){Runtime.stackRestore(stack)}));return}Runtime.stackRestore(stack)}return ret};var sourceRegex=/^function\s*[a-zA-Z$_0-9]*\s*\(([^)]*)\)\s*{\s*([^*]*?)[\s;]*(?:return\s*(.*?)[;\s]*)?}$/;function parseJSFunc(jsfunc){var parsed=jsfunc.toString().match(sourceRegex).slice(1);return{arguments:parsed[0],body:parsed[1],returnValue:parsed[2]}}var JSsource=null;function ensureJSsource(){if(!JSsource){JSsource={};for(var fun in JSfuncs){if(JSfuncs.hasOwnProperty(fun)){JSsource[fun]=parseJSFunc(JSfuncs[fun])}}}}cwrap=function cwrap(ident,returnType,argTypes){argTypes=argTypes||[];var cfunc=getCFunc(ident);var numericArgs=argTypes.every((function(type){return type==="number"}));var numericRet=returnType!=="string";if(numericRet&&numericArgs){return cfunc}var argNames=argTypes.map((function(x,i){return"$"+i}));var funcstr="(function("+argNames.join(",")+") {";var nargs=argTypes.length;if(!numericArgs){ensureJSsource();funcstr+="var stack = "+JSsource["stackSave"].body+";";for(var i=0;i<nargs;i++){var arg=argNames[i],type=argTypes[i];if(type==="number")continue;var convertCode=JSsource[type+"ToC"];funcstr+="var "+convertCode.arguments+" = "+arg+";";funcstr+=convertCode.body+";";funcstr+=arg+"=("+convertCode.returnValue+");"}}var cfuncname=parseJSFunc((function(){return cfunc})).returnValue;funcstr+="var ret = "+cfuncname+"("+argNames.join(",")+");";if(!numericRet){var strgfy=parseJSFunc((function(){return Pointer_stringify})).returnValue;funcstr+="ret = "+strgfy+"(ret);"}if(!numericArgs){ensureJSsource();funcstr+=JSsource["stackRestore"].body.replace("()","(stack)")+";"}funcstr+="return ret})";return eval(funcstr)}}))();Module["ccall"]=ccall;Module["cwrap"]=cwrap;function setValue(ptr,value,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":HEAP8[ptr>>0]=value;break;case"i8":HEAP8[ptr>>0]=value;break;case"i16":HEAP16[ptr>>1]=value;break;case"i32":HEAP32[ptr>>2]=value;break;case"i64":tempI64=[value>>>0,(tempDouble=value,+Math_abs(tempDouble)>=+1?tempDouble>+0?(Math_min(+Math_floor(tempDouble/+4294967296),+4294967295)|0)>>>0:~~+Math_ceil((tempDouble- +(~~tempDouble>>>0))/+4294967296)>>>0:0)],HEAP32[ptr>>2]=tempI64[0],HEAP32[ptr+4>>2]=tempI64[1];break;case"float":HEAPF32[ptr>>2]=value;break;case"double":HEAPF64[ptr>>3]=value;break;default:abort("invalid type for setValue: "+type)}}Module["setValue"]=setValue;function getValue(ptr,type,noSafe){type=type||"i8";if(type.charAt(type.length-1)==="*")type="i32";switch(type){case"i1":return HEAP8[ptr>>0];case"i8":return HEAP8[ptr>>0];case"i16":return HEAP16[ptr>>1];case"i32":return HEAP32[ptr>>2];case"i64":return HEAP32[ptr>>2];case"float":return HEAPF32[ptr>>2];case"double":return HEAPF64[ptr>>3];default:abort("invalid type for setValue: "+type)}return null}Module["getValue"]=getValue;var ALLOC_NORMAL=0;var ALLOC_STACK=1;var ALLOC_STATIC=2;var ALLOC_DYNAMIC=3;var ALLOC_NONE=4;Module["ALLOC_NORMAL"]=ALLOC_NORMAL;Module["ALLOC_STACK"]=ALLOC_STACK;Module["ALLOC_STATIC"]=ALLOC_STATIC;Module["ALLOC_DYNAMIC"]=ALLOC_DYNAMIC;Module["ALLOC_NONE"]=ALLOC_NONE;function allocate(slab,types,allocator,ptr){var zeroinit,size;if(typeof slab==="number"){zeroinit=true;size=slab}else{zeroinit=false;size=slab.length}var singleType=typeof types==="string"?types:null;var ret;if(allocator==ALLOC_NONE){ret=ptr}else{ret=[typeof _malloc==="function"?_malloc:Runtime.staticAlloc,Runtime.stackAlloc,Runtime.staticAlloc,Runtime.dynamicAlloc][allocator===undefined?ALLOC_STATIC:allocator](Math.max(size,singleType?1:types.length))}if(zeroinit){var ptr=ret,stop;assert((ret&3)==0);stop=ret+(size&~3);for(;ptr<stop;ptr+=4){HEAP32[ptr>>2]=0}stop=ret+size;while(ptr<stop){HEAP8[ptr++>>0]=0}return ret}if(singleType==="i8"){if(slab.subarray||slab.slice){HEAPU8.set(slab,ret)}else{HEAPU8.set(new Uint8Array(slab),ret)}return ret}var i=0,type,typeSize,previousType;while(i<size){var curr=slab[i];if(typeof curr==="function"){curr=Runtime.getFunctionIndex(curr)}type=singleType||types[i];if(type===0){i++;continue}if(type=="i64")type="i32";setValue(ret+i,curr,type);if(previousType!==type){typeSize=Runtime.getNativeTypeSize(type);previousType=type}i+=typeSize}return ret}Module["allocate"]=allocate;function getMemory(size){if(!staticSealed)return Runtime.staticAlloc(size);if(typeof _sbrk!=="undefined"&&!_sbrk.called||!runtimeInitialized)return Runtime.dynamicAlloc(size);return _malloc(size)}Module["getMemory"]=getMemory;function Pointer_stringify(ptr,length){if(length===0||!ptr)return"";var hasUtf=0;var t;var i=0;while(1){t=HEAPU8[ptr+i>>0];hasUtf|=t;if(t==0&&!length)break;i++;if(length&&i==length)break}if(!length)length=i;var ret="";if(hasUtf<128){var MAX_CHUNK=1024;var curr;while(length>0){curr=String.fromCharCode.apply(String,HEAPU8.subarray(ptr,ptr+Math.min(length,MAX_CHUNK)));ret=ret?ret+curr:curr;ptr+=MAX_CHUNK;length-=MAX_CHUNK}return ret}return Module["UTF8ToString"](ptr)}Module["Pointer_stringify"]=Pointer_stringify;function AsciiToString(ptr){var str="";while(1){var ch=HEAP8[ptr++>>0];if(!ch)return str;str+=String.fromCharCode(ch)}}Module["AsciiToString"]=AsciiToString;function stringToAscii(str,outPtr){return writeAsciiToMemory(str,outPtr,false)}Module["stringToAscii"]=stringToAscii;function UTF8ArrayToString(u8Array,idx){var u0,u1,u2,u3,u4,u5;var str="";while(1){u0=u8Array[idx++];if(!u0)return str;if(!(u0&128)){str+=String.fromCharCode(u0);continue}u1=u8Array[idx++]&63;if((u0&224)==192){str+=String.fromCharCode((u0&31)<<6|u1);continue}u2=u8Array[idx++]&63;if((u0&240)==224){u0=(u0&15)<<12|u1<<6|u2}else{u3=u8Array[idx++]&63;if((u0&248)==240){u0=(u0&7)<<18|u1<<12|u2<<6|u3}else{u4=u8Array[idx++]&63;if((u0&252)==248){u0=(u0&3)<<24|u1<<18|u2<<12|u3<<6|u4}else{u5=u8Array[idx++]&63;u0=(u0&1)<<30|u1<<24|u2<<18|u3<<12|u4<<6|u5}}}if(u0<65536){str+=String.fromCharCode(u0)}else{var ch=u0-65536;str+=String.fromCharCode(55296|ch>>10,56320|ch&1023)}}}Module["UTF8ArrayToString"]=UTF8ArrayToString;function UTF8ToString(ptr){return UTF8ArrayToString(HEAPU8,ptr)}Module["UTF8ToString"]=UTF8ToString;function stringToUTF8Array(str,outU8Array,outIdx,maxBytesToWrite){if(!(maxBytesToWrite>0))return 0;var startIdx=outIdx;var endIdx=outIdx+maxBytesToWrite-1;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127){if(outIdx>=endIdx)break;outU8Array[outIdx++]=u}else if(u<=2047){if(outIdx+1>=endIdx)break;outU8Array[outIdx++]=192|u>>6;outU8Array[outIdx++]=128|u&63}else if(u<=65535){if(outIdx+2>=endIdx)break;outU8Array[outIdx++]=224|u>>12;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else if(u<=2097151){if(outIdx+3>=endIdx)break;outU8Array[outIdx++]=240|u>>18;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else if(u<=67108863){if(outIdx+4>=endIdx)break;outU8Array[outIdx++]=248|u>>24;outU8Array[outIdx++]=128|u>>18&63;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}else{if(outIdx+5>=endIdx)break;outU8Array[outIdx++]=252|u>>30;outU8Array[outIdx++]=128|u>>24&63;outU8Array[outIdx++]=128|u>>18&63;outU8Array[outIdx++]=128|u>>12&63;outU8Array[outIdx++]=128|u>>6&63;outU8Array[outIdx++]=128|u&63}}outU8Array[outIdx]=0;return outIdx-startIdx}Module["stringToUTF8Array"]=stringToUTF8Array;function stringToUTF8(str,outPtr,maxBytesToWrite){return stringToUTF8Array(str,HEAPU8,outPtr,maxBytesToWrite)}Module["stringToUTF8"]=stringToUTF8;function lengthBytesUTF8(str){var len=0;for(var i=0;i<str.length;++i){var u=str.charCodeAt(i);if(u>=55296&&u<=57343)u=65536+((u&1023)<<10)|str.charCodeAt(++i)&1023;if(u<=127){++len}else if(u<=2047){len+=2}else if(u<=65535){len+=3}else if(u<=2097151){len+=4}else if(u<=67108863){len+=5}else{len+=6}}return len}Module["lengthBytesUTF8"]=lengthBytesUTF8;function demangle(func){var hasLibcxxabi=!!Module["___cxa_demangle"];if(hasLibcxxabi){try{var buf=_malloc(func.length);writeStringToMemory(func.substr(1),buf);var status=_malloc(4);var ret=Module["___cxa_demangle"](buf,0,0,status);if(getValue(status,"i32")===0&&ret){return Pointer_stringify(ret)}}catch(e){return func}finally{if(buf)_free(buf);if(status)_free(status);if(ret)_free(ret)}}Runtime.warnOnce("warning: build with -s DEMANGLE_SUPPORT=1 to link in libcxxabi demangling");return func}function demangleAll(text){return text.replace(/__Z[\w\d_]+/g,(function(x){var y=demangle(x);return x===y?x:x+" ["+y+"]"}))}function jsStackTrace(){var err=new Error;if(!err.stack){try{throw new Error(0)}catch(e){err=e}if(!err.stack){return"(no stack trace available)"}}return err.stack.toString()}function stackTrace(){return demangleAll(jsStackTrace())}Module["stackTrace"]=stackTrace;var PAGE_SIZE=4096;function alignMemoryPage(x){if(x%4096>0){x+=4096-x%4096}return x}var HEAP;var buffer;var HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferViews(){Module["HEAP8"]=HEAP8=new Int8Array(buffer);Module["HEAP16"]=HEAP16=new Int16Array(buffer);Module["HEAP32"]=HEAP32=new Int32Array(buffer);Module["HEAPU8"]=HEAPU8=new Uint8Array(buffer);Module["HEAPU16"]=HEAPU16=new Uint16Array(buffer);Module["HEAPU32"]=HEAPU32=new Uint32Array(buffer);Module["HEAPF32"]=HEAPF32=new Float32Array(buffer);Module["HEAPF64"]=HEAPF64=new Float64Array(buffer)}var STATIC_BASE=0,STATICTOP=0,staticSealed=false;var STACK_BASE=0,STACKTOP=0,STACK_MAX=0;var DYNAMIC_BASE=0,DYNAMICTOP=0;function abortOnCannotGrowMemory(){abort("Cannot enlarge memory arrays. Either (1) compile with -s TOTAL_MEMORY=X with X higher than the current value "+TOTAL_MEMORY+", (2) compile with -s ALLOW_MEMORY_GROWTH=1 which adjusts the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or if you want malloc to return NULL (0) instead of this abort, compile with -s ABORTING_MALLOC=0 ")}function enlargeMemory(){abortOnCannotGrowMemory()}var TOTAL_STACK=Module["TOTAL_STACK"]||5242880;var TOTAL_MEMORY=Module["TOTAL_MEMORY"]||16777216;var totalMemory=64*1024;while(totalMemory<TOTAL_MEMORY||totalMemory<2*TOTAL_STACK){if(totalMemory<16*1024*1024){totalMemory*=2}else{totalMemory+=16*1024*1024}}if(totalMemory!==TOTAL_MEMORY){TOTAL_MEMORY=totalMemory}if(Module["buffer"]){buffer=Module["buffer"]}else{buffer=new ArrayBuffer(TOTAL_MEMORY)}updateGlobalBufferViews();HEAP32[0]=255;if(HEAPU8[0]!==255||HEAPU8[3]!==0)throw"Typed arrays 2 must be run on a little-endian system";Module["HEAP"]=HEAP;Module["buffer"]=buffer;Module["HEAP8"]=HEAP8;Module["HEAP16"]=HEAP16;Module["HEAP32"]=HEAP32;Module["HEAPU8"]=HEAPU8;Module["HEAPU16"]=HEAPU16;Module["HEAPU32"]=HEAPU32;Module["HEAPF32"]=HEAPF32;Module["HEAPF64"]=HEAPF64;function callRuntimeCallbacks(callbacks){while(callbacks.length>0){var callback=callbacks.shift();if(typeof callback=="function"){callback();continue}var func=callback.func;if(typeof func==="number"){if(callback.arg===undefined){Runtime.dynCall("v",func)}else{Runtime.dynCall("vi",func,[callback.arg])}}else{func(callback.arg===undefined?null:callback.arg)}}}var __ATPRERUN__=[];var __ATINIT__=[];var __ATMAIN__=[];var __ATEXIT__=[];var __ATPOSTRUN__=[];var runtimeInitialized=false;var runtimeExited=false;function preRun(){if(Module["preRun"]){if(typeof Module["preRun"]=="function")Module["preRun"]=[Module["preRun"]];while(Module["preRun"].length){addOnPreRun(Module["preRun"].shift())}}callRuntimeCallbacks(__ATPRERUN__)}function ensureInitRuntime(){if(runtimeInitialized)return;runtimeInitialized=true;callRuntimeCallbacks(__ATINIT__)}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){callRuntimeCallbacks(__ATEXIT__);runtimeExited=true}function postRun(){if(Module["postRun"]){if(typeof Module["postRun"]=="function")Module["postRun"]=[Module["postRun"]];while(Module["postRun"].length){addOnPostRun(Module["postRun"].shift())}}callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(cb){__ATPRERUN__.unshift(cb)}Module["addOnPreRun"]=addOnPreRun;function addOnInit(cb){__ATINIT__.unshift(cb)}Module["addOnInit"]=addOnInit;function addOnPreMain(cb){__ATMAIN__.unshift(cb)}Module["addOnPreMain"]=addOnPreMain;function addOnExit(cb){__ATEXIT__.unshift(cb)}Module["addOnExit"]=addOnExit;function addOnPostRun(cb){__ATPOSTRUN__.unshift(cb)}Module["addOnPostRun"]=addOnPostRun;function intArrayFromString(stringy,dontAddNull,length){var len=length>0?length:lengthBytesUTF8(stringy)+1;var u8array=new Array(len);var numBytesWritten=stringToUTF8Array(stringy,u8array,0,u8array.length);if(dontAddNull)u8array.length=numBytesWritten;return u8array}Module["intArrayFromString"]=intArrayFromString;function intArrayToString(array){var ret=[];for(var i=0;i<array.length;i++){var chr=array[i];if(chr>255){chr&=255}ret.push(String.fromCharCode(chr))}return ret.join("")}Module["intArrayToString"]=intArrayToString;function writeStringToMemory(string,buffer,dontAddNull){var array=intArrayFromString(string,dontAddNull);var i=0;while(i<array.length){var chr=array[i];HEAP8[buffer+i>>0]=chr;i=i+1}}Module["writeStringToMemory"]=writeStringToMemory;function writeArrayToMemory(array,buffer){for(var i=0;i<array.length;i++){HEAP8[buffer++>>0]=array[i]}}Module["writeArrayToMemory"]=writeArrayToMemory;function writeAsciiToMemory(str,buffer,dontAddNull){for(var i=0;i<str.length;++i){HEAP8[buffer++>>0]=str.charCodeAt(i)}if(!dontAddNull)HEAP8[buffer>>0]=0}Module["writeAsciiToMemory"]=writeAsciiToMemory;if(!Math["imul"]||Math["imul"](4294967295,5)!==-5)Math["imul"]=function imul(a,b){var ah=a>>>16;var al=a&65535;var bh=b>>>16;var bl=b&65535;return al*bl+(ah*bl+al*bh<<16)|0};Math.imul=Math["imul"];if(!Math["clz32"])Math["clz32"]=(function(x){x=x>>>0;for(var i=0;i<32;i++){if(x&1<<31-i)return i}return 32});Math.clz32=Math["clz32"];var Math_abs=Math.abs;var Math_cos=Math.cos;var Math_sin=Math.sin;var Math_tan=Math.tan;var Math_acos=Math.acos;var Math_asin=Math.asin;var Math_atan=Math.atan;var Math_atan2=Math.atan2;var Math_exp=Math.exp;var Math_log=Math.log;var Math_sqrt=Math.sqrt;var Math_ceil=Math.ceil;var Math_floor=Math.floor;var Math_pow=Math.pow;var Math_imul=Math.imul;var Math_fround=Math.fround;var Math_min=Math.min;var Math_clz32=Math.clz32;var runDependencies=0;var runDependencyWatcher=null;var dependenciesFulfilled=null;function addRunDependency(id){runDependencies++;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}}Module["addRunDependency"]=addRunDependency;function removeRunDependency(id){runDependencies--;if(Module["monitorRunDependencies"]){Module["monitorRunDependencies"](runDependencies)}if(runDependencies==0){if(runDependencyWatcher!==null){clearInterval(runDependencyWatcher);runDependencyWatcher=null}if(dependenciesFulfilled){var callback=dependenciesFulfilled;dependenciesFulfilled=null;callback()}}}Module["removeRunDependency"]=removeRunDependency;Module["preloadedImages"]={};Module["preloadedAudios"]={};var ASM_CONSTS=[];STATIC_BASE=8;STATICTOP=STATIC_BASE+58176;__ATINIT__.push();allocate([0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,63,0,0,0,0,0,0,240,63,0,0,0,0,0,0,248,63,0,0,0,0,0,0,4,64,0,0,0,0,0,0,18,64,0,0,0,0,0,0,33,64,0,0,0,0,0,128,48,64,0,0,0,4,107,244,52,66,0,0,0,0,0,0,0,0,0,0,0,0,0,0,224,63,0,0,0,0,0,0,240,63,0,0,0,0,0,0,248,63,0,0,0,0,0,0,0,64,0,0,0,0,0,0,4,64,0,0,0,0,0,0,18,64,0,0,0,0,0,0,33,64,0,0,0,4,107,244,52,66,0,0,0,0,1,0,0,0,3,0,0,0,7,0,0,0,15,0,0,0,31,0,0,0,63,0,0,0,127,0,0,0,255,0,0,0,255,1,0,0,255,3,0,0,255,7,0,0,255,15,0,0,255,31,0,0,255,63,0,0,255,127,0,0,255,255,0,0,255,255,1,0,255,255,3,0,255,255,7,0,255,255,15,0,255,255,31,0,255,255,63,0,255,255,127,0,255,255,255,0,255,255,255,1,255,255,255,3,255,255,255,7,255,255,255,15,255,255,255,31,255,255,255,63,255,255,255,127,255,255,255,255,1,0,0,0,1,0,0,0,2,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,1,0,0,0,0,0,0,0,4,0,0,0,5,0,0,0,3,0,0,0,4,0,0,0,6,0,0,0,2,0,0,0,0,0,0,0,7,0,0,0,8,0,0,0,5,0,0,0,6,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,7,0,0,0,8,0,0,0,5,0,0,0,6,0,0,0,2,0,0,0,1,0,0,0,3,0,0,0,2,0,0,0,7,0,0,0,8,0,0,0,5,0,0,0,6,0,0,0,4,0,0,0,2,0,0,0,5,0,0,0,1,0,0,0,9,0,0,0,7,0,0,0,1,0,0,0,10,0,0,0,232,1,0,0,104,2,0,0,104,3,0,0,104,5,0,0,104,9,0,0,104,17,0,0,104,33,0,0,104,65,0,0,24,0,120,58,76,70,11,60,242,204,192,60,116,252,59,61,86,73,154,61,241,93,228,61,248,163,29,62,180,231,78,62,54,157,130,62,78,220,159,62,193,174,190,62,65,132,222,62,173,194,254,62,186,101,15,63,248,0,31,63,29,233,45,63,249,219,59,63,45,162,72,63,160,17,84,63,38,15,94,63,46,143,102,63,112,149,109,63,174,51,115,63,159,135,119,63,66,184,122,63,196,242,124,63,75,103,126,63,196,69,127,63,241,186,127,63,217,237,127,63,162,253,127,63,248,255,127,63,168,9,120,57,17,119,11,59,135,139,193,59,74,113,61,60,148,82,156,60,94,8,233,60,42,83,34,61,74,118,87,61,138,227,137,61,7,140,171,61,34,154,208,61,108,239,248,61,164,52,18,62,100,112,41,62,65,21,66,62,67,11,92,62,47,56,119,62,197,191,137,62,92,97,152,62,135,112,167,62,4,220,182,62,188,145,198,62,231,126,214,62,48,144,230,62,227,177,246,62,13,104,3,63,121,107,11,63,98,89,19,63,42,40,27,63,137,206,34,63,166,67,42,63,49,127,49,63,126,121,56,63,153,43,63,63,92,143,69,63,127,159,75,63,165,87,81,63,104,180,86,63,89,179,91,63,8,83,96,63,252,146,100,63,177,115,104,63,138,246,107,63,198,29,111,63,109,236,113,63,62,102,116,63,154,143,118,63,104,109,120,63,3,5,122,63,26,92,123,63,153,120,124,63,143,96,125,63,17,26,126,63,39,171,126,63,176,25,127,63,74,107,127,63,68,165,127,63,132,204,127,63,123,229,127,63,17,244,127,63,158,251,127,63,219,254,127,63,218,255,127,63,0,0,128,63,5,12,120,56,50,131,11,58,118,186,193,58,226,203,61,59,38,207,156,59,139,32,234,59,245,102,35,60,63,100,89,60,184,127,139,60,59,23,174,60,239,114,212,60,96,140,254,60,45,46,22,61,114,237,46,61,155,127,73,61,220,223,101,61,123,4,130,61,159,250,145,61,71,207,162,61,38,127,180,61,173,6,199,61,16,98,218,61,63,141,238,61,244,193,1,62,185,160,12,62,128,224,23,62,182,126,35,62,166,120,47,62,116,203,59,62,34,116,72,62,141,111,85,62,107,186,98,62,83,81,112,62,180,48,126,62,110,42,134,62,252,92,141,62,9,174,148,62,138,27,156,62,100,163,163,62,112,67,171,62,119,249,178,62,54,195,186,62,93,158,194,62,147,136,202,62,118,127,210,62,154,128,218,62,142,137,226,62,217,151,234,62,2,169,242,62,139,186,250,62,251,100,1,63,99,106,5,63,65,108,9,63,89,105,13,63,116,96,17,63,94,80,21,63,231,55,25,63,231,21,29,63,58,233,32,63,197,176,36,63,116,107,40,63,62,24,44,63,35,182,47,63,43,68,51,63,109,193,54,63,10,45,58,63,48,134,61,63,26,204,64,63,17,254,67,63,107,27,71,63,142,35,74,63,238,21,77,63,15,242,79,63,132,183,82,63,239,101,85,63,3,253,87,63,129,124,90,63,60,228,92,63,21,52,95,63,254,107,97,63,246,139,99,63,14,148,101,63,98,132,103,63,33,93,105,63,133,30,107,63,213,200,108,63,103,92,110,63,155,217,111,63,224,64,113,63,172,146,114,63,131,207,115,63,241,247,116,63,139,12,118,63,239,13,119,63,193,252,119,63,172,217,120,63,99,165,121,63,155,96,122,63,15,12,123,63,124,168,123,63,163,54,124,63,71,183,124,63,41,43,125,63,13,147,125,63,183,239,125,63,229,65,126,63,89,138,126,63,205,201,126,63,251,0,127,63,150,48,127,63,78,89,127,63,205,123,127,63,182,152,127,63,167,176,127,63,53,196,127,63,239,211,127,63,91,224,127,63,245,233,127,63,51,241,127,63,127,246,127,63,59,250,127,63,190,252,127,63,84,254,127,63,64,255,127,63,186,255,127,63,238,255,127,63,254,255,127,63,0,0,128,63,169,12,120,55,54,134,11,57,38,198,193,57,94,226,61,58,234,237,156,58,85,101,234,58,56,170,35,59,207,219,89,59,169,226,139,59,42,178,174,59,13,91,213,59,204,219,255,59,91,25,23,60,250,46,48,60,194,45,75,60,156,20,104,60,46,113,131,60,225,202,147,60,185,22,165,60,1,84,183,60,245,129,202,60,198,159,222,60,155,172,243,60,199,211,4,61,213,71,16,61,250,49,28,61,174,145,40,61,101,102,53,61,141,175,66,61,140,108,80,61,193,156,94,61,133,63,109,61,41,84,124,61,252,236,133,61,26,232,141,61,13,27,150,61,110,133,158,61,212,38,167,61,210,254,175,61,245,12,185,61,200,80,194,61,209,201,203,61,146,119,213,61,139,89,223,61,51,111,233,61,2,184,243,61,105,51,254,61,106,112,4,62,214,223,9,62,171,103,15,62,153,7,21,62,77,191,26,62,116,142,32,62,181,116,38,62,184,113,44,62,34,133,50,62,149,174,56,62,178,237,62,62,21,66,69,62,92,171,75,62,30,41,82,62,243,186,88,62,112,96,95,62,40,25,102,62,170,228,108,62,132,194,115,62,68,178,122,62,185,217,128,62,203,98,132,62,26,244,135,62,105,141,139,62,120,46,143,62,6,215,146,62,211,134,150,62,156,61,154,62,29,251,157,62,19,191,161,62,57,137,165,62,71,89,169,62,249,46,173,62,5,10,177,62,36,234,180,62,13,207,184,62,117,184,188,62,18,166,192,62,153,151,196,62,190,140,200,62,52,133,204,62,175,128,208,62,225,126,212,62,125,127,216,62,52,130,220,62,184,134,224,62,185,140,228,62,233,147,232,62,248,155,236,62,150,164,240,62,117,173,244,62,67,182,248,62,178,190,252,62,57,99,0,63,153,102,2,63,82,105,4,63,60,107,6,63,48,108,8,63,6,108,10,63,151,106,12,63,188,103,14,63,78,99,16,63,39,93,18,63,33,85,20,63,21,75,22,63,222,62,24,63,87,48,26,63,92,31,28,63,199,11,30,63,117,245,31,63,66,220,33,63,12,192,35,63,176,160,37,63,12,126,39,63,254,87,41,63,104,46,43,63,39,1,45,63,29,208,46,63,43,155,48,63,51,98,50,63,23,37,52,63,188,227,53,63,4,158,55,63,214,83,57,63,23,5,59,63,173,177,60,63,128,89,62,63,120,252,63,63,126,154,65,63,124,51,67,63,93,199,68,63,12,86,70,63,119,223,71,63,138,99,73,63,54,226,74,63,104,91,76,63,17,207,77,63,35,61,79,63,145,165,80,63,76,8,82,63,75,101,83,63,130,188,84,63,231,13,86,63,114,89,87,63,26,159,88,63,218,222,89,63,172,24,91,63,138,76,92,63,113,122,93,63,93,162,94,63,78,196,95,63,67,224,96,63,58,246,97,63,54,6,99,63,56,16,100,63,67,20,101,63,92,18,102,63,133,10,103,63,198,252,103,63,37,233,104,63,168,207,105,63,89,176,106,63,64,139,107,63,102,96,108,63,216,47,109,63,159,249,109,63,201,189,110,63,97,124,111,63,118,53,112,63,23,233,112,63,81,151,113,63,53,64,114,63,212,227,114,63,61,130,115,63,131,27,116,63,184,175,116,63,238,62,117,63,56,201,117,63,171,78,118,63,90,207,118,63,90,75,119,63,192,194,119,63,162,53,120,63,21,164,120,63,48,14,121,63,8,116,121,63,182,213,121,63,79,51,122,63,235,140,122,63,162,226,122,63,139,52,123,63,191,130,123,63,85,205,123,63,102,20,124,63,9,88,124,63,88,152,124,63,106,213,124,63,88,15,125,63,58,70,125,63,41,122,125,63,62,171,125,63,143,217,125,63,54,5,126,63,75,46,126,63,228,84,126,63,27,121,126,63,7,155,126,63,190,186,126,63,88,216,126,63,236,243,126,63,144,13,127,63,91,37,127,63,99,59,127,63,188,79,127,63,125,98,127,63,185,115,127,63,135,131,127,63,249,145,127,63,36,159,127,63,26,171,127,63,238,181,127,63,179,191,127,63,122,200,127,63,85,208,127,63,84,215,127,63,136,221,127,63,0,227,127,63,204,231,127,63,249,235,127,63,150,239,127,63,177,242,127,63,85,245,127,63,144,247,127,63,109,249,127,63,246,250,127,63,54,252,127,63,55,253,127,63,1,254,127,63,156,254,127,63,18,255,127,63,103,255,127,63,163,255,127,63,204,255,127,63,229,255,127,63,244,255,127,63,252,255,127,63,255,255,127,63,0,0,128,63,0,0,128,63,60,12,120,54,253,134,11,56,19,201,193,56,248,231,61,57,148,245,156,57,115,118,234,57,238,186,35,58,113,249,89,58,32,251,139,58,96,216,174,58,34,148,213,58,3,23,0,59,209,82,23,59,65,125,48,59,21,150,75,59,8,157,104,59,233,200,131,59,20,58,148,59,218,161,165,59,16,0,184,59,136,84,203,59,16,159,223,59,118,223,244,59,194,138,5,60,128,32,17,60,217,48,29,60,172,187,41,60,219,192,54,60,67,64,68,60,194,57,82,60,52,173,96,60,115,154,111,60,88,1,127,60,222,112,135,60,186,157,143,60,42,7,152,60,25,173,160,60,112,143,169,60,23,174,178,60,246,8,188,60,243,159,197,60,245,114,207,60,225,129,217,60,156,204,227,60,10,83,238,60,14,21,249,60,70,9,2,61,177,165,7,61,187,95,13,61,81,55,19,61,102,44,25,61,230,62,31,61,195,110,37,61,233,187,43,61,71,38,50,61,202,173,56,61,97,82,63,61,247,19,70,61,121,242,76,61,210,237,83,61,240,5,91,61,187,58,98,61,32,140,105,61,8,250,112,61,93,132,120,61,132,21,128,61,249,246,131,61,130,230,135,61,19,228,139,61,159,239,143,61,26,9,148,61,119,48,152,61,169,101,156,61,163,168,160,61,88,249,164,61,186,87,169,61,186,195,173,61,76,61,178,61,95,196,182,61,230,88,187,61,209,250,191,61,18,170,196,61,152,102,201,61,85,48,206,61,56,7,211,61,48,235,215,61,47,220,220,61,34,218,225,61,248,228,230,61,161,252,235,61,11,33,241,61,35,82,246,61,217,143,251,61,13,109,0,62,105,24,3,62,247,201,5,62,174,129,8,62,133,63,11,62,113,3,14,62,104,205,16,62,96,157,19,62,79,115,22,62,42,79,25,62,232,48,28,62,124,24,31,62,221,5,34,62,255,248,36,62,215,241,39,62,90,240,42,62,125,244,45,62,51,254,48,62,114,13,52,62,45,34,55,62,88,60,58,62,232,91,61,62,208,128,64,62,3,171,67,62,118,218,70,62,26,15,74,62,229,72,77,62,199,135,80,62,181,203,83,62,162,20,87,62,127,98,90,62,63,181,93,62,213,12,97,62,50,105,100,62,73,202,103,62,12,48,107,62,108,154,110,62,92,9,114,62,203,124,117,62,173,244,120,62,241,112,124,62,138,241,127,62,52,187,129,62,190,127,131,62,91,70,133,62,4,15,135,62,176,217,136,62,89,166,138,62,245,116,140,62,126,69,142,62,234,23,144,62,50,236,145,62,78,194,147,62,54,154,149,62,224,115,151,62,70,79,153,62,93,44,155,62,31,11,157,62,130,235,158,62,127,205,160,62,11,177,162,62,31,150,164,62,177,124,166,62,186,100,168,62,47,78,170,62,9,57,172,62,62,37,174,62,198,18,176,62,150,1,178,62,167,241,179,62,238,226,181,62,100,213,183,62,254,200,185,62,179,189,187,62,122,179,189,62,74,170,191,62,25,162,193,62,221,154,195,62,142,148,197,62,34,143,199,62,142,138,201,62,203,134,203,62,205,131,205,62,140,129,207,62,253,127,209,62,24,127,211,62,210,126,213,62,33,127,215,62,252,127,217,62,88,129,219,62,45,131,221,62,112,133,223,62,23,136,225,62,25,139,227,62,108,142,229,62,5,146,231,62,219,149,233,62,228,153,235,62,21,158,237,62,102,162,239,62,203,166,241,62,59,171,243,62,173,175,245,62,21,180,247,62,107,184,249,62,164,188,251,62,181,192,253,62,150,196,255,62,30,228,0,63,207,229,1,63,88,231,2,63,182,232,3,63,226,233,4,63,215,234,5,63,146,235,6,63,12,236,7,63,66,236,8,63,45,236,9,63,202,235,10,63,19,235,11,63,4,234,12,63,151,232,13,63,200,230,14,63,145,228,15,63,239,225,16,63,220,222,17,63,84,219,18,63,81,215,19,63,208,210,20,63,202,205,21,63,61,200,22,63,34,194,23,63,117,187,24,63,50,180,25,63,85,172,26,63,215,163,27,63,182,154,28,63,236,144,29,63,117,134,30,63,77,123,31,63,110,111,32,63,214,98,33,63,126,85,34,63,100,71,35,63,130,56,36,63,212,40,37,63,87,24,38,63,5,7,39,63,219,244,39,63,213,225,40,63,239,205,41,63,36,185,42,63,113,163,43,63,209,140,44,63,64,117,45,63,188,92,46,63,63,67,47,63,199,40,48,63,78,13,49,63,211,240,49,63,80,211,50,63,195,180,51,63,39,149,52,63,122,116,53,63,184,82,54,63,220,47,55,63,229,11,56,63,206,230,56,63,149,192,57,63,54,153,58,63,174,112,59,63,249,70,60,63,21,28,61,63,255,239,61,63,179,194,62,63,48,148,63,63,113,100,64,63,116,51,65,63,55,1,66,63,182,205,66,63,239,152,67,63,224,98,68,63,134,43,69,63,222,242,69,63,230,184,70,63,156,125,71,63,253,64,72,63,7,3,73,63,184,195,73,63,14,131,74,63,6,65,75,63,159,253,75,63,215,184,76,63,172,114,77,63,28,43,78,63,38,226,78,63,199,151,79,63,253,75,80,63,201,254,80,63,39,176,81,63,22,96,82,63,150,14,83,63,164,187,83,63,63,103,84,63,103,17,85,63,26,186,85,63,86,97,86,63,28,7,87,63,105,171,87,63,62,78,88,63,152,239,88,63,120,143,89,63,221,45,90,63,198,202,90,63,50,102,91,63,33,0,92,63,147,152,92,63,134,47,93,63,251,196,93,63,242,88,94,63,105,235,94,63,98,124,95,63,219,11,96,63,213,153,96,63,80,38,97,63,76,177,97,63,201,58,98,63,199,194,98,63,70,73,99,63,71,206,99,63,202,81,100,63,208,211,100,63,88,84,101,63,100,211,101,63,244,80,102,63,9,205,102,63,163,71,103,63,195,192,103,63,107,56,104,63,154,174,104,63,82,35,105,63,147,150,105,63,96,8,106,63,184,120,106,63,157,231,106,63,16,85,107,63,19,193,107,63,166,43,108,63,203,148,108,63,132,252,108,63,209,98,109,63,180,199,109,63,48,43,110,63,68,141,110,63,244,237,110,63,64,77,111,63,42,171,111,63,181,7,112,63,225,98,112,63,177,188,112,63,38,21,113,63,67,108,113,63,10,194,113,63,123,22,114,63,155,105,114,63,106,187,114,63,234,11,115,63,31,91,115,63,9,169,115,63,172,245,115,63,9,65,116,63,35,139,116,63,252,211,116,63,151,27,117,63,245,97,117,63,26,167,117,63,8,235,117,63,193,45,118,63,72,111,118,63,159,175,118,63,202,238,118,63,201,44,119,63,161,105,119,63,84,165,119,63,228,223,119,63,85,25,120,63,168,81,120,63,226,136,120,63,3,191,120,63,16,244,120,63,11,40,121,63,247,90,121,63,215,140,121,63,173,189,121,63,125,237,121,63,73,28,122,63,20,74,122,63,226,118,122,63,181,162,122,63,144,205,122,63,118,247,122,63,107,32,123,63,112,72,123,63,138,111,123,63,186,149,123,63,5,187,123,63,109,223,123,63,245,2,124,63,160,37,124,63,113,71,124,63,108,104,124,63,147,136,124,63,233,167,124,63,114,198,124,63,48,228,124,63,38,1,125,63,89,29,125,63,201,56,125,63,124,83,125,63,115,109,125,63,178,134,125,63,60,159,125,63,19,183,125,63,60,206,125,63,184,228,125,63,139,250,125,63,184,15,126,63,66,36,126,63,44,56,126,63,120,75,126,63,43,94,126,63,70,112,126,63,204,129,126,63,194,146,126,63,41,163,126,63,4,179,126,63,86,194,126,63,35,209,126,63,109,223,126,63,55,237,126,63,131,250,126,63,85,7,127,63,175,19,127,63,148,31,127,63,7,43,127,63,10,54,127,63,160,64,127,63,205,74,127,63,146,84,127,63,242,93,127,63,239,102,127,63,141,111,127,63,206,119,127,63,181,127,127,63,67,135,127,63,124,142,127,63,98,149,127,63,247,155,127,63,61,162,127,63,56,168,127,63,233,173,127,63,83,179,127,63,120,184,127,63,90,189,127,63,252,193,127,63,95,198,127,63,134,202,127,63,116,206,127,63,41,210,127,63,168,213,127,63,244,216,127,63,13,220,127,63,247,222,127,63,179,225,127,63,67,228,127,63,168,230,127,63,229,232,127,63,252,234,127,63,237,236,127,63,188,238,127,63,105,240,127,63,246,241,127,63,101,243,127,63,183,244,127,63,238,245,127,63,11,247,127,63,16,248,127,63,254,248,127,63,214,249,127,63,155,250,127,63,76,251,127,63,236,251,127,63,124,252,127,63,252,252,127,63,110,253,127,63,211,253,127,63,44,254,127,63,121,254,127,63,189,254,127,63,247,254,127,63,42,255,127,63,84,255,127,63,120,255,127,63,150,255,127,63,175,255,127,63,195,255,127,63,211,255,127,63,224,255,127,63,234,255,127,63,241,255,127,63,246,255,127,63,250,255,127,63,253,255,127,63,254,255,127,63,255,255,127,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,171,15,120,53,24,135,11,55,225,201,193,55,107,233,61,56,128,247,156,56,187,122,234,56,24,191,35,57,213,0,90,57,56,1,140,57,229,225,174,57,88,162,213,57,60,33,0,58,24,97,23,58,175,144,48,58,243,175,75,58,212,190,104,58,159,222,131,58,143,85,148,58,48,196,165,58,119,42,184,58,90,136,203,58,204,221,223,58,191,42,245,58,148,183,5,59,124,85,17,59,16,111,29,59,73,4,42,59,31,21,55,59,138,161,68,59,129,169,82,59,252,44,97,59,241,43,112,59,88,166,127,59,19,206,135,59,169,6,144,59,233,124,152,59,204,48,161,59,79,34,170,59,106,81,179,59,26,190,188,59,86,104,198,59,26,80,208,59,95,117,218,59,31,216,228,59,83,120,239,59,244,85,250,59,126,184,2,60,177,100,8,60,145,47,14,60,25,25,20,60,70,33,26,60,19,72,32,60,126,141,38,60,129,241,44,60,25,116,51,60,65,21,58,60,246,212,64,60,50,179,71,60,243,175,78,60,50,203,85,60,235,4,93,60,26,93,100,60,186,211,107,60,198,104,115,60,58,28,123,60,7,119,129,60,33,111,133,60,102,118,137,60,212,140,141,60,105,178,145,60,33,231,149,60,251,42,154,60,243,125,158,60,6,224,162,60,50,81,167,60,115,209,171,60,199,96,176,60,43,255,180,60,154,172,185,60,19,105,190,60,146,52,195,60,20,15,200,60,149,248,204,60,19,241,209,60,137,248,214,60,245,14,220,60,83,52,225,60,160,104,230,60,215,171,235,60,246,253,240,60,249,94,246,60,220,206,251,60,205,166,0,61,153,109,3,61,207,59,6,61,109,17,9,61,114,238,11,61,220,210,14,61,167,190,17,61,211,177,20,61,94,172,23,61,68,174,26,61,133,183,29,61,30,200,32,61,12,224,35,61,78,255,38,61,225,37,42,61,196,83,45,61,243,136,48,61,109,197,51,61,47,9,55,61,55,84,58,61,130,166,61,61,15,0,65,61,218,96,68,61,226,200,71,61,35,56,75,61,156,174,78,61,73,44,82,61,40,177,85,61,55,61,89,61,115,208,92,61,217,106,96,61,103,12,100,61,25,181,103,61,238,100,107,61,227,27,111,61,244,217,114,61,30,159,118,61,96,107,122,61,182,62,126,61,143,12,129,61,73,253,130,61,138,241,132,61,79,233,134,61,150,228,136,61,94,227,138,61,167,229,140,61,109,235,142,61,175,244,144,61,109,1,147,61,164,17,149,61,83,37,151,61,120,60,153,61,17,87,155,61,30,117,157,61,155,150,159,61,136,187,161,61,226,227,163,61,169,15,166,61,218,62,168,61,116,113,170,61,116,167,172,61,218,224,174,61,162,29,177,61,205,93,179,61,87,161,181,61,62,232,183,61,130,50,186,61,32,128,188,61,22,209,190,61,98,37,193,61,2,125,195,61,245,215,197,61,57,54,200,61,203,151,202,61,169,252,204,61,211,100,207,61,68,208,209,61,252,62,212,61,249,176,214,61,56,38,217,61,184,158,219,61,117,26,222,61,111,153,224,61,163,27,227,61,14,161,229,61,175,41,232,61,132,181,234,61,138,68,237,61,191,214,239,61,33,108,242,61,174,4,245,61,99,160,247,61,62,63,250,61,61,225,252,61,93,134,255,61,78,23,1,62,252,108,2,62,56,196,3,62,255,28,5,62,81,119,6,62,45,211,7,62,145,48,9,62,125,143,10,62,238,239,11,62,228,81,13,62,94,181,14,62,89,26,16,62,214,128,17,62,210,232,18,62,77,82,20,62,69,189,21,62,184,41,23,62,166,151,24,62,13,7,26,62,236,119,27,62,65,234,28,62,11,94,30,62,73,211,31,62,250,73,33,62,28,194,34,62,173,59,36,62,172,182,37,62,24,51,39,62,240,176,40,62,50,48,42,62,220,176,43,62,238,50,45,62,101,182,46,62,64,59,48,62,126,193,49,62,30,73,51,62,29,210,52,62,123,92,54,62,54,232,55,62,76,117,57,62,187,3,59,62,131,147,60,62,162,36,62,62,22,183,63,62,222,74,65,62,248,223,66,62,98,118,68,62,28,14,70,62,35,167,71,62,117,65,73,62,18,221,74,62,247,121,76,62,35,24,78,62,149,183,79,62,74,88,81,62,66,250,82,62,121,157,84,62,240,65,86,62,163,231,87,62,146,142,89,62,186,54,91,62,26,224,92,62,177,138,94,62,124,54,96,62,122,227,97,62,169,145,99,62,7,65,101,62,147,241,102,62,75,163,104,62,44,86,106,62,54,10,108,62,102,191,109,62,187,117,111,62,51,45,113,62,204,229,114,62,132,159,116,62,90,90,118,62,75,22,120,62,85,211,121,62,120,145,123,62,176,80,125,62,253,16,127,62,46,105,128,62,101,74,129,62,36,44,130,62,105,14,131,62,52,241,131,62,130,212,132,62,84,184,133,62,169,156,134,62,127,129,135,62,213,102,136,62,171,76,137,62,255,50,138,62,209,25,139,62,32,1,140,62,233,232,140,62,46,209,141,62,236,185,142,62,34,163,143,62,208,140,144,62,244,118,145,62,142,97,146,62,156,76,147,62,29,56,148,62,17,36,149,62,118,16,150,62,76,253,150,62,144,234,151,62,67,216,152,62,99,198,153,62,239,180,154,62,230,163,155,62,71,147,156,62,17,131,157,62,67,115,158,62,219,99,159,62,218,84,160,62,60,70,161,62,3,56,162,62,43,42,163,62,181,28,164,62,160,15,165,62,233,2,166,62,145,246,166,62,149,234,167,62,245,222,168,62,176,211,169,62,197,200,170,62,50,190,171,62,246,179,172,62,17,170,173,62,129,160,174,62,69,151,175,62,91,142,176,62,196,133,177,62,125,125,178,62,133,117,179,62,220,109,180,62,128,102,181,62,112,95,182,62,171,88,183,62,47,82,184,62,252,75,185,62,17,70,186,62,108,64,187,62,11,59,188,62,239,53,189,62,22,49,190,62,126,44,191,62,38,40,192,62,13,36,193,62,51,32,194,62,150,28,195,62,52,25,196,62,12,22,197,62,30,19,198,62,104,16,199,62,233,13,200,62,159,11,201,62,138,9,202,62,169,7,203,62,249,5,204,62,123,4,205,62,44,3,206,62,11,2,207,62,24,1,208,62,81,0,209,62,181,255,209,62,66,255,210,62,248,254,211,62,213,254,212,62,216,254,213,62,255,254,214,62,75,255,215,62,184,255,216,62,71,0,218,62,245,0,219,62,195,1,220,62,173,2,221,62,180,3,222,62,214,4,223,62,17,6,224,62,101,7,225,62,208,8,226,62,81,10,227,62,231,11,228,62,144,13,229,62,76,15,230,62,25,17,231,62,245,18,232,62,224,20,233,62,217,22,234,62,221,24,235,62,236,26,236,62,5,29,237,62,39,31,238,62,79,33,239,62,125,35,240,62,176,37,241,62,230,39,242,62,31,42,243,62,88,44,244,62,145,46,245,62,200,48,246,62,253,50,247,62,45,53,248,62,88,55,249,62,124,57,250,62,153,59,251,62,172,61,252,62,181,63,253,62,179,65,254,62,163,67,255,62,195,34,0,63,173,163,0,63,142,36,1,63,102,165,1,63,53,38,2,63,250,166,2,63,180,39,3,63,99,168,3,63,5,41,4,63,155,169,4,63,36,42,5,63,159,170,5,63,12,43,6,63,105,171,6,63,183,43,7,63,244,171,7,63,32,44,8,63,59,172,8,63,68,44,9,63,58,172,9,63,28,44,10,63,235,171,10,63,164,43,11,63,73,171,11,63,216,42,12,63,80,170,12,63,177,41,13,63,251,168,13,63,44,40,14,63,69,167,14,63,68,38,15,63,41,165,15,63,243,35,16,63,162,162,16,63,53,33,17,63,172,159,17,63,5,30,18,63,65,156,18,63,95,26,19,63,94,152,19,63,61,22,20,63,252,147,20,63,155,17,21,63,24,143,21,63,116,12,22,63,173,137,22,63,195,6,23,63,182,131,23,63,133,0,24,63,46,125,24,63,179,249,24,63,18,118,25,63,74,242,25,63,91,110,26,63,69,234,26,63,6,102,27,63,159,225,27,63,14,93,28,63,84,216,28,63,111,83,29,63,95,206,29,63,36,73,30,63,188,195,30,63,40,62,31,63,102,184,31,63,119,50,32,63,90,172,32,63,14,38,33,63,146,159,33,63,230,24,34,63,10,146,34,63,253,10,35,63,190,131,35,63,77,252,35,63,169,116,36,63,211,236,36,63,200,100,37,63,138,220,37,63,22,84,38,63,110,203,38,63,143,66,39,63,122,185,39,63,47,48,40,63,172,166,40,63,241,28,41,63,254,146,41,63,210,8,42,63,108,126,42,63,205,243,42,63,243,104,43,63,223,221,43,63,143,82,44,63,3,199,44,63,59,59,45,63,54,175,45,63,244,34,46,63,116,150,46,63,182,9,47,63,185,124,47,63,125,239,47,63,1,98,48,63,69,212,48,63,72,70,49,63,10,184,49,63,139,41,50,63,202,154,50,63,198,11,51,63,127,124,51,63,246,236,51,63,40,93,52,63,22,205,52,63,191,60,53,63,36,172,53,63,66,27,54,63,27,138,54,63,174,248,54,63,249,102,55,63,254,212,55,63,187,66,56,63,47,176,56,63,91,29,57,63,63,138,57,63,217,246,57,63,41,99,58,63,48,207,58,63,236,58,59,63,93,166,59,63,130,17,60,63,93,124,60,63,235,230,60,63,44,81,61,63,33,187,61,63,201,36,62,63,35,142,62,63,48,247,62,63,238,95,63,63,94,200,63,63,126,48,64,63,80,152,64,63,209,255,64,63,3,103,65,63,228,205,65,63,117,52,66,63,181,154,66,63,163,0,67,63,64,102,67,63,139,203,67,63,131,48,68,63,41,149,68,63,124,249,68,63,123,93,69,63,39,193,69,63,127,36,70,63,132,135,70,63,51,234,70,63,142,76,71,63,148,174,71,63,68,16,72,63,159,113,72,63,164,210,72,63,83,51,73,63,172,147,73,63,174,243,73,63,89,83,74,63,173,178,74,63,169,17,75,63,77,112,75,63,154,206,75,63,143,44,76,63,43,138,76,63,110,231,76,63,89,68,77,63,234,160,77,63,34,253,77,63,0,89,78,63,133,180,78,63,176,15,79,63,128,106,79,63,246,196,79,63,18,31,80,63,210,120,80,63,56,210,80,63,66,43,81,63,242,131,81,63,69,220,81,63,61,52,82,63,217,139,82,63,24,227,82,63,252,57,83,63,131,144,83,63,174,230,83,63,123,60,84,63,236,145,84,63,0,231,84,63,183,59,85,63,16,144,85,63,12,228,85,63,170,55,86,63,235,138,86,63,206,221,86,63,83,48,87,63,121,130,87,63,66,212,87,63,172,37,88,63,184,118,88,63,101,199,88,63,180,23,89,63,164,103,89,63,53,183,89,63,104,6,90,63,59,85,90,63,175,163,90,63,197,241,90,63,123,63,91,63,210,140,91,63,201,217,91,63,97,38,92,63,154,114,92,63,115,190,92,63,237,9,93,63,7,85,93,63,194,159,93,63,29,234,93,63,24,52,94,63,179,125,94,63,239,198,94,63,203,15,95,63,72,88,95,63,100,160,95,63,33,232,95,63,126,47,96,63,123,118,96,63,24,189,96,63,85,3,97,63,51,73,97,63,177,142,97,63,207,211,97,63,141,24,98,63,236,92,98,63,235,160,98,63,138,228,98,63,202,39,99,63,170,106,99,63,42,173,99,63,75,239,99,63,13,49,100,63,111,114,100,63,114,179,100,63,21,244,100,63,90,52,101,63,63,116,101,63,197,179,101,63,236,242,101,63,180,49,102,63,29,112,102,63,39,174,102,63,211,235,102,63,32,41,103,63,15,102,103,63,159,162,103,63,209,222,103,63,164,26,104,63,26,86,104,63,49,145,104,63,235,203,104,63,71,6,105,63,69,64,105,63,230,121,105,63,42,179,105,63,16,236,105,63,153,36,106,63,197,92,106,63,148,148,106,63,7,204,106,63,29,3,107,63,214,57,107,63,52,112,107,63,53,166,107,63,218,219,107,63,36,17,108,63,18,70,108,63,164,122,108,63,220,174,108,63,184,226,108,63,57,22,109,63,96,73,109,63,44,124,109,63,157,174,109,63,181,224,109,63,115,18,110,63,214,67,110,63,225,116,110,63,146,165,110,63,233,213,110,63,232,5,111,63,142,53,111,63,219,100,111,63,209,147,111,63,110,194,111,63,179,240,111,63,160,30,112,63,54,76,112,63,117,121,112,63,93,166,112,63,239,210,112,63,41,255,112,63,14,43,113,63,156,86,113,63,213,129,113,63,184,172,113,63,70,215,113,63,127,1,114,63,99,43,114,63,243,84,114,63,46,126,114,63,21,167,114,63,169,207,114,63,233,247,114,63,214,31,115,63,113,71,115,63,184,110,115,63,173,149,115,63,80,188,115,63,162,226,115,63,161,8,116,63,80,46,116,63,174,83,116,63,187,120,116,63,119,157,116,63,228,193,116,63,1,230,116,63,206,9,117,63,76,45,117,63,123,80,117,63,92,115,117,63,238,149,117,63,51,184,117,63,42,218,117,63,211,251,117,63,48,29,118,63,64,62,118,63,3,95,118,63,122,127,118,63,166,159,118,63,134,191,118,63,27,223,118,63,101,254,118,63,101,29,119,63,27,60,119,63,135,90,119,63,169,120,119,63,131,150,119,63,19,180,119,63,91,209,119,63,91,238,119,63,20,11,120,63,132,39,120,63,174,67,120,63,145,95,120,63,46,123,120,63,132,150,120,63,149,177,120,63,96,204,120,63,231,230,120,63,41,1,121,63,38,27,121,63,223,52,121,63,85,78,121,63,136,103,121,63,120,128,121,63,37,153,121,63,144,177,121,63,185,201,121,63,161,225,121,63,72,249,121,63,174,16,122,63,212,39,122,63,185,62,122,63,96,85,122,63,198,107,122,63,238,129,122,63,216,151,122,63,131,173,122,63,241,194,122,63,33,216,122,63,20,237,122,63,202,1,123,63,68,22,123,63,130,42,123,63,133,62,123,63,77,82,123,63,217,101,123,63,43,121,123,63,68,140,123,63,34,159,123,63,200,177,123,63,52,196,123,63,104,214,123,63,99,232,123,63,39,250,123,63,180,11,124,63,9,29,124,63,40,46,124,63,17,63,124,63,196,79,124,63,65,96,124,63,137,112,124,63,156,128,124,63,124,144,124,63,39,160,124,63,158,175,124,63,226,190,124,63,244,205,124,63,211,220,124,63,128,235,124,63,251,249,124,63,69,8,125,63,94,22,125,63,71,36,125,63,255,49,125,63,136,63,125,63,225,76,125,63,11,90,125,63,7,103,125,63,212,115,125,63,115,128,125,63,229,140,125,63,42,153,125,63,66,165,125,63,46,177,125,63,238,188,125,63,130,200,125,63,235,211,125,63,41,223,125,63,61,234,125,63,38,245,125,63,230,255,125,63,124,10,126,63,234,20,126,63,47,31,126,63,75,41,126,63,64,51,126,63,13,61,126,63,180,70,126,63,51,80,126,63,140,89,126,63,191,98,126,63,205,107,126,63,181,116,126,63,120,125,126,63,23,134,126,63,146,142,126,63,233,150,126,63,28,159,126,63,44,167,126,63,26,175,126,63,229,182,126,63,142,190,126,63,22,198,126,63,124,205,126,63,194,212,126,63,231,219,126,63,235,226,126,63,208,233,126,63,149,240,126,63,59,247,126,63,195,253,126,63,44,4,127,63,118,10,127,63,163,16,127,63,179,22,127,63,165,28,127,63,123,34,127,63,52,40,127,63,210,45,127,63,83,51,127,63,186,56,127,63,5,62,127,63,53,67,127,63,75,72,127,63,72,77,127,63,42,82,127,63,243,86,127,63,163,91,127,63,58,96,127,63,185,100,127,63,32,105,127,63,111,109,127,63,166,113,127,63,199,117,127,63,208,121,127,63,196,125,127,63,161,129,127,63,104,133,127,63,25,137,127,63,182,140,127,63,61,144,127,63,176,147,127,63,14,151,127,63,89,154,127,63,143,157,127,63,179,160,127,63,195,163,127,63,192,166,127,63,171,169,127,63,132,172,127,63,74,175,127,63,255,177,127,63,163,180,127,63,53,183,127,63,183,185,127,63,40,188,127,63,137,190,127,63,217,192,127,63,26,195,127,63,76,197,127,63,111,199,127,63,130,201,127,63,135,203,127,63,126,205,127,63,102,207,127,63,65,209,127,63,14,211,127,63,205,212,127,63,128,214,127,63,38,216,127,63,191,217,127,63,76,219,127,63,204,220,127,63,65,222,127,63,170,223,127,63,8,225,127,63,91,226,127,63,163,227,127,63,224,228,127,63,19,230,127,63,59,231,127,63,90,232,127,63,110,233,127,63,122,234,127,63,124,235,127,63,116,236,127,63,100,237,127,63,75,238,127,63,42,239,127,63,1,240,127,63,207,240,127,63,149,241,127,63,84,242,127,63,12,243,127,63,188,243,127,63,101,244,127,63,7,245,127,63,162,245,127,63,55,246,127,63,198,246,127,63,78,247,127,63,209,247,127,63,77,248,127,63,196,248,127,63,54,249,127,63,162,249,127,63,9,250,127,63,108,250,127,63,201,250,127,63,34,251,127,63,118,251,127,63,198,251,127,63,18,252,127,63,89,252,127,63,157,252,127,63,221,252,127,63,26,253,127,63,83,253,127,63,136,253,127,63,187,253,127,63,234,253,127,63,22,254,127,63,64,254,127,63,103,254,127,63,139,254,127,63,173,254,127,63,204,254,127,63,234,254,127,63,5,255,127,63,30,255,127,63,53,255,127,63,74,255,127,63,94,255,127,63,112,255,127,63,128,255,127,63,143,255,127,63,157,255,127,63,169,255,127,63,180,255,127,63,191,255,127,63,200,255,127,63,208,255,127,63,215,255,127,63,221,255,127,63,227,255,127,63,232,255,127,63,236,255,127,63,239,255,127,63,243,255,127,63,245,255,127,63,248,255,127,63,249,255,127,63,251,255,127,63,252,255,127,63,253,255,127,63,254,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,204,8,120,52,171,134,11,54,79,202,193,54,190,233,61,55,238,247,156,55,192,123,234,55,43,192,35,56,161,2,90,56,189,2,140,56,76,228,174,56,227,165,213,56,199,35,0,57,168,100,23,57,134,149,48,57,104,182,75,57,64,199,104,57,7,228,131,57,105,92,148,57,191,204,165,57,6,53,184,57,65,149,203,57,105,237,223,57,120,61,245,57,184,194,5,58,166,98,17,58,134,126,29,58,81,22,42,58,9,42,55,58,172,185,68,58,54,197,82,58,165,76,97,58,250,79,112,58,47,207,127,58,34,229,135,58,154,32,144,58,255,153,152,58,80,81,161,58,139,70,170,58,174,121,179,58,186,234,188,58,171,153,198,58,129,134,208,58,58,177,218,58,212,25,229,58,79,192,239,58,167,164,250,58,109,227,2,59,117,147,8,59,105,98,14,59,73,80,20,59,19,93,26,59,199,136,32,59,100,211,38,59,232,60,45,59,83,197,51,59,164,108,58,59,218,50,65,59,243,23,72,59,239,27,79,59,204,62,86,59,138,128,93,59,38,225,100,59,161,96,108,59,249,254,115,59,45,188,123,59,29,204,129,59,145,201,133,59,113,214,137,59,188,242,141,59,113,30,146,59,145,89,150,59,26,164,154,59,12,254,158,59,102,103,163,59,40,224,167,59,80,104,172,59,222,255,176,59,209,166,181,59,40,93,186,59,228,34,191,59,2,248,195,59,131,220,200,59,101,208,205,59,168,211,210,59,74,230,215,59,76,8,221,59,172,57,226,59,105,122,231,59,131,202,236,59,249,41,242,59,202,152,247,59,245,22,253,59,60,82,1,60,170,32,4,60,196,246,6,60,137,212,9,60,249,185,12,60,19,167,15,60,216,155,18,60,69,152,21,60,92,156,24,60,26,168,27,60,129,187,30,60,143,214,33,60,69,249,36,60,160,35,40,60,162,85,43,60,73,143,46,60,149,208,49,60,133,25,53,60,26,106,56,60,81,194,59,60,44,34,63,60,168,137,66,60,199,248,69,60,134,111,73,60,230,237,76,60,231,115,80,60,134,1,84,60,197,150,87,60,162,51,91,60,28,216,94,60,52,132,98,60,232,55,102,60,56,243,105,60,35,182,109,60,170,128,113,60,202,82,117,60,131,44,121,60,214,13,125,60,96,123,128,60,161,115,130,60,174,111,132,60,134,111,134,60,40,115,136,60,149,122,138,60,205,133,140,60,206,148,142,60,152,167,144,60,44,190,146,60,136,216,148,60,173,246,150,60,154,24,153,60,78,62,155,60,202,103,157,60,13,149,159,60,23,198,161,60,231,250,163,60,125,51,166,60,217,111,168,60,249,175,170,60,223,243,172,60,137,59,175,60,247,134,177,60,40,214,179,60,29,41,182,60,213,127,184,60,80,218,186,60,140,56,189,60,138,154,191,60,74,0,194,60,202,105,196,60,11,215,198,60,12,72,201,60,205,188,203,60,77,53,206,60,140,177,208,60,137,49,211,60,69,181,213,60,189,60,216,60,243,199,218,60,230,86,221,60,149,233,223,60,0,128,226,60,39,26,229,60,8,184,231,60,164,89,234,60,250,254,236,60,9,168,239,60,210,84,242,60,83,5,245,60,141,185,247,60,126,113,250,60,39,45,253,60,134,236,255,60,206,87,1,61,52,187,2,61,117,32,4,61,144,135,5,61,133,240,6,61,84,91,8,61,253,199,9,61,128,54,11,61,219,166,12,61,16,25,14,61,29,141,15,61,3,3,17,61,193,122,18,61,87,244,19,61,197,111,21,61,10,237,22,61,39,108,24,61,26,237,25,61,228,111,27,61,132,244,28,61,251,122,30,61,71,3,32,61,105,141,33,61,96,25,35,61,45,167,36,61,206,54,38,61,67,200,39,61,141,91,41,61,171,240,42,61,156,135,44,61,96,32,46,61,248,186,47,61,99,87,49,61,160,245,50,61,175,149,52,61,144,55,54,61,67,219,55,61,199,128,57,61,28,40,59,61,65,209,60,61,56,124,62,61,254,40,64,61,148,215,65,61,250,135,67,61,47,58,69,61,51,238,70,61,5,164,72,61,166,91,74,61,20,21,76,61,80,208,77,61,90,141,79,61,49,76,81,61,212,12,83,61,68,207,84,61,128,147,86,61,135,89,88,61,90,33,90,61,248,234,91,61,97,182,93,61,148,131,95,61,145,82,97,61,88,35,99,61,232,245,100,61,65,202,102,61,100,160,104,61,78,120,106,61,1,82,108,61,123,45,110,61,188,10,112,61,197,233,113,61,148,202,115,61,41,173,117,61,133,145,119,61,166,119,121,61,140,95,123,61,55,73,125,61,166,52,127,61,237,144,128,61,105,136,129,61,198,128,130,61,5,122,131,61,37,116,132,61,39,111,133,61,9,107,134,61,204,103,135,61,112,101,136,61,244,99,137,61,88,99,138,61,157,99,139,61,193,100,140,61,196,102,141,61,167,105,142,61,106,109,143,61,11,114,144,61,139,119,145,61,234,125,146,61,40,133,147,61,67,141,148,61,61,150,149,61,20,160,150,61,201,170,151,61,92,182,152,61,203,194,153,61,24,208,154,61,66,222,155,61,72,237,156,61,42,253,157,61,233,13,159,61,132,31,160,61,250,49,161,61,76,69,162,61,122,89,163,61,130,110,164,61,101,132,165,61,35,155,166,61,188,178,167,61,47,203,168,61,124,228,169,61,162,254,170,61,163,25,172,61,124,53,173,61,47,82,174,61,187,111,175,61,31,142,176,61,92,173,177,61,113,205,178,61,94,238,179,61,35,16,181,61,192,50,182,61,52,86,183,61,127,122,184,61,160,159,185,61,153,197,186,61,104,236,187,61,13,20,189,61,136,60,190,61,217,101,191,61,255,143,192,61,250,186,193,61,202,230,194,61,111,19,196,61,233,64,197,61,55,111,198,61,89,158,199,61,78,206,200,61,23,255,201,61,179,48,203,61,35,99,204,61,101,150,205,61,121,202,206,61,96,255,207,61,25,53,209,61,164,107,210,61,0,163,211,61,45,219,212,61,44,20,214,61,251,77,215,61,154,136,216,61,10,196,217,61,74,0,219,61,89,61,220,61,56,123,221,61,230,185,222,61,99,249,223,61,174,57,225,61,200,122,226,61,176,188,227,61,102,255,228,61,233,66,230,61,58,135,231,61,88,204,232,61,66,18,234,61,249,88,235,61,124,160,236,61,203,232,237,61,230,49,239,61,204,123,240,61,125,198,241,61,249,17,243,61,63,94,244,61,79,171,245,61,42,249,246,61,206,71,248,61,60,151,249,61,114,231,250,61,114,56,252,61,58,138,253,61,202,220,254,61,17,24,0,62,33,194,0,62,149,108,1,62,108,23,2,62,166,194,2,62,68,110,3,62,69,26,4,62,168,198,4,62,111,115,5,62,152,32,6,62,35,206,6,62,17,124,7,62,98,42,8,62,20,217,8,62,40,136,9,62,157,55,10,62,117,231,10,62,173,151,11,62,71,72,12,62,66,249,12,62,158,170,13,62,91,92,14,62,120,14,15,62,246,192,15,62,213,115,16,62,19,39,17,62,177,218,17,62,175,142,18,62,13,67,19,62,202,247,19,62,231,172,20,62,99,98,21,62,62,24,22,62,120,206,22,62,16,133,23,62,7,60,24,62,92,243,24,62,16,171,25,62,33,99,26,62,145,27,27,62,94,212,27,62,137,141,28,62,17,71,29,62,246,0,30,62,56,187,30,62,215,117,31,62,211,48,32,62,43,236,32,62,224,167,33,62,241,99,34,62,93,32,35,62],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE);allocate([38,221,35,62,74,154,36,62,202,87,37,62,165,21,38,62,219,211,38,62,108,146,39,62,88,81,40,62,159,16,41,62,64,208,41,62,59,144,42,62,144,80,43,62,63,17,44,62,72,210,44,62,170,147,45,62,102,85,46,62,122,23,47,62,232,217,47,62,175,156,48,62,206,95,49,62,69,35,50,62,21,231,50,62,61,171,51,62,189,111,52,62,148,52,53,62,195,249,53,62,73,191,54,62,38,133,55,62,91,75,56,62,230,17,57,62,199,216,57,62,255,159,58,62,141,103,59,62,113,47,60,62,171,247,60,62,59,192,61,62,31,137,62,62,89,82,63,62,232,27,64,62,204,229,64,62,5,176,65,62,146,122,66,62,115,69,67,62,168,16,68,62,49,220,68,62,14,168,69,62,62,116,70,62,194,64,71,62,152,13,72,62,193,218,72,62,61,168,73,62,12,118,74,62,44,68,75,62,159,18,76,62,100,225,76,62,122,176,77,62,225,127,78,62,154,79,79,62,164,31,80,62,255,239,80,62,170,192,81,62,166,145,82,62,242,98,83,62,141,52,84,62,121,6,85,62,180,216,85,62,63,171,86,62,25,126,87,62,65,81,88,62,185,36,89,62,126,248,89,62,147,204,90,62,245,160,91,62,165,117,92,62,163,74,93,62,238,31,94,62,135,245,94,62,109,203,95,62,159,161,96,62,30,120,97,62,233,78,98,62,1,38,99,62,100,253,99,62,19,213,100,62,14,173,101,62,84,133,102,62,229,93,103,62,193,54,104,62,231,15,105,62,88,233,105,62,19,195,106,62,24,157,107,62,103,119,108,62,255,81,109,62,224,44,110,62,11,8,111,62,126,227,111,62,58,191,112,62,62,155,113,62,139,119,114,62,31,84,115,62,251,48,116,62,31,14,117,62,138,235,117,62,59,201,118,62,52,167,119,62,115,133,120,62,248,99,121,62,196,66,122,62,213,33,123,62,44,1,124,62,200,224,124,62,170,192,125,62,208,160,126,62,59,129,127,62,245,48,128,62,111,161,128,62,11,18,129,62,201,130,129,62,168,243,129,62,169,100,130,62,204,213,130,62,15,71,131,62,117,184,131,62,251,41,132,62,162,155,132,62,107,13,133,62,84,127,133,62,93,241,133,62,136,99,134,62,210,213,134,62,61,72,135,62,200,186,135,62,116,45,136,62,63,160,136,62,42,19,137,62,52,134,137,62,94,249,137,62,168,108,138,62,17,224,138,62,153,83,139,62,64,199,139,62,6,59,140,62,235,174,140,62,239,34,141,62,17,151,141,62,82,11,142,62,177,127,142,62,46,244,142,62,201,104,143,62,130,221,143,62,89,82,144,62,78,199,144,62,96,60,145,62,143,177,145,62,220,38,146,62,70,156,146,62,205,17,147,62,113,135,147,62,50,253,147,62,16,115,148,62,9,233,148,62,32,95,149,62,82,213,149,62,161,75,150,62,12,194,150,62,146,56,151,62,53,175,151,62,243,37,152,62,204,156,152,62,193,19,153,62,209,138,153,62,252,1,154,62,66,121,154,62,163,240,154,62,31,104,155,62,181,223,155,62,101,87,156,62,48,207,156,62,21,71,157,62,20,191,157,62,45,55,158,62,96,175,158,62,172,39,159,62,18,160,159,62,145,24,160,62,41,145,160,62,218,9,161,62,165,130,161,62,136,251,161,62,132,116,162,62,152,237,162,62,197,102,163,62,10,224,163,62,103,89,164,62,220,210,164,62,105,76,165,62,14,198,165,62,202,63,166,62,158,185,166,62,137,51,167,62,139,173,167,62,164,39,168,62,213,161,168,62,27,28,169,62,121,150,169,62,237,16,170,62,119,139,170,62,24,6,171,62,206,128,171,62,155,251,171,62,125,118,172,62,117,241,172,62,130,108,173,62,165,231,173,62,221,98,174,62,42,222,174,62,140,89,175,62,2,213,175,62,142,80,176,62,46,204,176,62,226,71,177,62,170,195,177,62,135,63,178,62,119,187,178,62,124,55,179,62,148,179,179,62,191,47,180,62,254,171,180,62,80,40,181,62,181,164,181,62,45,33,182,62,184,157,182,62,85,26,183,62,5,151,183,62,199,19,184,62,156,144,184,62,130,13,185,62,123,138,185,62,133,7,186,62,161,132,186,62,206,1,187,62,13,127,187,62,93,252,187,62,190,121,188,62,48,247,188,62,178,116,189,62,70,242,189,62,233,111,190,62,157,237,190,62,98,107,191,62,54,233,191,62,26,103,192,62,14,229,192,62,17,99,193,62,36,225,193,62,70,95,194,62,119,221,194,62,184,91,195,62,7,218,195,62,100,88,196,62,209,214,196,62,75,85,197,62,212,211,197,62,107,82,198,62,16,209,198,62,195,79,199,62,132,206,199,62,82,77,200,62,45,204,200,62,21,75,201,62,11,202,201,62,13,73,202,62,29,200,202,62,56,71,203,62,97,198,203,62,149,69,204,62,214,196,204,62,34,68,205,62,123,195,205,62,223,66,206,62,79,194,206,62,202,65,207,62,81,193,207,62,226,64,208,62,127,192,208,62,38,64,209,62,216,191,209,62,148,63,210,62,91,191,210,62,44,63,211,62,7,191,211,62,235,62,212,62,218,190,212,62,210,62,213,62,211,190,213,62,222,62,214,62,242,190,214,62,15,63,215,62,53,191,215,62,99,63,216,62,154,191,216,62,217,63,217,62,32,192,217,62,112,64,218,62,199,192,218,62,38,65,219,62,140,193,219,62,250,65,220,62,112,194,220,62,236,66,221,62,112,195,221,62,250,67,222,62,139,196,222,62,34,69,223,62,192,197,223,62,100,70,224,62,14,199,224,62,189,71,225,62,115,200,225,62,46,73,226,62,239,201,226,62,181,74,227,62,127,203,227,62,79,76,228,62,36,205,228,62,253,77,229,62,219,206,229,62,190,79,230,62,164,208,230,62,142,81,231,62,125,210,231,62,111,83,232,62,100,212,232,62,93,85,233,62,89,214,233,62,89,87,234,62,91,216,234,62,96,89,235,62,104,218,235,62,114,91,236,62,126,220,236,62,141,93,237,62,158,222,237,62,176,95,238,62,196,224,238,62,218,97,239,62,241,226,239,62,10,100,240,62,35,229,240,62,62,102,241,62,89,231,241,62,116,104,242,62,145,233,242,62,173,106,243,62,202,235,243,62,230,108,244,62,3,238,244,62,31,111,245,62,59,240,245,62,86,113,246,62,112,242,246,62,137,115,247,62,161,244,247,62,184,117,248,62,206,246,248,62,226,119,249,62,244,248,249,62,4,122,250,62,18,251,250,62,30,124,251,62,40,253,251,62,47,126,252,62,52,255,252,62,54,128,253,62,52,1,254,62,48,130,254,62,40,3,255,62,29,132,255,62,135,2,0,63,254,66,0,63,115,131,0,63,230,195,0,63,86,4,1,63,197,68,1,63,49,133,1,63,155,197,1,63,3,6,2,63,103,70,2,63,202,134,2,63,42,199,2,63,135,7,3,63,225,71,3,63,56,136,3,63,141,200,3,63,222,8,4,63,44,73,4,63,119,137,4,63,191,201,4,63,3,10,5,63,68,74,5,63,130,138,5,63,188,202,5,63,242,10,6,63,36,75,6,63,83,139,6,63,126,203,6,63,165,11,7,63,199,75,7,63,230,139,7,63,1,204,7,63,23,12,8,63,41,76,8,63,54,140,8,63,63,204,8,63,67,12,9,63,67,76,9,63,62,140,9,63,52,204,9,63,37,12,10,63,18,76,10,63,249,139,10,63,219,203,10,63,184,11,11,63,144,75,11,63,98,139,11,63,47,203,11,63,246,10,12,63,184,74,12,63,116,138,12,63,43,202,12,63,219,9,13,63,134,73,13,63,43,137,13,63,202,200,13,63,98,8,14,63,245,71,14,63,129,135,14,63,7,199,14,63,135,6,15,63,0,70,15,63,114,133,15,63,222,196,15,63,67,4,16,63,161,67,16,63,249,130,16,63,73,194,16,63,147,1,17,63,213,64,17,63,17,128,17,63,69,191,17,63,114,254,17,63,151,61,18,63,181,124,18,63,203,187,18,63,218,250,18,63,225,57,19,63,225,120,19,63,216,183,19,63,200,246,19,63,176,53,20,63,143,116,20,63,103,179,20,63,54,242,20,63,253,48,21,63,188,111,21,63,114,174,21,63,32,237,21,63,197,43,22,63,98,106,22,63,246,168,22,63,129,231,22,63,3,38,23,63,125,100,23,63,237,162,23,63,84,225,23,63,178,31,24,63,7,94,24,63,83,156,24,63,149,218,24,63,206,24,25,63,253,86,25,63,35,149,25,63,63,211,25,63,82,17,26,63,90,79,26,63,89,141,26,63,78,203,26,63,57,9,27,63,25,71,27,63,240,132,27,63,188,194,27,63,126,0,28,63,54,62,28,63,227,123,28,63,134,185,28,63,30,247,28,63,172,52,29,63,47,114,29,63,167,175,29,63,20,237,29,63,118,42,30,63,206,103,30,63,26,165,30,63,91,226,30,63,145,31,31,63,188,92,31,63,219,153,31,63,239,214,31,63,247,19,32,63,244,80,32,63,230,141,32,63,203,202,32,63,165,7,33,63,115,68,33,63,53,129,33,63,235,189,33,63,150,250,33,63,52,55,34,63,198,115,34,63,75,176,34,63,197,236,34,63,50,41,35,63,146,101,35,63,230,161,35,63,46,222,35,63,105,26,36,63,151,86,36,63,185,146,36,63,205,206,36,63,213,10,37,63,208,70,37,63,190,130,37,63,158,190,37,63,114,250,37,63,56,54,38,63,241,113,38,63,157,173,38,63,59,233,38,63,204,36,39,63,79,96,39,63,197,155,39,63,45,215,39,63,135,18,40,63,211,77,40,63,18,137,40,63,66,196,40,63,101,255,40,63,121,58,41,63,128,117,41,63,120,176,41,63,98,235,41,63,62,38,42,63,11,97,42,63,202,155,42,63,122,214,42,63,28,17,43,63,175,75,43,63,52,134,43,63,170,192,43,63,16,251,43,63,105,53,44,63,178,111,44,63,236,169,44,63,23,228,44,63,51,30,45,63,64,88,45,63,61,146,45,63,43,204,45,63,10,6,46,63,218,63,46,63,154,121,46,63,74,179,46,63,235,236,46,63,124,38,47,63,254,95,47,63,112,153,47,63,210,210,47,63,36,12,48,63,102,69,48,63,152,126,48,63,186,183,48,63,204,240,48,63,205,41,49,63,191,98,49,63,160,155,49,63,113,212,49,63,49,13,50,63,225,69,50,63,128,126,50,63,15,183,50,63,141,239,50,63,251,39,51,63,87,96,51,63,163,152,51,63,222,208,51,63,8,9,52,63,34,65,52,63,42,121,52,63,33,177,52,63,7,233,52,63,219,32,53,63,159,88,53,63,81,144,53,63,242,199,53,63,129,255,53,63,255,54,54,63,108,110,54,63,198,165,54,63,16,221,54,63,71,20,55,63,109,75,55,63,129,130,55,63,131,185,55,63,116,240,55,63,82,39,56,63,30,94,56,63,217,148,56,63,129,203,56,63,23,2,57,63,155,56,57,63,13,111,57,63,108,165,57,63,185,219,57,63,244,17,58,63,28,72,58,63,50,126,58,63,53,180,58,63,38,234,58,63,4,32,59,63,207,85,59,63,135,139,59,63,45,193,59,63,192,246,59,63,64,44,60,63,173,97,60,63,7,151,60,63,78,204,60,63,130,1,61,63,163,54,61,63,177,107,61,63,171,160,61,63,146,213,61,63,102,10,62,63,39,63,62,63,212,115,62,63,110,168,62,63,244,220,62,63,103,17,63,63,198,69,63,63,17,122,63,63,73,174,63,63,109,226,63,63,126,22,64,63,122,74,64,63,99,126,64,63,56,178,64,63,248,229,64,63,165,25,65,63,62,77,65,63,195,128,65,63,52,180,65,63,144,231,65,63,216,26,66,63,13,78,66,63,44,129,66,63,56,180,66,63,47,231,66,63,18,26,67,63,224,76,67,63,154,127,67,63,64,178,67,63,208,228,67,63,77,23,68,63,180,73,68,63,7,124,68,63,69,174,68,63,111,224,68,63,131,18,69,63,131,68,69,63,110,118,69,63,68,168,69,63,5,218,69,63,177,11,70,63,72,61,70,63,202,110,70,63,55,160,70,63,143,209,70,63,210,2,71,63,255,51,71,63,23,101,71,63,26,150,71,63,8,199,71,63,224,247,71,63,163,40,72,63,81,89,72,63,233,137,72,63,107,186,72,63,216,234,72,63,48,27,73,63,114,75,73,63,158,123,73,63,181,171,73,63,181,219,73,63,161,11,74,63,118,59,74,63,54,107,74,63,224,154,74,63,116,202,74,63,242,249,74,63,90,41,75,63,173,88,75,63,233,135,75,63,15,183,75,63,32,230,75,63,26,21,76,63,254,67,76,63,204,114,76,63,132,161,76,63,38,208,76,63,177,254,76,63,38,45,77,63,133,91,77,63,206,137,77,63,0,184,77,63,28,230,77,63,34,20,78,63,17,66,78,63,234,111,78,63,172,157,78,63,88,203,78,63,238,248,78,63,108,38,79,63,213,83,79,63,38,129,79,63,97,174,79,63,134,219,79,63,147,8,80,63,138,53,80,63,107,98,80,63,52,143,80,63,231,187,80,63,131,232,80,63,8,21,81,63,119,65,81,63,206,109,81,63,15,154,81,63,57,198,81,63,76,242,81,63,71,30,82,63,44,74,82,63,250,117,82,63,177,161,82,63,81,205,82,63,218,248,82,63,76,36,83,63,166,79,83,63,234,122,83,63,22,166,83,63,44,209,83,63,42,252,83,63,17,39,84,63,224,81,84,63,153,124,84,63,58,167,84,63,196,209,84,63,54,252,84,63,146,38,85,63,214,80,85,63,2,123,85,63,24,165,85,63,22,207,85,63,252,248,85,63,204,34,86,63,131,76,86,63,36,118,86,63,172,159,86,63,30,201,86,63,120,242,86,63,186,27,87,63,229,68,87,63,248,109,87,63,244,150,87,63,216,191,87,63,165,232,87,63,90,17,88,63,248,57,88,63,126,98,88,63,236,138,88,63,67,179,88,63,130,219,88,63,169,3,89,63,185,43,89,63,177,83,89,63,145,123,89,63,90,163,89,63,11,203,89,63,164,242,89,63,37,26,90,63,143,65,90,63,225,104,90,63,27,144,90,63,62,183,90,63,72,222,90,63,59,5,91,63,22,44,91,63,217,82,91,63,133,121,91,63,24,160,91,63,148,198,91,63,248,236,91,63,68,19,92,63,120,57,92,63,149,95,92,63,153,133,92,63,134,171,92,63,91,209,92,63,24,247,92,63,189,28,93,63,74,66,93,63,191,103,93,63,28,141,93,63,98,178,93,63,143,215,93,63,165,252,93,63,162,33,94,63,136,70,94,63,86,107,94,63,11,144,94,63,169,180,94,63,47,217,94,63,157,253,94,63,243,33,95,63,49,70,95,63,88,106,95,63,102,142,95,63,92,178,95,63,59,214,95,63,1,250,95,63,175,29,96,63,70,65,96,63,196,100,96,63,43,136,96,63,122,171,96,63,176,206,96,63,207,241,96,63,214,20,97,63,197,55,97,63,155,90,97,63,90,125,97,63,1,160,97,63,144,194,97,63,8,229,97,63,103,7,98,63,174,41,98,63,221,75,98,63,245,109,98,63,244,143,98,63,220,177,98,63,171,211,98,63,99,245,98,63,3,23,99,63,139,56,99,63,251,89,99,63,83,123,99,63,147,156,99,63,188,189,99,63,204,222,99,63,197,255,99,63,166,32,100,63,110,65,100,63,32,98,100,63,185,130,100,63,58,163,100,63,164,195,100,63,245,227,100,63,47,4,101,63,82,36,101,63,92,68,101,63,78,100,101,63,41,132,101,63,236,163,101,63,151,195,101,63,43,227,101,63,167,2,102,63,11,34,102,63,87,65,102,63,139,96,102,63,168,127,102,63,174,158,102,63,155,189,102,63,113,220,102,63,47,251,102,63,214,25,103,63,101,56,103,63,220,86,103,63,59,117,103,63,132,147,103,63,180,177,103,63,205,207,103,63,206,237,103,63,184,11,104,63,138,41,104,63,69,71,104,63,233,100,104,63,116,130,104,63,233,159,104,63,69,189,104,63,139,218,104,63,185,247,104,63,207,20,105,63,207,49,105,63,182,78,105,63,135,107,105,63,64,136,105,63,225,164,105,63,108,193,105,63,223,221,105,63,59,250,105,63,127,22,106,63,172,50,106,63,195,78,106,63,193,106,106,63,169,134,106,63,121,162,106,63,51,190,106,63,213,217,106,63,96,245,106,63,212,16,107,63,48,44,107,63,118,71,107,63,165,98,107,63,188,125,107,63,189,152,107,63,167,179,107,63,121,206,107,63,53,233,107,63,218,3,108,63,104,30,108,63,223,56,108,63,63,83,108,63,136,109,108,63,187,135,108,63,214,161,108,63,219,187,108,63,201,213,108,63,161,239,108,63,97,9,109,63,11,35,109,63,159,60,109,63,27,86,109,63,129,111,109,63,209,136,109,63,9,162,109,63,44,187,109,63,56,212,109,63,45,237,109,63,12,6,110,63,212,30,110,63,134,55,110,63,33,80,110,63,166,104,110,63,21,129,110,63,110,153,110,63,176,177,110,63,220,201,110,63,241,225,110,63,241,249,110,63,218,17,111,63,173,41,111,63,106,65,111,63,16,89,111,63,161,112,111,63,28,136,111,63,128,159,111,63,207,182,111,63,7,206,111,63,42,229,111,63,54,252,111,63,45,19,112,63,14,42,112,63,217,64,112,63,142,87,112,63,46,110,112,63,184,132,112,63,43,155,112,63,138,177,112,63,210,199,112,63,5,222,112,63,35,244,112,63,42,10,113,63,29,32,113,63,249,53,113,63,193,75,113,63,114,97,113,63,15,119,113,63,150,140,113,63,7,162,113,63,99,183,113,63,170,204,113,63,220,225,113,63,249,246,113,63,0,12,114,63,242,32,114,63,207,53,114,63,151,74,114,63,73,95,114,63,231,115,114,63,112,136,114,63,227,156,114,63,66,177,114,63,140,197,114,63,193,217,114,63,225,237,114,63,236,1,115,63,227,21,115,63,197,41,115,63,146,61,115,63,74,81,115,63,238,100,115,63,125,120,115,63,248,139,115,63,94,159,115,63,175,178,115,63,236,197,115,63,21,217,115,63,41,236,115,63,41,255,115,63,21,18,116,63,236,36,116,63,175,55,116,63,94,74,116,63,248,92,116,63,127,111,116,63,241,129,116,63,80,148,116,63,154,166,116,63,208,184,116,63,242,202,116,63,1,221,116,63,251,238,116,63,226,0,117,63,181,18,117,63,116,36,117,63,31,54,117,63,183,71,117,63,59,89,117,63,171,106,117,63,8,124,117,63,81,141,117,63,135,158,117,63,169,175,117,63,184,192,117,63,179,209,117,63,155,226,117,63,112,243,117,63,50,4,118,63,224,20,118,63,123,37,118,63,3,54,118,63,120,70,118,63,217,86,118,63,40,103,118,63,100,119,118,63,140,135,118,63,162,151,118,63,165,167,118,63,149,183,118,63,114,199,118,63,61,215,118,63,245,230,118,63,154,246,118,63,44,6,119,63,172,21,119,63,26,37,119,63,117,52,119,63,189,67,119,63,243,82,119,63,22,98,119,63,40,113,119,63,39,128,119,63,19,143,119,63,238,157,119,63,182,172,119,63,108,187,119,63,16,202,119,63,162,216,119,63,34,231,119,63,144,245,119,63,236,3,120,63,55,18,120,63,111,32,120,63,150,46,120,63,170,60,120,63,174,74,120,63,159,88,120,63,127,102,120,63,77,116,120,63,10,130,120,63,181,143,120,63,79,157,120,63,215,170,120,63,78,184,120,63,180,197,120,63,8,211,120,63,76,224,120,63,126,237,120,63,158,250,120,63,174,7,121,63,173,20,121,63,155,33,121,63,119,46,121,63,67,59,121,63,254,71,121,63,168,84,121,63,66,97,121,63,202,109,121,63,66,122,121,63,169,134,121,63,0,147,121,63,70,159,121,63,124,171,121,63,161,183,121,63,181,195,121,63,186,207,121,63,173,219,121,63,145,231,121,63,100,243,121,63,40,255,121,63,219,10,122,63,126,22,122,63,16,34,122,63,147,45,122,63,6,57,122,63,105,68,122,63,188,79,122,63,255,90,122,63,51,102,122,63,86,113,122,63,106,124,122,63,111,135,122,63,99,146,122,63,72,157,122,63,30,168,122,63,228,178,122,63,155,189,122,63,66,200,122,63,218,210,122,63,99,221,122,63,221,231,122,63,71,242,122,63,162,252,122,63,238,6,123,63,43,17,123,63,89,27,123,63,120,37,123,63,137,47,123,63,138,57,123,63,124,67,123,63,96,77,123,63,53,87,123,63,252,96,123,63,179,106,123,63,92,116,123,63,247,125,123,63,131,135,123,63,1,145,123,63,112,154,123,63,209,163,123,63,36,173,123,63,104,182,123,63,158,191,123,63,198,200,123,63,224,209,123,63,236,218,123,63,234,227,123,63,218,236,123,63,188,245,123,63,144,254,123,63,86,7,124,63,14,16,124,63,185,24,124,63,86,33,124,63,230,41,124,63,104,50,124,63,220,58,124,63,67,67,124,63,156,75,124,63,232,83,124,63,39,92,124,63,88,100,124,63,124,108,124,63,147,116,124,63,157,124,124,63,153,132,124,63,137,140,124,63,107,148,124,63,65,156,124,63,9,164,124,63,197,171,124,63,116,179,124,63,22,187,124,63,172,194,124,63,52,202,124,63,176,209,124,63,32,217,124,63,131,224,124,63,217,231,124,63,35,239,124,63,97,246,124,63,146,253,124,63,183,4,125,63,208,11,125,63,221,18,125,63,221,25,125,63,209,32,125,63,185,39,125,63,150,46,125,63,102,53,125,63,42,60,125,63,227,66,125,63,143,73,125,63,48,80,125,63,197,86,125,63,78,93,125,63,204,99,125,63,62,106,125,63,165,112,125,63,0,119,125,63,80,125,125,63,148,131,125,63,205,137,125,63,251,143,125,63,29,150,125,63,52,156,125,63,64,162,125,63,65,168,125,63,55,174,125,63,34,180,125,63,2,186,125,63,215,191,125,63,161,197,125,63,96,203,125,63,21,209,125,63,190,214,125,63,93,220,125,63,242,225,125,63,124,231,125,63,251,236,125,63,112,242,125,63,218,247,125,63,58,253,125,63,143,2,126,63,219,7,126,63,28,13,126,63,82,18,126,63,127,23,126,63,161,28,126,63,186,33,126,63,200,38,126,63,204,43,126,63,199,48,126,63,183,53,126,63,158,58,126,63,123,63,126,63,78,68,126,63,23,73,126,63,215,77,126,63,141,82,126,63,58,87,126,63,221,91,126,63,118,96,126,63,6,101,126,63,141,105,126,63,10,110,126,63,126,114,126,63,233,118,126,63,75,123,126,63,164,127,126,63,243,131,126,63,57,136,126,63,119,140,126,63,171,144,126,63,214,148,126,63,249,152,126,63,18,157,126,63,35,161,126,63,44,165,126,63,43,169,126,63,34,173,126,63,16,177,126,63,246,180,126,63,211,184,126,63,167,188,126,63,115,192,126,63,55,196,126,63,243,199,126,63,166,203,126,63,81,207,126,63,243,210,126,63,142,214,126,63,32,218,126,63,171,221,126,63,45,225,126,63,167,228,126,63,26,232,126,63,132,235,126,63,231,238,126,63,66,242,126,63,149,245,126,63,224,248,126,63,36,252,126,63,96,255,126,63,148,2,127,63,193,5,127,63,230,8,127,63,4,12,127,63,27,15,127,63,42,18,127,63,50,21,127,63,50,24,127,63,43,27,127,63,29,30,127,63,8,33,127,63,236,35,127,63,201,38,127,63,158,41,127,63,109,44,127,63,53,47,127,63,246,49,127,63,175,52,127,63,99,55,127,63,15,58,127,63,181,60,127,63,83,63,127,63,236,65,127,63,125,68,127,63,8,71,127,63,141,73,127,63,11,76,127,63,131,78,127,63,244,80,127,63,95,83,127,63,195,85,127,63,33,88,127,63,121,90,127,63,203,92,127,63,23,95,127,63,92,97,127,63,155,99,127,63,213,101,127,63,8,104,127,63,54,106,127,63,93,108,127,63,127,110,127,63,155,112,127,63,177,114,127,63,193,116,127,63,203,118,127,63,208,120,127,63,207,122,127,63,201,124,127,63,189,126,127,63,171,128,127,63,148,130,127,63,120,132,127,63,86,134,127,63,47,136,127,63,2,138,127,63,209,139,127,63,153,141,127,63,93,143,127,63,28,145,127,63,213,146,127,63,137,148,127,63,57,150,127,63,227,151,127,63,136,153,127,63,40,155,127,63,196,156,127,63,90,158,127,63,236,159,127,63,121,161,127,63,1,163,127,63,132,164,127,63,3,166,127,63,125,167,127,63,242,168,127,63,99,170,127,63,207,171,127,63,55,173,127,63,154,174,127,63,249,175,127,63,84,177,127,63,170,178,127,63,251,179,127,63,73,181,127,63,146,182,127,63,215,183,127,63,24,185,127,63,85,186,127,63,141,187,127,63,193,188,127,63,242,189,127,63,30,191,127,63,71,192,127,63,107,193,127,63,140,194,127,63,168,195,127,63,193,196,127,63,214,197,127,63,231,198,127,63,245,199,127,63,255,200,127,63,5,202,127,63,7,203,127,63,6,204,127,63,1,205,127,63,249,205,127,63,237,206,127,63,222,207,127,63,203,208,127,63,181,209,127,63,156,210,127,63,127,211,127,63,95,212,127,63,59,213,127,63,20,214,127,63,234,214,127,63,189,215,127,63,141,216,127,63,90,217,127,63,35,218,127,63,233,218,127,63,173,219,127,63,109,220,127,63,43,221,127,63,229,221,127,63,156,222,127,63,81,223,127,63,3,224,127,63,178,224,127,63,94,225,127,63,7,226,127,63,174,226,127,63,82,227,127,63,243,227,127,63,146,228,127,63,46,229,127,63,199,229,127,63,94,230,127,63,242,230,127,63,132,231,127,63,19,232,127,63,160,232,127,63,42,233,127,63,178,233,127,63,56,234,127,63,187,234,127,63,60,235,127,63,187,235,127,63,55,236,127,63,177,236,127,63,41,237,127,63,159,237,127,63,18,238,127,63,132,238,127,63,243,238,127,63,96,239,127,63,204,239,127,63,53,240,127,63,156,240,127,63,1,241,127,63,101,241,127,63,198,241,127,63,37,242,127,63,131,242,127,63,222,242,127,63,56,243,127,63,144,243,127,63,231,243,127,63,59,244,127,63,142,244,127,63,223,244,127,63,46,245,127,63,124,245,127,63,200,245,127,63,19,246,127,63,91,246,127,63,163,246,127,63,233,246,127,63,45,247,127,63,111,247,127,63,177,247,127,63,240,247,127,63,47,248,127,63,108,248,127,63,167,248,127,63,225,248,127,63,26,249,127,63,82,249,127,63,136,249,127,63,188,249,127,63,240,249,127,63,34,250,127,63,83,250,127,63,131,250,127,63,178,250,127,63,224,250,127,63,12,251,127,63,55,251,127,63,97,251,127,63,138,251,127,63,178,251,127,63,217,251,127,63,255,251,127,63,36,252,127,63,72,252,127,63,107,252,127,63,141,252,127,63,173,252,127,63,205,252,127,63,237,252,127,63,11,253,127,63,40,253,127,63,69,253,127,63,96,253,127,63,123,253,127,63,149,253,127,63,174,253,127,63,199,253,127,63,222,253,127,63,245,253,127,63,12,254,127,63,33,254,127,63,54,254,127,63,74,254,127,63,93,254,127,63,112,254,127,63,130,254,127,63,148,254,127,63,165,254,127,63,181,254,127,63,197,254,127,63,212,254,127,63,227,254,127,63,241,254,127,63,254,254,127,63,11,255,127,63,24,255,127,63,36,255,127,63,47,255,127,63,59,255,127,63,69,255,127,63,79,255,127,63,89,255,127,63,99,255,127,63,108,255,127,63,116,255,127,63,124,255,127,63,132,255,127,63,140,255,127,63,147,255,127,63,154,255,127,63,160,255,127,63,166,255,127,63,172,255,127,63,178,255,127,63,183,255,127,63,188,255,127,63,193,255,127,63,197,255,127,63,202,255,127,63,206,255,127,63,209,255,127,63,213,255,127,63,216,255,127,63,220,255,127,63,223,255,127,63,225,255,127,63,228,255,127,63,230,255,127,63,233,255,127,63,235,255,127,63,237,255,127,63,239,255,127,63,240,255,127,63,242,255,127,63,243,255,127,63,245,255,127,63,246,255,127,63,247,255,127,63,248,255,127,63,249,255,127,63,250,255,127,63,251,255,127,63,251,255,127,63,252,255,127,63,252,255,127,63,253,255,127,63,253,255,127,63,254,255,127,63,254,255,127,63,254,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,198,63,120,51,98,136,11,53,151,200,193,53,80,233,61,54,183,247,156,54,46,124,234,54,153,192,35,55,244,2,90,55,56,3,140,55,227,228,174,55,177,166,213,55,108,36,0,56,146,101,23,56,201,150,48,56,18,184,75,56,81,201,104,56,94,229,131,56,29,94,148,56,229,206,165,56,167,55,184,56,128,152,203,56,85,241,223,56,36,66,245,56,126,197,5,57,238,101,17,57,99,130,29,57,207,26,42,57,63,47,55,57,179,191,68,57,30,204,82,57,141,84,97,57,243,88,112,57,94,217,127,57,227,234,135,57,18,39,144,57,64,161,152,57,105,89,161,57,146,79,170,57,181,131,179,57,215,245,188,57,245,165,198,57,14,148,208,57,34,192,218,57,46,42,229,57,57,210,239,57,60,184,250,57,27,238,2,58,22,159,8,58,13,111,14,58,0,94,20,58,239,107,26,58,218,152,32,58,192,228,38,58,161,79,45,58,124,217,51,58,83,130,58,58,37,74,65,58,240,48,72,58,182,54,79,58,116,91,86,58,45,159,93,58,222,1,101,58,136,131,108,58,42,36,116,58,196,227,123,58,44,225,129,58,241,223,133,58,49,238,137,58,238,11,142,58,37,57,146,58,215,117,150,58,5,194,154,58,174,29,159,58,209,136,163,58,110,3,168,58,134,141,172,58,24,39,177,58,36,208,181,58,169,136,186,58,169,80,191,58,33,40,196,58,19,15,201,58,126,5,206,58,98,11,211,58,191,32,216,58,148,69,221,58,225,121,226,58,166,189,231,58,227,16,237,58,152,115,242,58,196,229,247,58,103,103,253,58,65,124,1,59,137,76,4,59,141,36,7,59,76,4,10,59,198,235,12,59,251,218,15,59,235,209,18,59,149,208,21,59,251,214,24,59,26,229,27,59,244,250,30,59,136,24,34,59,215,61,37,59,223,106,40,59,161,159,43,59,29,220,46,59,83,32,50,59,66,108,53,59,234,191,56,59,76,27,60,59,103,126,63,59,59,233,66,59,199,91,70,59,12,214,73,59,10,88,77,59,193,225,80,59,48,115,84,59,86,12,88,59,53,173,91,59,204,85,95,59,26,6,99,59,32,190,102,59,222,125,106,59,82,69,110,59,127,20,114,59,97,235,117,59,251,201,121,59,76,176,125,59,41,207,128,59,8,202,130,59,194,200,132,59,87,203,134,59,198,209,136,59,17,220,138,59,55,234,140,59,55,252,142,59,18,18,145,59,199,43,147,59,87,73,149,59,194,106,151,59,6,144,153,59,37,185,155,59,30,230,157,59,241,22,160,59,158,75,162,59,37,132,164,59,134,192,166,59,192,0,169,59,212,68,171,59,193,140,173,59,137,216,175,59,41,40,178,59,163,123,180,59,245,210,182,59,33,46,185,59,38,141,187,59,4,240,189,59,186,86,192,59,73,193,194,59,177,47,197,59,242,161,199,59,10,24,202,59,251,145,204,59,196,15,207,59,102,145,209,59,223,22,212,59,49,160,214,59,90,45,217,59,91,190,219,59,51,83,222,59,227,235,224,59,107,136,227,59,201,40,230,59,255,204,232,59,12,117,235,59,240,32,238,59,171,208,240,59,61,132,243,59,165,59,246,59,228,246,248,59,250,181,251,59,229,120,254,59,212,159,0,60,32,5,2,60,87,108,3,60,121,213,4,60,134,64,6,60,126,173,7,60,96,28,9,60,45,141,10,60,229,255,11,60,136,116,13,60,21,235,14,60,141,99,16,60,239,221,17,60,59,90,19,60,114,216,20,60,147,88,22,60,158,218,23,60,147,94,25,60,115,228,26,60,60,108,28,60,240,245,29,60,141,129,31,60,20,15,33,60,133,158,34,60,224,47,36,60,36,195,37,60,82,88,39,60,105,239,40,60,106,136,42,60,84,35,44,60,40,192,45,60,229,94,47,60,139,255,48,60,26,162,50,60,146,70,52,60,243,236,53,60,61,149,55,60,112,63,57,60,140,235,58,60,145,153,60,60,126,73,62,60,84,251,63,60,18,175,65,60,185,100,67,60,72,28,69,60,192,213,70,60,31,145,72,60,103,78,74,60,151,13,76,60,175,206,77,60,176,145,79,60,152,86,81,60,103,29,83,60,31,230,84,60,190,176,86,60,69,125,88,60,179,75,90,60,9,28,92,60,71,238,93,60,107,194,95,60,119,152,97,60,106,112,99,60,68,74,101,60,5,38,103,60,173,3,105,60,60,227,106,60,178,196,108,60,14,168,110,60,81,141,112,60,123,116,114,60,139,93,116,60,130,72,118,60,95,53,120,60,34,36,122,60,203,20,124,60,90,7,126,60,208,251,127,60,22,249,128,60,54,245,129,60,74,242,130,60,80,240,131,60,73,239,132,60,53,239,133,60,19,240,134,60,229,241,135,60,169,244,136,60,95,248,137,60,8,253,138,60,164,2,140,60,50,9,141,60,178,16,142,60,37,25,143,60,139,34,144,60,226,44,145,60,44,56,146,60,104,68,147,60,150,81,148,60,182,95,149,60,201,110,150,60,205,126,151,60,196,143,152,60,172,161,153,60,135,180,154,60,83,200,155,60,17,221,156,60,193,242,157,60,98,9,159,60,245,32,160,60,122,57,161,60,241,82,162,60,89,109,163,60,178,136,164,60,253,164,165,60,57,194,166,60,103,224,167,60,134,255,168,60,151,31,170,60,152,64,171,60,139,98,172,60,111,133,173,60,68,169,174,60,10,206,175,60,193,243,176,60,105,26,178,60,2,66,179,60,139,106,180,60,6,148,181,60,113,190,182,60,205,233,183,60,26,22,185,60,87,67,186,60,133,113,187,60,163,160,188,60,177,208,189,60,177,1,191,60,160,51,192,60,128,102,193,60,80,154,194,60,16,207,195,60,193,4,197,60,97,59,198,60,242,114,199,60,114,171,200,60,227,228,201,60,67,31,203,60,147,90,204,60,211,150,205,60,3,212,206,60,34,18,208,60,49,81,209,60,48,145,210,60,30,210,211,60,252,19,213,60,201,86,214,60,133,154,215,60,49,223,216,60,204,36,218,60,86,107,219,60,208,178,220,60,56,251,221,60,144,68,223,60,214,142,224,60,12,218,225,60,48,38,227,60,67,115,228,60,69,193,229,60,54,16,231,60,21,96,232,60,227,176,233,60,160,2,235,60,75,85,236,60,228,168,237,60,108,253,238,60,226,82,240,60,70,169,241,60,153,0,243,60,218,88,244,60,8,178,245,60,37,12,247,60,48,103,248,60,41,195,249,60,15,32,251,60,228,125,252,60,166,220,253,60,85,60,255,60,121,78,0,61,63,255,0,61,123,176,1,61,46,98,2,61,88,20,3,61,248,198,3,61,15,122,4,61,156,45,5,61,161,225,5,61,27,150,6,61,12,75,7,61,116,0,8,61,82,182,8,61,167,108,9,61,113,35,10,61,179,218,10,61,106,146,11,61,152,74,12,61,60,3,13,61,87,188,13,61,231,117,14,61,238,47,15,61,107,234,15,61,94,165,16,61,199,96,17,61,166,28,18,61,251,216,18,61,198,149,19,61,7,83,20,61,190,16,21,61,234,206,21,61,141,141,22,61,165,76,23,61,52,12,24,61,56,204,24,61,177,140,25,61,161,77,26,61,6,15,27,61,224,208,27,61,48,147,28,61,246,85,29,61,49,25,30,61,226,220,30,61,8,161,31,61,164,101,32,61,181,42,33,61,59,240,33,61,55,182,34,61,168,124,35,61,142,67,36,61,233,10,37,61,186,210,37,61,255,154,38,61,186,99,39,61,234,44,40,61,143,246,40,61,168,192,41,61,55,139,42,61,59,86,43,61,180,33,44,61,161,237,44,61,4,186,45,61,219,134,46,61,38,84,47,61,231,33,48,61,28,240,48,61,198,190,49,61,229,141,50,61,120,93,51,61,127,45,52,61,251,253,52,61,236,206,53,61,81,160,54,61,42,114,55,61,120,68,56,61,58,23,57,61,112,234,57,61,27,190,58,61,58,146,59,61,204,102,60,61,211,59,61,61,79,17,62,61,62,231,62,61,161,189,63,61,120,148,64,61,195,107,65,61,130,67,66,61,181,27,67,61,92,244,67,61,118,205,68,61,4,167,69,61,6,129,70,61,124,91,71,61,101,54,72,61,194,17,73,61,146,237,73,61,214,201,74,61,141,166,75,61,184,131,76,61,86,97,77,61,104,63,78,61,236,29,79,61,229,252,79,61,80,220,80,61,46,188,81,61,128,156,82,61,69,125,83,61,125,94,84,61,40,64,85,61,69,34,86,61,214,4,87,61,218,231,87,61,81,203,88,61,58,175,89,61,150,147,90,61,101,120,91,61,167,93,92,61,91,67,93,61,130,41,94,61,28,16,95,61,40,247,95,61,167,222,96,61,152,198,97,61,251,174,98,61,209,151,99,61,25,129,100,61,212,106,101,61,0,85,102,61,159,63,103,61,176,42,104,61,51,22,105,61,41,2,106,61,144,238,106,61,105,219,107,61,180,200,108,61,113,182,109,61,160,164,110,61,65,147,111,61,84,130,112,61,216,113,113,61,206,97,114,61,54,82,115,61,15,67,116,61,89,52,117,61,22,38,118,61,67,24,119,61,226,10,120,61,243,253,120,61,117,241,121,61,104,229,122,61,204,217,123,61,162,206,124,61,232,195,125,61,160,185,126,61,201,175,127,61,49,83,128,61,183,206,128,61,117,74,129,61,107,198,129,61,154,66,130,61,1,191,130,61,160,59,131,61,120,184,131,61,136,53,132,61,209,178,132,61,81,48,133,61,10,174,133,61,251,43,134,61,37,170,134,61,134,40,135,61,32,167,135,61,242,37,136,61,252,164,136,61,62,36,137,61,184,163,137,61,106,35,138,61,84,163,138,61,118,35,139,61,209,163,139,61,99,36,140,61,45,165,140,61,46,38,141,61,104,167,141,61,218,40,142,61,131,170,142,61,100,44,143,61,125,174,143,61,206,48,144,61,86,179,144,61,23,54,145,61,14,185,145,61,62,60,146,61,165,191,146,61,67,67,147,61,26,199,147,61,39,75,148,61,109,207,148,61,234,83,149,61,158,216,149,61,138,93,150,61,173,226,150,61,7,104,151,61,153,237,151,61,98,115,152,61,99,249,152,61,155,127,153,61,10,6,154,61,176,140,154,61,142,19,155,61,163,154,155,61,239,33,156,61,114,169,156,61,44,49,157,61,29,185,157,61,69,65,158,61,165,201,158,61,59,82,159,61,8,219,159,61,13,100,160,61,72,237,160,61,186,118,161,61,99,0,162,61,67,138,162,61,90,20,163,61,167,158,163,61,43,41,164,61,230,179,164,61,216,62,165,61,0,202,165,61,95,85,166,61,245,224,166,61,193,108,167,61,196,248,167,61,254,132,168,61,110,17,169,61,20,158,169,61,241,42,170,61,4,184,170,61,78,69,171,61,206,210,171,61,133,96,172,61,113,238,172,61,149,124,173,61,238,10,174,61,126,153,174,61,67,40,175,61,63,183,175,61,114,70,176,61,218,213,176,61,120,101,177,61,77,245,177,61,88,133,178,61,152,21,179,61,15,166,179,61,187,54,180,61,158,199,180,61,182,88,181,61,4,234,181,61,137,123,182,61,67,13,183,61,50,159,183,61,88,49,184,61,179,195,184,61,68,86,185,61,11,233,185,61,7,124,186,61,57,15,187,61,160,162,187,61,61,54,188,61,16,202,188,61,24,94,189,61,85,242,189,61,200,134,190,61,112,27,191,61,78,176,191,61,97,69,192,61,170,218,192,61,39,112,193,61,218,5,194,61,194,155,194,61,224,49,195,61,50,200,195,61,186,94,196,61,119,245,196,61,104,140,197,61,143,35,198,61,235,186,198,61,124,82,199,61,66,234,199,61,61,130,200,61,108,26,201,61,209,178,201,61,106,75,202,61,57,228,202,61,59,125,203,61,115,22,204,61,224,175,204,61,129,73,205,61,86,227,205,61,97,125,206,61,159,23,207,61,19,178,207,61,187,76,208,61,151,231,208,61,168,130,209,61,237,29,210,61,103,185,210,61,21,85,211,61,248,240,211,61,14,141,212,61,89,41,213,61,216,197,213,61,140,98,214,61,115,255,214,61,143,156,215,61,223,57,216,61,99,215,216,61,27,117,217,61,7,19,218,61,38,177,218,61,122,79,219,61,2,238,219,61,189,140,220,61,173,43,221,61,208,202,221,61,39,106,222,61,178,9,223,61,112,169,223,61,98,73,224,61,136,233,224,61,226,137,225,61,111,42,226,61,47,203,226,61,35,108,227,61,74,13,228,61,165,174,228,61,52,80,229,61,245,241,229,61,234,147,230,61,19,54,231,61,110,216,231,61,253,122,232,61,191,29,233,61,180,192,233,61,221,99,234,61,56,7,235,61,199,170,235,61,136,78,236,61,125,242,236,61,164,150,237,61,255,58,238,61,140,223,238,61,76,132,239,61,63,41,240,61,101,206,240,61,189,115,241,61,73,25,242,61,7,191,242,61,247,100,243,61,26,11,244,61,112,177,244,61,248,87,245,61,179,254,245,61,160,165,246,61,192,76,247,61,18,244,247,61,151,155,248,61,77,67,249,61,55,235,249,61,82,147,250,61,159,59,251,61,31,228,251,61,209,140,252,61,181,53,253,61,203,222,253,61,19,136,254,61,141,49,255,61,57,219,255,61,140,66,0,62,148,151,0,62,181,236,0,62,238,65,1,62,65,151,1,62,173,236,1,62,49,66,2,62,206,151,2,62,132,237,2,62,83,67,3,62,59,153,3,62,59,239,3,62,84,69,4,62,134,155,4,62,209,241,4,62,52,72,5,62,176,158,5,62,68,245,5,62,242,75,6,62,183,162,6,62,150,249,6,62,141,80,7,62,156,167,7,62,196,254,7,62,5,86,8,62,94,173,8,62,207,4,9,62,89,92,9,62,252,179,9,62,183,11,10,62,138,99,10,62,118,187,10,62,122,19,11,62,150,107,11,62,203,195,11,62,24,28,12,62,125,116,12,62,250,204,12,62,144,37,13,62,62,126,13,62,4,215,13,62,227,47,14,62,217,136,14,62,232,225,14,62,15,59,15,62,78,148,15,62,165,237,15,62,20,71,16,62,155,160,16,62,58,250,16,62,241,83,17,62,193,173,17,62,168,7,18,62,167,97,18,62,190,187,18,62,237,21,19,62,51,112,19,62,146,202,19,62,9,37,20,62,151,127,20,62,61,218,20,62,251,52,21,62,209,143,21,62,190,234,21,62,195,69,22,62,224,160,22,62,21,252,22,62,97,87,23,62,197,178,23,62,64,14,24,62,211,105,24,62,126,197,24,62,64,33,25,62,26,125,25,62,11,217,25,62,20,53,26,62,52,145,26,62,108,237,26,62,187,73,27,62,34,166,27,62,160,2,28,62,53,95,28,62,226,187,28,62,166,24,29,62,129,117,29,62,116,210,29,62,126,47,30,62,159,140,30,62,215,233,30,62,39,71,31,62,141,164,31,62,11,2,32,62,160,95,32,62,76,189,32,62,16,27,33,62,234,120,33,62,219,214,33,62,228,52,34,62,3,147,34,62,58,241,34,62,135,79,35,62,235,173,35,62,103,12,36,62,249,106,36,62,162,201,36,62,98,40,37,62,56,135,37,62,38,230,37,62,42,69,38,62,69,164,38,62,119,3,39,62,192,98,39,62,31,194,39,62,149,33,40,62,33,129,40,62,197,224,40,62,126,64,41,62,79,160,41,62,54,0,42,62,51,96,42,62,72,192,42,62,114,32,43,62,179,128,43,62,11,225,43,62,121,65,44,62,253,161,44,62,152,2,45,62,73,99,45,62,16,196,45,62,238,36,46,62,226,133,46,62,237,230,46,62,13,72,47,62,68,169,47,62,145,10,48,62,245,107,48,62,110,205,48,62,254,46,49,62,163,144,49,62,95,242,49,62,49,84,50,62,25,182,50,62,23,24,51,62,43,122,51,62,85,220,51,62,148,62,52,62,234,160,52,62,86,3,53,62,216,101,53,62,111,200,53,62,28,43,54,62,223,141,54,62,184,240,54,62,167,83,55,62,171,182,55,62,197,25,56,62,245,124,56,62,59,224,56,62,150,67,57,62,7,167,57,62,141,10,58,62,41,110,58,62,219,209,58,62,162,53,59,62,126,153,59,62,112,253,59,62,120,97,60,62,149,197,60,62,199,41,61,62,15,142,61,62,108,242,61,62,222,86,62,62,102,187,62,62,3,32,63,62,181,132,63,62,125,233,63,62,90,78,64,62,75,179,64,62,83,24,65,62,111,125,65,62,160,226,65,62,231,71,66,62,66,173,66,62,179,18,67,62,57,120,67,62,211,221,67,62,131,67,68,62,71,169,68,62,33,15,69,62],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE+10240);allocate([15,117,69,62,18,219,69,62,42,65,70,62,87,167,70,62,153,13,71,62,240,115,71,62,91,218,71,62,219,64,72,62,111,167,72,62,25,14,73,62,215,116,73,62,169,219,73,62,144,66,74,62,140,169,74,62,157,16,75,62,193,119,75,62,251,222,75,62,73,70,76,62,171,173,76,62,34,21,77,62,173,124,77,62,76,228,77,62,0,76,78,62,200,179,78,62,164,27,79,62,149,131,79,62,154,235,79,62,179,83,80,62,225,187,80,62,34,36,81,62,120,140,81,62,225,244,81,62,95,93,82,62,241,197,82,62,151,46,83,62,81,151,83,62,31,0,84,62,1,105,84,62,247,209,84,62,0,59,85,62,30,164,85,62,79,13,86,62,149,118,86,62,238,223,86,62,91,73,87,62,219,178,87,62,112,28,88,62,24,134,88,62,211,239,88,62,163,89,89,62,134,195,89,62,124,45,90,62,134,151,90,62,164,1,91,62,213,107,91,62,26,214,91,62,114,64,92,62,221,170,92,62,92,21,93,62,239,127,93,62,148,234,93,62,77,85,94,62,26,192,94,62,249,42,95,62,236,149,95,62,242,0,96,62,11,108,96,62,55,215,96,62,119,66,97,62,202,173,97,62,47,25,98,62,168,132,98,62,52,240,98,62,210,91,99,62,132,199,99,62,73,51,100,62,32,159,100,62,11,11,101,62,8,119,101,62,24,227,101,62,59,79,102,62,113,187,102,62,186,39,103,62,21,148,103,62,131,0,104,62,3,109,104,62,151,217,104,62,60,70,105,62,245,178,105,62,192,31,106,62,157,140,106,62,141,249,106,62,144,102,107,62,165,211,107,62,204,64,108,62,6,174,108,62,82,27,109,62,176,136,109,62,33,246,109,62,164,99,110,62,57,209,110,62,225,62,111,62,154,172,111,62,102,26,112,62,68,136,112,62,52,246,112,62,55,100,113,62,75,210,113,62,113,64,114,62,169,174,114,62,243,28,115,62,80,139,115,62,190,249,115,62,61,104,116,62,207,214,116,62,115,69,117,62,40,180,117,62,239,34,118,62,200,145,118,62,179,0,119,62,175,111,119,62,189,222,119,62,221,77,120,62,14,189,120,62,80,44,121,62,165,155,121,62,10,11,122,62,130,122,122,62,10,234,122,62,164,89,123,62,80,201,123,62,13,57,124,62,219,168,124,62,186,24,125,62,171,136,125,62,173,248,125,62,192,104,126,62,228,216,126,62,26,73,127,62,96,185,127,62,220,20,128,62,16,77,128,62,77,133,128,62,147,189,128,62,225,245,128,62,55,46,129,62,150,102,129,62,253,158,129,62,109,215,129,62,229,15,130,62,102,72,130,62,238,128,130,62,128,185,130,62,25,242,130,62,187,42,131,62,102,99,131,62,24,156,131,62,211,212,131,62,150,13,132,62,98,70,132,62,53,127,132,62,17,184,132,62,245,240,132,62,226,41,133,62,214,98,133,62,211,155,133,62,216,212,133,62,229,13,134,62,250,70,134,62,23,128,134,62,61,185,134,62,106,242,134,62,160,43,135,62,221,100,135,62,35,158,135,62,112,215,135,62,198,16,136,62,35,74,136,62,137,131,136,62,247,188,136,62,108,246,136,62,233,47,137,62,111,105,137,62,252,162,137,62,145,220,137,62,46,22,138,62,211,79,138,62,127,137,138,62,52,195,138,62,240,252,138,62,180,54,139,62,128,112,139,62,84,170,139,62,47,228,139,62,18,30,140,62,253,87,140,62,239,145,140,62,233,203,140,62,235,5,141,62,245,63,141,62,6,122,141,62,31,180,141,62,63,238,141,62,103,40,142,62,150,98,142,62,205,156,142,62,12,215,142,62,82,17,143,62,159,75,143,62,245,133,143,62,81,192,143,62,181,250,143,62,33,53,144,62,147,111,144,62,14,170,144,62,143,228,144,62,25,31,145,62,169,89,145,62,65,148,145,62,224,206,145,62,134,9,146,62,52,68,146,62,233,126,146,62,165,185,146,62,105,244,146,62,52,47,147,62,6,106,147,62,223,164,147,62,191,223,147,62,167,26,148,62,150,85,148,62,139,144,148,62,136,203,148,62,140,6,149,62,152,65,149,62,170,124,149,62,195,183,149,62,227,242,149,62,11,46,150,62,57,105,150,62,111,164,150,62,171,223,150,62,238,26,151,62,56,86,151,62,138,145,151,62,226,204,151,62,65,8,152,62,167,67,152,62,19,127,152,62,135,186,152,62,1,246,152,62,130,49,153,62,10,109,153,62,153,168,153,62,47,228,153,62,203,31,154,62,110,91,154,62,24,151,154,62,200,210,154,62,127,14,155,62,61,74,155,62,2,134,155,62,205,193,155,62,158,253,155,62,119,57,156,62,85,117,156,62,59,177,156,62,39,237,156,62,25,41,157,62,18,101,157,62,18,161,157,62,24,221,157,62,36,25,158,62,55,85,158,62,80,145,158,62,112,205,158,62,150,9,159,62,195,69,159,62,246,129,159,62,47,190,159,62,111,250,159,62,180,54,160,62,1,115,160,62,83,175,160,62,172,235,160,62,11,40,161,62,112,100,161,62,219,160,161,62,77,221,161,62,196,25,162,62,66,86,162,62,198,146,162,62,81,207,162,62,225,11,163,62,119,72,163,62,20,133,163,62,182,193,163,62,95,254,163,62,13,59,164,62,194,119,164,62,125,180,164,62,61,241,164,62,4,46,165,62,208,106,165,62,162,167,165,62,123,228,165,62,89,33,166,62,61,94,166,62,39,155,166,62,23,216,166,62,12,21,167,62,7,82,167,62,8,143,167,62,15,204,167,62,28,9,168,62,46,70,168,62,70,131,168,62,100,192,168,62,136,253,168,62,177,58,169,62,223,119,169,62,20,181,169,62,78,242,169,62,141,47,170,62,211,108,170,62,29,170,170,62,109,231,170,62,195,36,171,62,31,98,171,62,127,159,171,62,230,220,171,62,81,26,172,62,194,87,172,62,57,149,172,62,181,210,172,62,54,16,173,62,189,77,173,62,73,139,173,62,218,200,173,62,113,6,174,62,13,68,174,62,174,129,174,62,85,191,174,62,0,253,174,62,177,58,175,62,103,120,175,62,35,182,175,62,227,243,175,62,169,49,176,62,116,111,176,62,68,173,176,62,25,235,176,62,243,40,177,62,210,102,177,62,182,164,177,62,160,226,177,62,142,32,178,62,129,94,178,62,121,156,178,62,119,218,178,62,121,24,179,62,128,86,179,62,140,148,179,62,157,210,179,62,178,16,180,62,205,78,180,62,236,140,180,62,16,203,180,62,57,9,181,62,103,71,181,62,154,133,181,62,209,195,181,62,13,2,182,62,78,64,182,62,147,126,182,62,221,188,182,62,44,251,182,62,127,57,183,62,215,119,183,62,52,182,183,62,149,244,183,62,251,50,184,62,101,113,184,62,212,175,184,62,71,238,184,62,191,44,185,62,59,107,185,62,188,169,185,62,65,232,185,62,202,38,186,62,88,101,186,62,235,163,186,62,129,226,186,62,28,33,187,62,188,95,187,62,95,158,187,62,7,221,187,62,180,27,188,62,100,90,188,62,25,153,188,62,210,215,188,62,143,22,189,62,80,85,189,62,22,148,189,62,223,210,189,62,173,17,190,62,127,80,190,62,85,143,190,62,47,206,190,62,13,13,191,62,239,75,191,62,213,138,191,62,191,201,191,62,173,8,192,62,159,71,192,62,149,134,192,62,143,197,192,62,141,4,193,62,143,67,193,62,148,130,193,62,158,193,193,62,171,0,194,62,188,63,194,62,209,126,194,62,234,189,194,62,6,253,194,62,38,60,195,62,74,123,195,62,113,186,195,62,157,249,195,62,204,56,196,62,254,119,196,62,52,183,196,62,110,246,196,62,171,53,197,62,236,116,197,62,49,180,197,62,121,243,197,62,196,50,198,62,19,114,198,62,102,177,198,62,188,240,198,62,21,48,199,62,114,111,199,62,210,174,199,62,54,238,199,62,157,45,200,62,7,109,200,62,117,172,200,62,230,235,200,62,90,43,201,62,209,106,201,62,76,170,201,62,202,233,201,62,75,41,202,62,208,104,202,62,88,168,202,62,226,231,202,62,112,39,203,62,1,103,203,62,149,166,203,62,45,230,203,62,199,37,204,62,100,101,204,62,4,165,204,62,168,228,204,62,78,36,205,62,248,99,205,62,164,163,205,62,83,227,205,62,5,35,206,62,186,98,206,62,114,162,206,62,45,226,206,62,234,33,207,62,171,97,207,62,110,161,207,62,52,225,207,62,253,32,208,62,200,96,208,62,150,160,208,62,103,224,208,62,59,32,209,62,17,96,209,62,234,159,209,62,198,223,209,62,164,31,210,62,133,95,210,62,104,159,210,62,78,223,210,62,55,31,211,62,33,95,211,62,15,159,211,62,255,222,211,62,241,30,212,62,230,94,212,62,221,158,212,62,215,222,212,62,211,30,213,62,209,94,213,62,210,158,213,62,213,222,213,62,219,30,214,62,226,94,214,62,236,158,214,62,248,222,214,62,7,31,215,62,24,95,215,62,42,159,215,62,63,223,215,62,87,31,216,62,112,95,216,62,139,159,216,62,169,223,216,62,200,31,217,62,234,95,217,62,14,160,217,62,51,224,217,62,91,32,218,62,133,96,218,62,176,160,218,62,222,224,218,62,13,33,219,62,63,97,219,62,114,161,219,62,167,225,219,62,222,33,220,62,23,98,220,62,82,162,220,62,142,226,220,62,204,34,221,62,12,99,221,62,78,163,221,62,146,227,221,62,215,35,222,62,29,100,222,62,102,164,222,62,176,228,222,62,252,36,223,62,73,101,223,62,152,165,223,62,232,229,223,62,58,38,224,62,142,102,224,62,227,166,224,62,57,231,224,62,145,39,225,62,234,103,225,62,69,168,225,62,161,232,225,62,255,40,226,62,94,105,226,62,190,169,226,62,32,234,226,62,131,42,227,62,231,106,227,62,76,171,227,62,179,235,227,62,27,44,228,62,132,108,228,62,238,172,228,62,90,237,228,62,199,45,229,62,52,110,229,62,163,174,229,62,19,239,229,62,133,47,230,62,247,111,230,62,106,176,230,62,222,240,230,62,83,49,231,62,202,113,231,62,65,178,231,62,185,242,231,62,50,51,232,62,172,115,232,62,38,180,232,62,162,244,232,62,31,53,233,62,156,117,233,62,26,182,233,62,153,246,233,62,25,55,234,62,153,119,234,62,26,184,234,62,156,248,234,62,31,57,235,62,162,121,235,62,38,186,235,62,170,250,235,62,47,59,236,62,181,123,236,62,59,188,236,62,194,252,236,62,73,61,237,62,209,125,237,62,89,190,237,62,226,254,237,62,107,63,238,62,245,127,238,62,127,192,238,62,10,1,239,62,149,65,239,62,32,130,239,62,171,194,239,62,55,3,240,62,196,67,240,62,80,132,240,62,221,196,240,62,106,5,241,62,247,69,241,62,132,134,241,62,18,199,241,62,160,7,242,62,45,72,242,62,187,136,242,62,74,201,242,62,216,9,243,62,102,74,243,62,244,138,243,62,131,203,243,62,17,12,244,62,159,76,244,62,46,141,244,62,188,205,244,62,74,14,245,62,216,78,245,62,102,143,245,62,244,207,245,62,129,16,246,62,15,81,246,62,156,145,246,62,41,210,246,62,182,18,247,62,67,83,247,62,207,147,247,62,91,212,247,62,231,20,248,62,115,85,248,62,254,149,248,62,136,214,248,62,19,23,249,62,157,87,249,62,38,152,249,62,175,216,249,62,56,25,250,62,192,89,250,62,72,154,250,62,207,218,250,62,86,27,251,62,220,91,251,62,97,156,251,62,230,220,251,62,106,29,252,62,238,93,252,62,113,158,252,62,243,222,252,62,117,31,253,62,245,95,253,62,118,160,253,62,245,224,253,62,116,33,254,62,241,97,254,62,110,162,254,62,235,226,254,62,102,35,255,62,224,99,255,62,90,164,255,62,211,228,255,62,165,18,0,63,225,50,0,63,27,83,0,63,86,115,0,63,144,147,0,63,201,179,0,63,2,212,0,63,58,244,0,63,114,20,1,63,169,52,1,63,224,84,1,63,22,117,1,63,76,149,1,63,129,181,1,63,181,213,1,63,233,245,1,63,28,22,2,63,78,54,2,63,128,86,2,63,178,118,2,63,226,150,2,63,18,183,2,63,65,215,2,63,112,247,2,63,157,23,3,63,203,55,3,63,247,87,3,63,35,120,3,63,78,152,3,63,120,184,3,63,161,216,3,63,202,248,3,63,242,24,4,63,25,57,4,63,63,89,4,63,101,121,4,63,137,153,4,63,173,185,4,63,208,217,4,63,243,249,4,63,20,26,5,63,52,58,5,63,84,90,5,63,115,122,5,63,145,154,5,63,173,186,5,63,202,218,5,63,229,250,5,63,255,26,6,63,24,59,6,63,48,91,6,63,72,123,6,63,94,155,6,63,116,187,6,63,136,219,6,63,155,251,6,63,174,27,7,63,191,59,7,63,208,91,7,63,223,123,7,63,237,155,7,63,250,187,7,63,7,220,7,63,18,252,7,63,28,28,8,63,37,60,8,63,44,92,8,63,51,124,8,63,57,156,8,63,61,188,8,63,64,220,8,63,67,252,8,63,68,28,9,63,68,60,9,63,66,92,9,63,64,124,9,63,60,156,9,63,55,188,9,63,49,220,9,63,41,252,9,63,33,28,10,63,23,60,10,63,12,92,10,63,255,123,10,63,242,155,10,63,227,187,10,63,211,219,10,63,193,251,10,63,174,27,11,63,154,59,11,63,133,91,11,63,110,123,11,63,86,155,11,63,60,187,11,63,33,219,11,63,5,251,11,63,231,26,12,63,200,58,12,63,168,90,12,63,134,122,12,63,98,154,12,63,62,186,12,63,23,218,12,63,240,249,12,63,199,25,13,63,156,57,13,63,112,89,13,63,66,121,13,63,19,153,13,63,227,184,13,63,176,216,13,63,125,248,13,63,72,24,14,63,17,56,14,63,216,87,14,63,159,119,14,63,99,151,14,63,38,183,14,63,232,214,14,63,167,246,14,63,101,22,15,63,34,54,15,63,221,85,15,63,150,117,15,63,78,149,15,63,4,181,15,63,184,212,15,63,106,244,15,63,27,20,16,63,202,51,16,63,120,83,16,63,36,115,16,63,206,146,16,63,118,178,16,63,28,210,16,63,193,241,16,63,100,17,17,63,6,49,17,63,165,80,17,63,67,112,17,63,223,143,17,63,121,175,17,63,17,207,17,63,167,238,17,63,60,14,18,63,206,45,18,63,95,77,18,63,238,108,18,63,123,140,18,63,7,172,18,63,144,203,18,63,23,235,18,63,157,10,19,63,32,42,19,63,162,73,19,63,34,105,19,63,159,136,19,63,27,168,19,63,149,199,19,63,13,231,19,63,131,6,20,63,247,37,20,63,104,69,20,63,216,100,20,63,70,132,20,63,178,163,20,63,27,195,20,63,131,226,20,63,233,1,21,63,76,33,21,63,174,64,21,63,13,96,21,63,106,127,21,63,197,158,21,63,31,190,21,63,117,221,21,63,202,252,21,63,29,28,22,63,109,59,22,63,188,90,22,63,8,122,22,63,82,153,22,63,153,184,22,63,223,215,22,63,34,247,22,63,100,22,23,63,162,53,23,63,223,84,23,63,26,116,23,63,82,147,23,63,136,178,23,63,187,209,23,63,237,240,23,63,28,16,24,63,73,47,24,63,115,78,24,63,155,109,24,63,193,140,24,63,228,171,24,63,6,203,24,63,36,234,24,63,65,9,25,63,91,40,25,63,115,71,25,63,136,102,25,63,155,133,25,63,171,164,25,63,185,195,25,63,197,226,25,63,206,1,26,63,213,32,26,63,217,63,26,63,219,94,26,63,218,125,26,63,215,156,26,63,210,187,26,63,202,218,26,63,191,249,26,63,178,24,27,63,162,55,27,63,144,86,27,63,123,117,27,63,100,148,27,63,74,179,27,63,46,210,27,63,15,241,27,63,237,15,28,63,201,46,28,63,162,77,28,63,121,108,28,63,77,139,28,63,31,170,28,63,237,200,28,63,185,231,28,63,131,6,29,63,74,37,29,63,14,68,29,63,207,98,29,63,142,129,29,63,74,160,29,63,3,191,29,63,186,221,29,63,110,252,29,63,31,27,30,63,205,57,30,63,121,88,30,63,34,119,30,63,200,149,30,63,107,180,30,63,12,211,30,63,170,241,30,63,69,16,31,63,221,46,31,63,114,77,31,63,5,108,31,63,148,138,31,63,33,169,31,63,171,199,31,63,50,230,31,63,182,4,32,63,56,35,32,63,182,65,32,63,50,96,32,63,170,126,32,63,32,157,32,63,147,187,32,63,3,218,32,63,112,248,32,63,218,22,33,63,65,53,33,63,165,83,33,63,6,114,33,63,100,144,33,63,191,174,33,63,23,205,33,63,108,235,33,63,190,9,34,63,13,40,34,63,89,70,34,63,162,100,34,63,232,130,34,63,43,161,34,63,107,191,34,63,167,221,34,63,225,251,34,63,24,26,35,63,75,56,35,63,123,86,35,63,168,116,35,63,211,146,35,63,249,176,35,63,29,207,35,63,62,237,35,63,91,11,36,63,118,41,36,63,141,71,36,63,161,101,36,63,177,131,36,63,191,161,36,63,201,191,36,63,208,221,36,63,212,251,36,63,213,25,37,63,210,55,37,63,204,85,37,63,195,115,37,63,183,145,37,63,167,175,37,63,148,205,37,63,126,235,37,63,101,9,38,63,72,39,38,63,40,69,38,63,4,99,38,63,221,128,38,63,179,158,38,63,134,188,38,63,85,218,38,63,33,248,38,63,233,21,39,63,174,51,39,63,112,81,39,63,46,111,39,63,233,140,39,63,160,170,39,63,84,200,39,63,4,230,39,63,178,3,40,63,91,33,40,63,1,63,40,63,164,92,40,63,67,122,40,63,223,151,40,63,120,181,40,63,12,211,40,63,158,240,40,63,43,14,41,63,182,43,41,63,60,73,41,63,192,102,41,63,63,132,41,63,187,161,41,63,52,191,41,63,169,220,41,63,26,250,41,63,136,23,42,63,242,52,42,63,89,82,42,63,188,111,42,63,28,141,42,63,119,170,42,63,208,199,42,63,36,229,42,63,117,2,43,63,194,31,43,63,12,61,43,63,82,90,43,63,148,119,43,63,211,148,43,63,14,178,43,63,69,207,43,63,120,236,43,63,168,9,44,63,212,38,44,63,252,67,44,63,33,97,44,63,66,126,44,63,95,155,44,63,120,184,44,63,142,213,44,63,159,242,44,63,173,15,45,63,184,44,45,63,190,73,45,63,193,102,45,63,191,131,45,63,186,160,45,63,177,189,45,63,165,218,45,63,148,247,45,63,128,20,46,63,103,49,46,63,75,78,46,63,43,107,46,63,7,136,46,63,224,164,46,63,180,193,46,63,132,222,46,63,81,251,46,63,26,24,47,63,222,52,47,63,159,81,47,63,92,110,47,63,21,139,47,63,202,167,47,63,123,196,47,63,40,225,47,63,209,253,47,63,118,26,48,63,23,55,48,63,180,83,48,63,77,112,48,63,226,140,48,63,115,169,48,63,0,198,48,63,137,226,48,63,14,255,48,63,142,27,49,63,11,56,49,63,132,84,49,63,248,112,49,63,105,141,49,63,214,169,49,63,62,198,49,63,162,226,49,63,2,255,49,63,95,27,50,63,182,55,50,63,10,84,50,63,90,112,50,63,166,140,50,63,237,168,50,63,48,197,50,63,111,225,50,63,170,253,50,63,225,25,51,63,19,54,51,63,66,82,51,63,108,110,51,63,146,138,51,63,180,166,51,63,209,194,51,63,234,222,51,63,0,251,51,63,16,23,52,63,29,51,52,63,37,79,52,63,41,107,52,63,41,135,52,63,37,163,52,63,28,191,52,63,15,219,52,63,253,246,52,63,232,18,53,63,206,46,53,63,176,74,53,63,141,102,53,63,102,130,53,63,59,158,53,63,11,186,53,63,215,213,53,63,159,241,53,63,98,13,54,63,33,41,54,63,220,68,54,63,146,96,54,63,68,124,54,63,241,151,54,63,154,179,54,63,63,207,54,63,223,234,54,63,123,6,55,63,18,34,55,63,165,61,55,63,52,89,55,63,190,116,55,63,67,144,55,63,196,171,55,63,65,199,55,63,185,226,55,63,45,254,55,63,156,25,56,63,7,53,56,63,109,80,56,63,207,107,56,63,44,135,56,63,133,162,56,63,217,189,56,63,40,217,56,63,115,244,56,63,186,15,57,63,252,42,57,63,57,70,57,63,114,97,57,63,166,124,57,63,214,151,57,63,1,179,57,63,40,206,57,63,74,233,57,63,103,4,58,63,128,31,58,63,148,58,58,63,163,85,58,63,174,112,58,63,180,139,58,63,182,166,58,63,179,193,58,63,171,220,58,63,159,247,58,63,142,18,59,63,120,45,59,63,94,72,59,63,63,99,59,63,27,126,59,63,243,152,59,63,197,179,59,63,148,206,59,63,93,233,59,63,34,4,60,63,226,30,60,63,157,57,60,63,84,84,60,63,5,111,60,63,178,137,60,63,91,164,60,63,254,190,60,63,157,217,60,63,55,244,60,63,204,14,61,63,93,41,61,63,232,67,61,63,111,94,61,63,241,120,61,63,110,147,61,63,231,173,61,63,91,200,61,63,201,226,61,63,51,253,61,63,152,23,62,63,249,49,62,63,84,76,62,63,171,102,62,63,252,128,62,63,73,155,62,63,145,181,62,63,212,207,62,63,19,234,62,63,76,4,63,63,128,30,63,63,176,56,63,63,219,82,63,63,0,109,63,63,33,135,63,63,61,161,63,63,84,187,63,63,102,213,63,63,115,239,63,63,123,9,64,63,127,35,64,63,125,61,64,63,118,87,64,63,106,113,64,63,90,139,64,63,68,165,64,63,42,191,64,63,10,217,64,63,229,242,64,63,188,12,65,63,141,38,65,63,90,64,65,63,33,90,65,63,228,115,65,63,161,141,65,63,89,167,65,63,13,193,65,63,187,218,65,63,100,244,65,63,8,14,66,63,167,39,66,63,65,65,66,63,214,90,66,63,102,116,66,63,241,141,66,63,119,167,66,63,248,192,66,63,115,218,66,63,234,243,66,63,91,13,67,63,199,38,67,63,47,64,67,63,145,89,67,63,238,114,67,63,69,140,67,63,152,165,67,63,230,190,67,63,46,216,67,63,113,241,67,63,175,10,68,63,232,35,68,63,28,61,68,63,75,86,68,63,116,111,68,63,153,136,68,63,184,161,68,63,210,186,68,63,230,211,68,63,246,236,68,63,0,6,69,63,5,31,69,63,5,56,69,63,0,81,69,63,245,105,69,63,230,130,69,63,209,155,69,63,182,180,69,63,151,205,69,63,114,230,69,63,72,255,69,63,25,24,70,63,229,48,70,63,171,73,70,63,108,98,70,63,40,123,70,63,222,147,70,63,143,172,70,63,59,197,70,63,226,221,70,63,131,246,70,63,31,15,71,63,182,39,71,63,71,64,71,63,211,88,71,63,90,113,71,63,220,137,71,63,88,162,71,63,207,186,71,63,64,211,71,63,172,235,71,63,19,4,72,63,116,28,72,63,209,52,72,63,39,77,72,63,121,101,72,63,197,125,72,63,11,150,72,63,77,174,72,63,137,198,72,63,191,222,72,63,240,246,72,63,28,15,73,63,66,39,73,63,99,63,73,63,127,87,73,63,149,111,73,63,166,135,73,63,177,159,73,63,183,183,73,63,183,207,73,63,178,231,73,63,168,255,73,63,152,23,74,63,131,47,74,63,104,71,74,63,72,95,74,63,34,119,74,63,247,142,74,63,199,166,74,63,145,190,74,63,85,214,74,63,20,238,74,63,206,5,75,63,130,29,75,63,49,53,75,63,218,76,75,63,126,100,75,63,28,124,75,63,181,147,75,63,72,171,75,63,213,194,75,63,93,218,75,63,224,241,75,63,93,9,76,63,213,32,76,63,71,56,76,63,179,79,76,63,26,103,76,63,124,126,76,63,216,149,76,63,46,173,76,63,127,196,76,63,202,219,76,63,16,243,76,63,80,10,77,63,139,33,77,63,192,56,77,63,240,79,77,63,26,103,77,63,62,126,77,63,93,149,77,63,118,172,77,63,137,195,77,63,151,218,77,63,160,241,77,63,163,8,78,63,160,31,78,63,151,54,78,63,137,77,78,63,118,100,78,63,93,123,78,63,62,146,78,63,25,169,78,63,239,191,78,63,192,214,78,63,138,237,78,63,79,4,79,63,15,27,79,63,201,49,79,63,125,72,79,63,43,95,79,63,212,117,79,63,119,140,79,63,21,163,79,63,172,185,79,63,63,208,79,63,203,230,79,63,82,253,79,63,211,19,80,63,79,42,80,63,197,64,80,63,53,87,80,63,159,109,80,63,4,132,80,63,99,154,80,63,189,176,80,63,16,199,80,63,94,221,80,63,167,243,80,63,233,9,81,63,38,32,81,63,93,54,81,63,143,76,81,63,187,98,81,63,225,120,81,63,1,143,81,63,28,165,81,63,48,187,81,63,64,209,81,63,73,231,81,63,77,253,81,63,75,19,82,63,67,41,82,63,53,63,82,63,34,85,82,63,9,107,82,63,234,128,82,63,198,150,82,63,155,172,82,63,107,194,82,63,53,216,82,63,250,237,82,63,185,3,83,63,113,25,83,63,37,47,83,63,210,68,83,63,121,90,83,63,27,112,83,63,183,133,83,63,77,155,83,63,222,176,83,63,104,198,83,63,237,219,83,63,108,241,83,63,230,6,84,63,89,28,84,63,199,49,84,63,46,71,84,63,145,92,84,63,237,113,84,63,67,135,84,63,148,156,84,63,223,177,84,63,35,199,84,63,99,220,84,63,156,241,84,63,207,6,85,63,253,27,85,63,37,49,85,63,71,70,85,63,99,91,85,63,121,112,85,63,138,133,85,63,149,154,85,63,153,175,85,63,152,196,85,63,146,217,85,63,133,238,85,63,114,3,86,63,90,24,86,63,60,45,86,63,24,66,86,63,238,86,86,63,190,107,86,63,136,128,86,63,76,149,86,63,11,170,86,63,196,190,86,63,118,211,86,63,35,232,86,63,203,252,86,63,108,17,87,63,7,38,87,63,156,58,87,63,44,79,87,63,182,99,87,63,58,120,87,63,183,140,87,63,47,161,87,63,162,181,87,63,14,202,87,63,116,222,87,63,213,242,87,63,47,7,88,63,132,27,88,63,211,47,88,63,28,68,88,63,95,88,88,63,156,108,88,63,211,128,88,63,4,149,88,63,47,169,88,63,85,189,88,63,116,209,88,63,142,229,88,63,162,249,88,63,175,13,89,63,183,33,89,63,185,53,89,63,181,73,89,63,171,93,89,63,155,113,89,63,134,133,89,63,106,153,89,63,72,173,89,63,33,193,89,63,243,212,89,63,192,232,89,63,135,252,89,63,71,16,90,63,2,36,90,63,183,55,90,63,102,75,90,63,15,95,90,63,178,114,90,63,79,134,90,63,230,153,90,63,119,173,90,63,3,193,90,63,136,212,90,63,7,232,90,63,129,251,90,63,244,14,91,63,98,34,91,63,201,53,91,63,43,73,91,63,135,92,91,63,220,111,91,63,44,131,91,63,118,150,91,63,186,169,91,63,248,188,91,63,47,208,91,63,97,227,91,63,141,246,91,63,179,9,92,63,212,28,92,63,238,47,92,63,2,67,92,63,16,86,92,63,24,105,92,63,26,124,92,63,23,143,92,63,13,162,92,63,253,180,92,63,232,199,92,63,204,218,92,63,171,237,92,63,131,0,93,63,86,19,93,63,34,38,93,63,233,56,93,63,169,75,93,63,100,94,93,63,24,113,93,63,199,131,93,63,112,150,93,63,18,169,93,63,175,187,93,63,70,206,93,63,215,224,93,63,97,243,93,63,230,5,94,63,101,24,94,63,222,42,94,63,81,61,94,63,190,79,94,63,36,98,94,63,133,116,94,63,224,134,94,63,53,153,94,63,132,171,94,63,205,189,94,63,16,208,94,63,77,226,94,63,132,244,94,63,181,6,95,63,224,24,95,63,5,43,95,63,36,61,95,63,61,79,95,63,80,97,95,63,93,115,95,63,101,133,95,63,102,151,95,63,97,169,95,63,86,187,95,63,69,205,95,63,46,223,95,63,18,241,95,63,239,2,96,63,198,20,96,63,151,38,96,63,98,56,96,63,40,74,96,63,231,91,96,63,160,109,96,63,84,127,96,63,1,145,96,63,168,162,96,63,73,180,96,63,229,197,96,63,122,215,96,63,10,233,96,63,147,250,96,63,22,12,97,63,148,29,97,63,11,47,97,63,125,64,97,63,232,81,97,63,77,99,97,63,173,116,97,63,6,134,97,63,90,151,97,63,167,168,97,63,239,185,97,63,48,203,97,63,108,220,97,63,162,237,97,63,209,254,97,63,251,15,98,63,30,33,98,63,60,50,98,63,84,67,98,63,101,84,98,63,113,101,98,63,119,118,98,63,119,135,98,63,112,152,98,63,100,169,98,63,82,186,98,63,58,203,98,63,28,220,98,63,247,236,98,63,205,253,98,63,157,14,99,63,103,31,99,63,43,48,99,63,233,64,99,63,161,81,99,63,83,98,99,63,255,114,99,63,165,131,99,63,69,148,99,63,224,164,99,63,116,181,99,63,2,198,99,63,138,214,99,63,13,231,99,63,137,247,99,63,255,7,100,63,112,24,100,63,218,40,100,63,62,57,100,63,157,73,100,63,246,89,100,63,72,106,100,63,149,122,100,63,219,138,100,63,28,155,100,63,87,171,100,63,140,187,100,63,186,203,100,63,227,219,100,63,6,236,100,63,35,252,100,63,58,12,101,63,75,28,101,63,86,44,101,63,91,60,101,63,91,76,101,63,84,92,101,63,71,108,101,63,53,124,101,63,28,140,101,63,254,155,101,63,217,171,101,63,175,187,101,63,126,203,101,63,72,219,101,63,12,235,101,63,202,250,101,63,130,10,102,63,52,26,102,63,224,41,102,63,134,57,102,63,38,73,102,63,193,88,102,63,85,104,102,63,227,119,102,63,108,135,102,63,238,150,102,63,107,166,102,63,226,181,102,63,83,197,102,63,190,212,102,63,35,228,102,63,130,243,102,63,219,2,103,63,46,18,103,63,124,33,103,63,195,48,103,63,5,64,103,63,64,79,103,63,118,94,103,63,166,109,103,63,208,124,103,63,244,139,103,63,18,155,103,63,42,170,103,63,61,185,103,63,73,200,103,63,80,215,103,63,80,230,103,63,75,245,103,63,64,4,104,63,47,19,104,63,24,34,104,63,251,48,104,63,217,63,104,63,176,78,104,63,130,93,104,63,78,108,104,63,20,123,104,63,212,137,104,63,142,152,104,63,66,167,104,63,240,181,104,63,153,196,104,63,60,211,104,63,217,225,104,63,112,240,104,63,1,255,104,63,140,13,105,63,17,28,105,63,145,42,105,63,11,57,105,63,127,71,105,63,237,85,105,63,85,100,105,63,183,114,105,63,20,129,105,63,106,143,105,63,187,157,105,63,6,172,105,63,75,186,105,63,139,200,105,63,196,214,105,63,248,228,105,63,38,243,105,63,78,1,106,63,112,15,106,63,141,29,106,63,163,43,106,63,180,57,106,63,191,71,106,63,196,85,106,63,196,99,106,63,189,113,106,63,177,127,106,63,159,141,106,63,135,155,106,63,106,169,106,63,70,183,106,63,29,197,106,63,238,210,106,63,186,224,106,63,127,238,106,63,63,252,106,63,249,9,107,63,173,23,107,63,91,37,107,63,4,51,107,63,167,64,107,63,68,78,107,63,219,91,107,63,109,105,107,63,249,118,107,63,127,132,107,63,255,145,107,63,122,159,107,63,238,172,107,63,94,186,107,63,199,199,107,63,42,213,107,63,136,226,107,63,224,239,107,63,51,253,107,63,128,10,108,63,198,23,108,63,8,37,108,63,67,50,108,63,121,63,108,63,169,76,108,63,211,89,108,63,248,102,108,63,23,116,108,63,48,129,108,63,68,142,108,63,82,155,108,63,90,168,108,63,92,181,108,63,89,194,108,63,80,207,108,63,65,220,108,63,45,233,108,63,19,246,108,63,243,2,109,63,206,15,109,63,163,28,109,63,114,41,109,63,60,54,109,63,0,67,109,63,190,79,109,63,119,92,109,63,42,105,109,63,215,117,109,63,127,130,109,63,33,143,109,63,189,155,109,63,84,168,109,63,229,180,109,63,113,193,109,63,247,205,109,63,119,218,109,63,242,230,109,63,103,243,109,63,214,255,109,63,64,12,110,63,164,24,110,63,3,37,110,63,91,49,110,63,175,61,110,63,253,73,110,63,69,86,110,63,135,98,110,63,196,110,110,63,252,122,110,63,45,135,110,63,90,147,110,63,128,159,110,63,161,171,110,63,189,183,110,63,211,195,110,63,227,207,110,63,238,219,110,63,243,231,110,63,243,243,110,63,237,255,110,63,226,11,111,63,209,23,111,63,186,35,111,63,158,47,111,63,125,59,111,63,85,71,111,63,41,83,111,63,247,94,111,63,191,106,111,63,130,118,111,63,63,130,111,63,247,141,111,63,169,153,111,63,86,165,111,63,253,176,111,63,159,188,111,63,59,200,111,63,210,211,111,63,99,223,111,63,239,234,111,63,117,246,111,63,246,1,112,63,114,13,112,63,231,24,112,63,88,36,112,63,195,47,112,63,40,59,112,63,137,70,112,63,227,81,112,63,56,93,112,63,136,104,112,63,210,115,112,63,23,127,112,63,87,138,112,63,145,149,112,63,197,160,112,63,244,171,112,63,30,183,112,63,66,194,112,63,97,205,112,63,123,216,112,63,143,227,112,63,157,238,112,63,167,249,112,63,171,4,113,63,169,15,113,63,162,26,113,63,150,37,113,63,132,48,113,63,109,59,113,63,81,70,113,63,47,81,113,63,8,92,113,63,219,102,113,63,170,113,113,63,114,124,113,63,54,135,113,63,244,145,113,63,173,156,113,63,96,167,113,63,14,178,113,63,183,188,113,63,91,199,113,63,249,209,113,63,146,220,113,63,37,231,113,63,179,241,113,63,60,252,113,63,192,6,114,63,62,17,114,63,183,27,114,63,43,38,114,63,154,48,114,63,3,59,114,63,103,69,114,63,197,79,114,63,31,90,114,63,115,100,114,63,194,110,114,63,11,121,114,63,79,131,114,63,143,141,114,63,200,151,114,63,253,161,114,63,44,172,114,63,87,182,114,63,123,192,114,63,155,202,114,63,182,212,114,63,203,222,114,63,219,232,114,63,230,242,114,63,235,252,114,63,236,6,115,63,231,16,115,63,221,26,115,63,206,36,115,63,186,46,115,63,160,56,115,63,130,66,115,63,94,76,115,63,53,86,115,63,7,96,115,63,212,105,115,63,155,115,115,63,94,125,115,63,27,135,115,63,211,144,115,63,134,154,115,63,52,164,115,63,221,173,115,63,128,183,115,63,31,193,115,63,184,202,115,63,77,212,115,63,220,221,115,63,102,231,115,63,235,240,115,63,107,250,115,63,230,3,116,63,92,13,116,63,204,22,116,63,56,32,116,63,159,41,116,63,0,51,116,63,93,60,116,63,180,69,116,63,6,79,116,63,84,88,116,63,156,97,116,63,223,106,116,63,29,116,116,63,87,125,116,63,139,134,116,63,186,143,116,63,228,152,116,63,9,162,116,63,41,171,116,63,68,180,116,63,91,189,116,63,108,198,116,63,120,207,116,63,127,216,116,63,129,225,116,63,127,234,116,63,119,243,116,63,106,252,116,63,89,5,117,63,66,14,117,63,38,23,117,63,6,32,117,63,225,40,117,63,182,49,117,63,135,58,117,63,83,67,117,63,26,76,117,63,220,84,117,63,153,93,117,63,81,102,117,63,4,111,117,63,179,119,117,63,92,128,117,63,1,137,117,63,160,145,117,63,59,154,117,63,209,162,117,63,98,171,117,63,239,179,117,63,118,188,117,63,249,196,117,63,118,205,117,63,239,213,117,63,99,222,117,63,210,230,117,63,61,239,117,63,162,247,117,63,3,0,118,63,95,8,118,63,182,16,118,63,8,25,118,63,86,33,118,63,159,41,118,63,227,49,118,63,34,58,118,63,92,66,118,63,146,74,118,63,195,82,118,63,239,90,118,63,22,99,118,63,57,107,118,63,86,115,118,63,112,123,118,63,132,131,118,63,148,139,118,63,158,147,118,63,165,155,118,63,166,163,118,63,163,171,118,63,155,179,118,63,142,187,118,63,125,195,118,63,103,203,118,63,76,211,118,63,45,219,118,63,9,227,118,63,224,234,118,63,178,242,118,63,128,250,118,63,74,2,119,63,14,10,119,63,206,17,119,63,137,25,119,63,64,33,119,63,242,40,119,63,160,48,119,63,72,56,119,63,237,63,119,63,140,71,119,63,39,79,119,63,190,86,119,63,79,94,119,63,220,101,119,63,101,109,119,63,233,116,119,63,105,124,119,63,228,131,119,63,90,139,119,63,204,146,119,63,57,154,119,63,162,161,119,63,6,169,119,63,101,176,119,63,192,183,119,63,23,191,119,63,105,198,119,63,182,205,119,63,255,212,119,63,68,220,119,63,132,227,119,63,191,234,119,63,246,241,119,63,41,249,119,63,87,0,120,63,129,7,120,63,166,14,120,63,198,21,120,63,227,28,120,63,250,35,120,63,14,43,120,63,28,50,120,63,39,57,120,63,45,64,120,63,46,71,120,63,44,78,120,63,36,85,120,63,25,92,120,63,9,99,120,63,244,105,120,63,219,112,120,63,190,119,120,63,156,126,120,63,118,133,120,63,76,140,120,63,29,147,120,63,234,153,120,63,179,160,120,63,119,167,120,63,55,174,120,63,242,180,120,63,169,187,120,63,92,194,120,63,11,201,120,63,181,207,120,63,91,214,120,63,252,220,120,63,154,227,120,63,51,234,120,63,199,240,120,63,88,247,120,63,228,253,120,63,108,4,121,63,240,10,121,63,111,17,121,63,234,23,121,63,97,30,121,63,211,36,121,63,66,43,121,63,172,49,121,63,18,56,121,63,116,62,121,63,209,68,121,63,42,75,121,63,127,81,121,63,208,87,121,63,29,94,121,63,101,100,121,63,170,106,121,63,234,112,121,63,38,119,121,63,93,125,121,63,145,131,121,63,193,137,121,63,236,143,121,63,19,150,121,63,54,156,121,63,85,162,121,63,112,168,121,63,134,174,121,63,153,180,121,63,167,186,121,63,178,192,121,63,184,198,121,63,186,204,121,63,184,210,121,63,178,216,121,63,168,222,121,63,154,228,121,63,135,234,121,63,113,240,121,63,87,246,121,63,56,252,121,63,22,2,122,63,239,7,122,63,197,13,122,63,150,19,122,63,100,25,122,63,45,31,122,63,243,36,122,63,180,42,122,63,113,48,122,63,43,54,122,63,224,59,122,63,146,65,122,63,63,71,122,63,233,76,122,63,142,82,122,63,48,88,122,63,206,93,122,63,103,99,122,63,253,104,122,63,143,110,122,63,29,116,122,63,167,121,122,63,45,127,122,63,175,132,122,63,45,138,122,63,168,143,122,63,30,149,122,63,145,154,122,63,255,159,122,63,106,165,122,63,209,170,122,63,52,176,122,63,147,181,122,63,239,186,122,63,70,192,122,63,154,197,122,63,234,202,122,63,54,208,122,63,126,213,122,63,194,218,122,63,3,224,122,63,64,229,122,63,121,234,122,63,174,239,122,63,223,244,122,63,13,250,122,63,55,255,122,63,93,4,123,63,127,9,123,63,157,14,123,63,184,19,123,63,207,24,123,63,227,29,123,63,242,34,123,63,254,39,123,63,6,45,123,63,10,50,123,63,11,55,123,63,8,60,123,63,1,65,123,63,247,69,123,63,233,74,123,63,215,79,123,63,193,84,123,63,168,89,123,63,139,94,123,63,107,99,123,63,71,104,123,63,31,109,123,63,243,113,123,63,196,118,123,63,146,123,123,63,91,128,123,63,33,133,123,63,228,137,123,63,163,142,123,63,94,147,123,63,22,152,123,63,202,156,123,63,122,161,123,63,39,166,123,63,208,170,123,63,118,175,123,63,24,180,123,63,183,184,123,63,82,189,123,63,233,193,123,63,125,198,123,63,14,203,123,63,155,207,123,63,36,212,123,63,170,216,123,63,45,221,123,63,172,225,123,63,39,230,123,63,159,234,123,63,19,239,123,63,132,243,123,63,242,247,123,63,92,252,123,63,195,0,124,63,38,5,124,63,133,9,124,63,226,13,124,63,58,18,124,63,144,22,124,63,226,26,124,63,48,31,124,63,123,35,124,63,195,39,124,63,7,44,124,63,72,48,124,63,134,52,124,63,192,56,124,63,247,60,124,63,42,65,124,63,90,69,124,63,135,73,124,63,176,77,124,63,214,81,124,63,249,85,124,63,24,90,124,63,52,94,124,63,77,98,124,63,98,102,124,63,116,106,124,63,131,110,124,63,142,114,124,63,150,118,124,63,155,122,124,63,157,126,124,63,155,130,124,63,150,134,124,63,142,138,124,63,130,142,124,63,116,146,124,63,98,150,124,63,77,154,124,63,52,158,124,63,24,162,124,63,249,165,124,63,215,169,124,63,178,173,124,63,137,177,124,63,94,181,124,63,47,185,124,63,253,188,124,63,199,192,124,63,143,196,124,63,83,200,124,63,20,204,124,63,211,207,124,63,141,211,124,63,69,215,124,63,250,218,124,63,171,222,124,63,90,226,124,63,5,230,124,63,173,233,124,63,82,237,124,63,244,240,124,63,147,244,124,63,46,248,124,63,199,251,124,63,93,255,124,63,239,2,125,63,127,6,125,63,11,10,125,63,148,13,125,63,27,17,125,63,158,20,125,63,30,24,125,63,155,27,125,63,21,31,125,63,140,34,125,63,0,38,125,63,114,41,125,63,224,44,125,63,75,48,125,63,179,51,125,63,24,55,125,63,122,58,125,63,217,61,125,63,54,65,125,63,143,68,125,63,229,71,125,63,56,75,125,63,137,78,125,63,214,81,125,63,33,85,125,63,104,88,125,63,173,91,125,63,239,94,125,63,46,98,125,63,106,101,125,63,163,104,125,63,217,107,125,63,12,111,125,63,61,114,125,63,106,117,125,63,149,120,125,63,189,123,125,63,226,126,125,63,4,130,125,63,36,133,125,63,64,136,125,63,90,139,125,63,112,142,125,63,133,145,125,63,150,148,125,63,164,151,125,63,176,154,125,63,185,157,125,63,191,160,125,63,194,163,125,63,194,166,125,63,192,169,125,63,187,172,125,63,179,175,125,63,168,178,125,63,155,181,125,63,139,184,125,63,120,187,125,63,99,190,125,63,74,193,125,63,48,196,125,63,18,199,125,63,241,201,125,63,206,204,125,63,169,207,125,63,128,210,125,63,85,213,125,63,39,216,125,63,247,218,125,63,196,221,125,63,142,224,125,63,85,227,125,63,26,230,125,63,220,232,125,63,156,235,125,63,89,238,125,63,19,241,125,63,203,243,125,63,128,246,125,63,51,249,125,63,227,251,125,63,144,254,125,63,59,1,126,63,227,3,126,63,137,6,126,63,44,9,126,63,204,11,126,63,106,14,126,63,6,17,126,63,158,19,126,63,53,22,126,63,200,24,126,63,90,27,126,63,232,29,126,63,116,32,126,63,254,34,126,63,133,37,126,63,10,40,126,63,140,42,126,63,12,45,126,63,137,47,126,63,4,50,126,63,124,52,126,63,242,54,126,63,101,57,126,63,214,59,126,63,68,62,126,63,176,64,126,63,26,67,126,63,129,69,126,63,230,71,126,63,72,74,126,63,168,76,126,63,5,79,126,63,96,81,126,63,185,83,126,63,15,86,126,63,99,88,126,63,181,90,126,63,4,93,126,63,81,95,126,63,155,97,126,63,227,99,126,63,41,102,126,63,108,104,126,63,173,106,126,63,236,108,126,63,40,111,126,63,98,113,126,63,154,115,126,63,208,117,126,63,3,120,126,63,51,122,126,63,98,124,126,63,142,126,126,63,184,128,126,63,224,130,126,63,5,133,126,63,40,135,126,63,73,137,126,63,104,139,126,63,132,141,126,63,159,143,126,63,183,145,126,63,204,147,126,63,224,149,126,63,241,151,126,63,0,154,126,63,13,156,126,63,24,158,126,63,32,160,126,63,38,162,126,63,42,164,126,63,44,166,126,63,44,168,126,63,41,170,126,63,37,172,126,63,30,174,126,63,21,176,126,63,10,178,126,63,253,179,126,63,238,181,126,63,220,183,126,63,201,185,126,63,179,187,126,63,155,189,126,63,129,191,126,63,101,193,126,63,71,195,126,63,39,197,126,63,5,199,126,63,224,200,126,63,186,202,126,63,145,204,126,63,103,206,126,63,58,208,126,63,12,210,126,63,219,211,126,63,168,213,126,63,115,215,126,63,61,217,126,63,4,219,126,63,201,220,126,63,140,222,126,63,77,224,126,63,12,226,126,63,202,227,126,63,133,229,126,63,62,231,126,63,245,232,126,63,170,234,126,63,94,236,126,63,15,238,126,63,190,239,126,63,108,241,126,63,23,243,126,63,193,244,126,63,104,246,126,63,14,248,126,63,178,249,126,63,84,251,126,63,243,252,126,63,145,254,126,63,46,0,127,63,200,1,127,63,96,3,127,63,247,4,127,63,139,6,127,63,30,8,127,63,175,9,127,63,62,11,127,63,203,12,127,63,86,14,127,63,223,15,127,63,103,17,127,63,237,18,127,63,112,20,127,63,242,21,127,63,115,23,127,63,241,24,127,63,110,26,127,63,233,27,127,63,98,29,127,63,217,30,127,63,78,32,127,63,194,33,127,63,52,35,127,63,164,36,127,63],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE+20480);allocate([18,38,127,63,127,39,127,63,234,40,127,63,83,42,127,63,186,43,127,63,32,45,127,63,131,46,127,63,230,47,127,63,70,49,127,63,165,50,127,63,2,52,127,63,93,53,127,63,182,54,127,63,14,56,127,63,100,57,127,63,185,58,127,63,12,60,127,63,93,61,127,63,172,62,127,63,250,63,127,63,70,65,127,63,145,66,127,63,217,67,127,63,33,69,127,63,102,70,127,63,170,71,127,63,236,72,127,63,45,74,127,63,108,75,127,63,169,76,127,63,229,77,127,63,31,79,127,63,88,80,127,63,143,81,127,63,196,82,127,63,248,83,127,63,42,85,127,63,91,86,127,63,138,87,127,63,184,88,127,63,228,89,127,63,14,91,127,63,55,92,127,63,94,93,127,63,132,94,127,63,169,95,127,63,203,96,127,63,237,97,127,63,12,99,127,63,42,100,127,63,71,101,127,63,98,102,127,63,124,103,127,63,148,104,127,63,171,105,127,63,192,106,127,63,212,107,127,63,230,108,127,63,247,109,127,63,6,111,127,63,20,112,127,63,33,113,127,63,44,114,127,63,53,115,127,63,61,116,127,63,68,117,127,63,73,118,127,63,77,119,127,63,79,120,127,63,80,121,127,63,80,122,127,63,78,123,127,63,75,124,127,63,70,125,127,63,64,126,127,63,57,127,127,63,48,128,127,63,38,129,127,63,27,130,127,63,14,131,127,63,0,132,127,63,240,132,127,63,223,133,127,63,205,134,127,63,185,135,127,63,164,136,127,63,142,137,127,63,118,138,127,63,93,139,127,63,67,140,127,63,40,141,127,63,11,142,127,63,237,142,127,63,205,143,127,63,173,144,127,63,139,145,127,63,103,146,127,63,67,147,127,63,29,148,127,63,246,148,127,63,205,149,127,63,164,150,127,63,121,151,127,63,77,152,127,63,31,153,127,63,241,153,127,63,193,154,127,63,144,155,127,63,93,156,127,63,42,157,127,63,245,157,127,63,191,158,127,63,136,159,127,63,79,160,127,63,22,161,127,63,219,161,127,63,159,162,127,63,98,163,127,63,36,164,127,63,228,164,127,63,163,165,127,63,98,166,127,63,31,167,127,63,219,167,127,63,149,168,127,63,79,169,127,63,7,170,127,63,190,170,127,63,117,171,127,63,42,172,127,63,221,172,127,63,144,173,127,63,66,174,127,63,242,174,127,63,162,175,127,63,80,176,127,63,253,176,127,63,169,177,127,63,85,178,127,63,254,178,127,63,167,179,127,63,79,180,127,63,246,180,127,63,156,181,127,63,64,182,127,63,228,182,127,63,134,183,127,63,40,184,127,63,200,184,127,63,103,185,127,63,6,186,127,63,163,186,127,63,63,187,127,63,219,187,127,63,117,188,127,63,14,189,127,63,166,189,127,63,61,190,127,63,212,190,127,63,105,191,127,63,253,191,127,63,144,192,127,63,34,193,127,63,180,193,127,63,68,194,127,63,211,194,127,63,98,195,127,63,239,195,127,63,123,196,127,63,7,197,127,63,145,197,127,63,27,198,127,63,163,198,127,63,43,199,127,63,178,199,127,63,56,200,127,63,189,200,127,63,65,201,127,63,196,201,127,63,70,202,127,63,199,202,127,63,71,203,127,63,199,203,127,63,69,204,127,63,195,204,127,63,64,205,127,63,187,205,127,63,54,206,127,63,177,206,127,63,42,207,127,63,162,207,127,63,26,208,127,63,144,208,127,63,6,209,127,63,123,209,127,63,239,209,127,63,98,210,127,63,213,210,127,63,70,211,127,63,183,211,127,63,39,212,127,63,150,212,127,63,4,213,127,63,114,213,127,63,222,213,127,63,74,214,127,63,181,214,127,63,32,215,127,63,137,215,127,63,242,215,127,63,89,216,127,63,192,216,127,63,39,217,127,63,140,217,127,63,241,217,127,63,85,218,127,63,184,218,127,63,27,219,127,63,124,219,127,63,221,219,127,63,61,220,127,63,157,220,127,63,251,220,127,63,89,221,127,63,183,221,127,63,19,222,127,63,111,222,127,63,202,222,127,63,36,223,127,63,126,223,127,63,215,223,127,63,47,224,127,63,134,224,127,63,221,224,127,63,51,225,127,63,137,225,127,63,221,225,127,63,49,226,127,63,133,226,127,63,215,226,127,63,41,227,127,63,122,227,127,63,203,227,127,63,27,228,127,63,106,228,127,63,185,228,127,63,7,229,127,63,84,229,127,63,161,229,127,63,237,229,127,63,56,230,127,63,131,230,127,63,205,230,127,63,23,231,127,63,96,231,127,63,168,231,127,63,239,231,127,63,54,232,127,63,125,232,127,63,195,232,127,63,8,233,127,63,76,233,127,63,144,233,127,63,212,233,127,63,23,234,127,63,89,234,127,63,154,234,127,63,219,234,127,63,28,235,127,63,92,235,127,63,155,235,127,63,218,235,127,63,24,236,127,63,86,236,127,63,147,236,127,63,207,236,127,63,11,237,127,63,71,237,127,63,130,237,127,63,188,237,127,63,246,237,127,63,47,238,127,63,104,238,127,63,160,238,127,63,216,238,127,63,15,239,127,63,69,239,127,63,123,239,127,63,177,239,127,63,230,239,127,63,27,240,127,63,79,240,127,63,130,240,127,63,182,240,127,63,232,240,127,63,26,241,127,63,76,241,127,63,125,241,127,63,174,241,127,63,222,241,127,63,14,242,127,63,61,242,127,63,108,242,127,63,154,242,127,63,200,242,127,63,245,242,127,63,34,243,127,63,79,243,127,63,123,243,127,63,166,243,127,63,209,243,127,63,252,243,127,63,38,244,127,63,80,244,127,63,121,244,127,63,162,244,127,63,203,244,127,63,243,244,127,63,27,245,127,63,66,245,127,63,105,245,127,63,143,245,127,63,181,245,127,63,219,245,127,63,0,246,127,63,37,246,127,63,73,246,127,63,109,246,127,63,145,246,127,63,180,246,127,63,215,246,127,63,250,246,127,63,28,247,127,63,62,247,127,63,95,247,127,63,128,247,127,63,160,247,127,63,193,247,127,63,225,247,127,63,0,248,127,63,31,248,127,63,62,248,127,63,93,248,127,63,123,248,127,63,152,248,127,63,182,248,127,63,211,248,127,63,240,248,127,63,12,249,127,63,40,249,127,63,68,249,127,63,95,249,127,63,122,249,127,63,149,249,127,63,175,249,127,63,202,249,127,63,227,249,127,63,253,249,127,63,22,250,127,63,47,250,127,63,71,250,127,63,96,250,127,63,120,250,127,63,143,250,127,63,166,250,127,63,190,250,127,63,212,250,127,63,235,250,127,63,1,251,127,63,23,251,127,63,44,251,127,63,66,251,127,63,87,251,127,63,108,251,127,63,128,251,127,63,148,251,127,63,168,251,127,63,188,251,127,63,208,251,127,63,227,251,127,63,246,251,127,63,8,252,127,63,27,252,127,63,45,252,127,63,63,252,127,63,81,252,127,63,98,252,127,63,115,252,127,63,132,252,127,63,149,252,127,63,165,252,127,63,182,252,127,63,198,252,127,63,213,252,127,63,229,252,127,63,244,252,127,63,3,253,127,63,18,253,127,63,33,253,127,63,47,253,127,63,62,253,127,63,76,253,127,63,89,253,127,63,103,253,127,63,116,253,127,63,130,253,127,63,143,253,127,63,155,253,127,63,168,253,127,63,181,253,127,63,193,253,127,63,205,253,127,63,217,253,127,63,228,253,127,63,240,253,127,63,251,253,127,63,6,254,127,63,17,254,127,63,28,254,127,63,38,254,127,63,49,254,127,63,59,254,127,63,69,254,127,63,79,254,127,63,89,254,127,63,98,254,127,63,108,254,127,63,117,254,127,63,126,254,127,63,135,254,127,63,144,254,127,63,152,254,127,63,161,254,127,63,169,254,127,63,177,254,127,63,185,254,127,63,193,254,127,63,201,254,127,63,208,254,127,63,216,254,127,63,223,254,127,63,230,254,127,63,237,254,127,63,244,254,127,63,251,254,127,63,2,255,127,63,8,255,127,63,14,255,127,63,21,255,127,63,27,255,127,63,33,255,127,63,39,255,127,63,45,255,127,63,50,255,127,63,56,255,127,63,61,255,127,63,67,255,127,63,72,255,127,63,77,255,127,63,82,255,127,63,87,255,127,63,92,255,127,63,96,255,127,63,101,255,127,63,105,255,127,63,110,255,127,63,114,255,127,63,118,255,127,63,122,255,127,63,126,255,127,63,130,255,127,63,134,255,127,63,138,255,127,63,142,255,127,63,145,255,127,63,149,255,127,63,152,255,127,63,155,255,127,63,159,255,127,63,162,255,127,63,165,255,127,63,168,255,127,63,171,255,127,63,174,255,127,63,176,255,127,63,179,255,127,63,182,255,127,63,184,255,127,63,187,255,127,63,189,255,127,63,192,255,127,63,194,255,127,63,196,255,127,63,198,255,127,63,201,255,127,63,203,255,127,63,205,255,127,63,207,255,127,63,209,255,127,63,210,255,127,63,212,255,127,63,214,255,127,63,216,255,127,63,217,255,127,63,219,255,127,63,220,255,127,63,222,255,127,63,223,255,127,63,225,255,127,63,226,255,127,63,227,255,127,63,229,255,127,63,230,255,127,63,231,255,127,63,232,255,127,63,233,255,127,63,234,255,127,63,235,255,127,63,236,255,127,63,237,255,127,63,238,255,127,63,239,255,127,63,240,255,127,63,241,255,127,63,241,255,127,63,242,255,127,63,243,255,127,63,244,255,127,63,244,255,127,63,245,255,127,63,246,255,127,63,246,255,127,63,247,255,127,63,247,255,127,63,248,255,127,63,248,255,127,63,249,255,127,63,249,255,127,63,250,255,127,63,250,255,127,63,250,255,127,63,251,255,127,63,251,255,127,63,251,255,127,63,252,255,127,63,252,255,127,63,252,255,127,63,253,255,127,63,253,255,127,63,253,255,127,63,253,255,127,63,254,255,127,63,254,255,127,63,254,255,127,63,254,255,127,63,254,255,127,63,254,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,255,255,127,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,0,0,128,63,62,180,228,51,9,145,243,51,139,178,1,52,60,32,10,52,35,26,19,52,96,169,28,52,167,215,38,52,75,175,49,52,80,59,61,52,112,135,73,52,35,160,86,52,184,146,100,52,85,109,115,52,136,159,129,52,252,11,138,52,147,4,147,52,105,146,156,52,50,191,166,52,63,149,177,52,147,31,189,52,228,105,201,52,173,128,214,52,54,113,228,52,166,73,243,52,136,140,1,53,192,247,9,53,6,239,18,53,118,123,28,53,192,166,38,53,55,123,49,53,218,3,61,53,94,76,73,53,59,97,86,53,185,79,100,53,252,37,115,53,138,121,129,53,134,227,137,53,124,217,146,53,133,100,156,53,82,142,166,53,51,97,177,53,37,232,188,53,220,46,201,53,206,65,214,53,65,46,228,53,87,2,243,53,143,102,1,54,79,207,9,54,245,195,18,54,152,77,28,54,232,117,38,54,50,71,49,54,116,204,60,54,94,17,73,54,101,34,86,54,206,12,100,54,184,222,114,54,151,83,129,54,28,187,137,54,114,174,146,54,175,54,156,54,129,93,166,54,53,45,177,54,199,176,188,54,228,243,200,54,1,3,214,54,96,235,227,54,30,187,242,54,162,64,1,55,235,166,9,55,241,152,18,55,201,31,28,55,30,69,38,55,61,19,49,55,30,149,60,55,111,214,72,55,162,227,85,55,247,201,99,55,137,151,114,55,175,45,129,55,190,146,137,55,116,131,146,55,230,8,156,55,190,44,166,55,71,249,176,55,121,121,188,55,254,184,200,55,71,196,213,55,146,168,227,55,248,115,242,55,192,26,1,56,147,126,9,56,249,109,18,56,6,242,27,56,98,20,38,56,86,223,48,56,216,93,60,56,146,155,72,56,242,164,85,56,51,135,99,56,110,80,114,56,211,7,129,56,107,106,137,56,130,88,146,56,42,219,155,56,9,252,165,56,104,197,176,56,59,66,188,56,41,126,200,56,160,133,213,56,217,101,227,56,232,44,242,56,233,244,0,57,70,86,9,57,14,67,18,57,81,196,27,57,181,227,37,57,127,171,48,57,162,38,60,57,197,96,72,57,83,102,85,57,131,68,99,57,104,9,114,57,1,226,128,57,36,66,137,57,157,45,146,57,123,173,155,57,99,203,165,57,153,145,176,57,13,11,188,57,102,67,200,57,11,71,213,57,50,35,227,57,237,229,241,57,29,207,0,58,5,46,9,58,48,24,18,58,169,150,27,58,21,179,37,58,183,119,48,58,124,239,59,58,10,38,72,58,199,39,85,58,230,1,99,58,120,194,113,58,59,188,128,58,233,25,137,58,198,2,146,58,219,127,155,58,203,154,165,58,216,93,176,58,239,211,187,58,179,8,200,58,136,8,213,58,159,224,226,58,7,159,241,58,92,169,0,59,208,5,9,59,94,237,17,59,15,105,27,59,132,130,37,59,253,67,48,59,103,184,59,59,97,235,71,59,77,233,84,59,93,191,98,59,156,123,113,59,127,150,128,59,186,241,136,59,249,215,145,59,71,82,155,59,65,106,165,59,39,42,176,59,226,156,187,59,18,206,199,59,23,202,212,59,32,158,226,59,53,88,241,59,166,131,0,60,167,221,8,60,152,194,17,60,130,59,27,60,1,82,37,60,84,16,48,60,97,129,59,60,200,176,71,60,229,170,84,60,232,124,98,60,212,52,113,60,207,112,128,60,150,201,136,60,58,173,145,60,192,36,155,60,197,57,165,60,133,246,175,60,229,101,187,60,130,147,199,60,185,139,212,60,180,91,226,60,121,17,241,60,251,93,0,61,137,181,8,61,223,151,17,61,2,14,27,61,141,33,37,61,185,220,47,61,109,74,59,61,64,118,71,61,145,108,84,61,133,58,98,61,34,238,112,61,42,75,128,61,127,161,136,61,136,130,145,61,72,247,154,61,88,9,165,61,242,194,175,61,248,46,187,61,3,89,199,61,109,77,212,61,92,25,226,61,209,202,240,61,91,56,0,62,119,141,8,62,51,109,17,62,144,224,26,62,39,241,36,62,46,169,47,62,135,19,59,62,202,59,71,62,77,46,84,62,55,248,97,62,132,167,112,62,143,37,128,62,115,121,136,62,226,87,145,62,220,201,154,62,249,216,164,62,109,143,175,62,27,248,186,62,149,30,199,62,51,15,212,62,23,215,225,62,61,132,240,62,198,18,0,63,114,101,8,63,147,66,17,63,43,179,26,63,206,192,36,63,177,117,47,63,178,220,58,63,101,1,71,63,29,240,83,63,251,181,97,63,251,96,112,63,0,0,128,63,84,1,0,0,116,1,0,0,148,1,0,0,56,1,0,0,28,1,0,0,180,1,0,0,4,0,0,0,2,0,0,0,3,0,0,0,5,0,0,0,0,0,76,194,0,0,80,194,0,0,84,194,0,0,88,194,0,0,92,194,0,0,96,194,0,0,100,194,0,0,104,194,0,0,108,194,0,0,112,194,0,0,116,194,0,0,120,194,0,0,124,194,0,0,128,194,0,0,130,194,0,0,132,194,0,0,134,194,0,0,136,194,0,0,138,194,0,0,140,194,0,0,142,194,0,0,144,194,0,0,146,194,0,0,148,194,0,0,150,194,0,0,152,194,0,0,154,194,0,0,156,194,0,0,160,194,0,0,162,194,0,0,164,194,0,0,166,194,0,0,168,194,0,0,170,194,0,0,172,194,0,0,174,194,0,0,176,194,0,0,176,194,0,0,178,194,0,0,178,194,0,0,180,194,0,0,182,194,0,0,182,194,0,0,184,194,0,0,186,194,0,0,188,194,0,0,190,194,0,0,192,194,0,0,192,194,0,0,194,194,0,0,196,194,0,0,196,194,0,0,198,194,0,0,198,194,0,0,200,194,0,0,200,194,0,0,202,194,0,0,204,194,0,0,206,194,0,0,208,194,0,0,212,194,0,0,214,194,0,0,214,194,0,0,214,194,0,0,214,194,0,0,210,194,0,0,206,194,0,0,204,194,0,0,202,194,0,0,198,194,0,0,196,194,0,0,192,194,0,0,190,194,0,0,190,194,0,0,192,194,0,0,194,194,0,0,192,194,0,0,190,194,0,0,186,194,0,0,180,194,0,0,160,194,0,0,140,194,0,0,72,194,0,0,32,194,0,0,240,193,0,0,240,193,0,0,240,193,0,0,240,193,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,112,194,0,0,120,194,0,0,120,194,0,0,130,194,0,0,146,194,0,0,138,194,0,0,136,194,0,0,136,194,0,0,134,194,0,0,140,194,0,0,140,194,0,0,144,194,0,0,148,194,0,0,150,194,0,0,158,194,0,0,158,194,0,0,160,194,0,0,166,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,84,194,0,0,116,194,0,0,132,194,0,0,132,194,0,0,136,194,0,0,134,194,0,0,140,194,0,0,152,194,0,0,152,194,0,0,144,194,0,0,146,194,0,0,150,194,0,0,152,194,0,0,156,194,0,0,158,194,0,0,166,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,20,194,0,0,20,194,0,0,20,194,0,0,20,194,0,0,20,194,0,0,20,194,0,0,20,194,0,0,20,194,0,0,24,194,0,0,32,194,0,0,40,194,0,0,56,194,0,0,64,194,0,0,84,194,0,0,92,194,0,0,120,194,0,0,130,194,0,0,104,194,0,0,96,194,0,0,96,194,0,0,116,194,0,0,112,194,0,0,130,194,0,0,134,194,0,0,138,194,0,0,142,194,0,0,154,194,0,0,154,194,0,0,156,194,0,0,160,194,0,0,164,194,0,0,168,194,0,0,176,194,0,0,186,194,0,0,196,194,0,0,212,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,200,193,0,0,208,193,0,0,216,193,0,0,232,193,0,0,0,194,0,0,24,194,0,0,64,194,0,0,80,194,0,0,80,194,0,0,72,194,0,0,64,194,0,0,64,194,0,0,76,194,0,0,80,194,0,0,88,194,0,0,112,194,0,0,134,194,0,0,134,194,0,0,132,194,0,0,136,194,0,0,138,194,0,0,146,194,0,0,146,194,0,0,152,194,0,0,160,194,0,0,162,194,0,0,162,194,0,0,170,194,0,0,170,194,0,0,172,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,128,193,0,0,128,193,0,0,128,193,0,0,128,193,0,0,128,193,0,0,128,193,0,0,128,193,0,0,128,193,0,0,136,193,0,0,152,193,0,0,160,193,0,0,176,193,0,0,208,193,0,0,224,193,0,0,248,193,0,0,32,194,0,0,60,194,0,0,28,194,0,0,28,194,0,0,32,194,0,0,40,194,0,0,44,194,0,0,60,194,0,0,76,194,0,0,100,194,0,0,80,194,0,0,92,194,0,0,92,194,0,0,112,194,0,0,104,194,0,0,120,194,0,0,124,194,0,0,140,194,0,0,134,194,0,0,138,194,0,0,144,194,0,0,146,194,0,0,154,194,0,0,160,194,0,0,164,194,0,0,166,194,0,0,174,194,0,0,180,194,0,0,188,194,0,0,196,194,0,0,208,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,0,193,0,0,32,193,0,0,48,193,0,0,112,193,0,0,152,193,0,0,200,193,0,0,240,193,0,0,8,194,0,0,248,193,0,0,240,193,0,0,248,193,0,0,232,193,0,0,0,194,0,0,12,194,0,0,40,194,0,0,64,194,0,0,40,194,0,0,48,194,0,0,56,194,0,0,72,194,0,0,72,194,0,0,76,194,0,0,80,194,0,0,108,194,0,0,88,194,0,0,92,194,0,0,92,194,0,0,104,194,0,0,120,194,0,0,124,194,0,0,132,194,0,0,144,194,0,0,146,194,0,0,152,194,0,0,150,194,0,0,156,194,0,0,160,194,0,0,160,194,0,0,162,194,0,0,168,194,0,0,176,194,0,0,180,194,0,0,188,194,0,0,196,194,0,0,202,194,0,0,212,194,0,0,220,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,134,194,0,0,134,194,0,0,134,194,0,0,152,194,0,0,144,194,0,0,142,194,0,0,148,194,0,0,152,194,0,0,152,194,0,0,150,194,0,0,156,194,0,0,158,194,0,0,158,194,0,0,162,194,0,0,166,194,0,0,172,194,0,0,178,194,0,0,186,194,0,0,194,194,0,0,200,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,64,194,0,0,76,194,0,0,92,194,0,0,108,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,134,194,0,0,132,194,0,0,136,194,0,0,138,194,0,0,140,194,0,0,148,194,0,0,158,194,0,0,154,194,0,0,154,194,0,0,156,194,0,0,160,194,0,0,162,194,0,0,164,194,0,0,168,194,0,0,172,194,0,0,176,194,0,0,182,194,0,0,190,194,0,0,200,194,0,0,216,194,0,0,232,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,20,194,0,0,20,194,0,0,36,194,0,0,48,194,0,0,64,194,0,0,76,194,0,0,104,194,0,0,120,194,0,0,112,194,0,0,100,194,0,0,108,194,0,0,108,194,0,0,112,194,0,0,124,194,0,0,130,194,0,0,144,194,0,0,142,194,0,0,140,194,0,0,144,194,0,0,148,194,0,0,154,194,0,0,152,194,0,0,156,194,0,0,162,194,0,0,162,194,0,0,160,194,0,0,166,194,0,0,172,194,0,0,182,194,0,0,192,194,0,0,200,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,240,193,0,0,0,194,0,0,0,194,0,0,4,194,0,0,12,194,0,0,36,194,0,0,68,194,0,0,72,194,0,0,68,194,0,0,60,194,0,0,64,194,0,0,64,194,0,0,80,194,0,0,76,194,0,0,100,194,0,0,130,194,0,0,116,194,0,0,108,194,0,0,116,194,0,0,128,194,0,0,138,194,0,0,140,194,0,0,148,194,0,0,154,194,0,0,154,194,0,0,156,194,0,0,162,194,0,0,168,194,0,0,170,194,0,0,174,194,0,0,180,194,0,0,184,194,0,0,192,194,0,0,200,194,0,0,214,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,152,193,0,0,152,193,0,0,152,193,0,0,152,193,0,0,152,193,0,0,152,193,0,0,152,193,0,0,152,193,0,0,160,193,0,0,168,193,0,0,184,193,0,0,216,193,0,0,240,193,0,0,12,194,0,0,16,194,0,0,36,194,0,0,56,194,0,0,48,194,0,0,40,194,0,0,32,194,0,0,36,194,0,0,36,194,0,0,44,194,0,0,64,194,0,0,92,194,0,0,84,194,0,0,80,194,0,0,84,194,0,0,96,194,0,0,108,194,0,0,104,194,0,0,112,194,0,0,134,194,0,0,132,194,0,0,138,194,0,0,142,194,0,0,144,194,0,0,150,194,0,0,158,194,0,0,162,194,0,0,168,194,0,0,174,194,0,0,180,194,0,0,186,194,0,0,194,194,0,0,202,194,0,0,214,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,16,193,0,0,16,193,0,0,16,193,0,0,16,193,0,0,16,193,0,0,16,193,0,0,16,193,0,0,16,193,0,0,48,193,0,0,64,193,0,0,64,193,0,0,112,193,0,0,128,193,0,0,160,193,0,0,184,193,0,0,240,193,0,0,20,194,0,0,8,194,0,0,4,194,0,0,8,194,0,0,248,193,0,0,0,194,0,0,0,194,0,0,24,194,0,0,60,194,0,0,48,194,0,0,36,194,0,0,32,194,0,0,60,194,0,0,68,194,0,0,56,194,0,0,56,194,0,0,104,194,0,0,72,194,0,0,72,194,0,0,88,194,0,0,104,194,0,0,120,194,0,0,128,194,0,0,134,194,0,0,134,194,0,0,140,194,0,0,144,194,0,0,152,194,0,0,158,194,0,0,166,194,0,0,174,194,0,0,182,194,0,0,192,194,0,0,200,194,0,0,208,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,124,194,0,0,128,194,0,0,132,194,0,0,134,194,0,0,132,194,0,0,136,194,0,0,150,194,0,0,144,194,0,0,152,194,0,0,150,194,0,0,152,194,0,0,156,194,0,0,158,194,0,0,164,194,0,0,168,194,0,0,170,194,0,0,180,194,0,0,188,194,0,0,202,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,108,194,0,0,112,194,0,0,112,194,0,0,116,194,0,0,124,194,0,0,132,194,0,0,142,194,0,0,136,194,0,0,140,194,0,0,140,194,0,0,142,194,0,0,144,194,0,0,144,194,0,0,150,194,0,0,162,194,0,0,156,194,0,0,158,194,0,0,164,194,0,0,166,194,0,0,172,194,0,0,180,194,0,0,194,194,0,0,206,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,84,194,0,0,88,194,0,0,92,194,0,0,100,194,0,0,96,194,0,0,100,194,0,0,92,194,0,0,116,194,0,0,130,194,0,0,112,194,0,0,112,194,0,0,120,194,0,0,124,194,0,0,124,194,0,0,132,194,0,0,136,194,0,0,148,194,0,0,146,194,0,0,150,194,0,0,150,194,0,0,156,194,0,0,160,194,0,0,160,194,0,0,164,194,0,0,170,194,0,0,180,194,0,0,192,194,0,0,202,194,0,0,216,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,56,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,60,194,0,0,64,194,0,0,76,194,0,0,100,194,0,0,76,194,0,0,68,194,0,0,72,194,0,0,76,194,0,0,84,194,0,0,88,194,0,0,108,194,0,0,132,194,0,0,112,194,0,0,120,194,0,0,134,194,0,0,134,194,0,0,140,194,0,0,144,194,0,0,150,194,0,0,152,194,0,0,156,194,0,0,162,194,0,0,170,194,0,0,176,194,0,0,188,194,0,0,194,194,0,0,208,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,16,194,0,0,28,194,0,0,36,194,0,0,40,194,0,0,40,194,0,0,28,194,0,0,24,194,0,0,36,194,0,0,44,194,0,0,80,194,0,0,48,194,0,0,32,194,0,0,28,194,0,0,20,194,0,0,20,194,0,0,32,194,0,0,60,194,0,0,88,194,0,0,72,194,0,0,64,194,0,0,72,194,0,0,92,194,0,0,116,194,0,0,108,194,0,0,120,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,138,194,0,0,138,194,0,0,146,194,0,0,148,194,0,0,148,194,0,0,150,194,0,0,154,194,0,0,158,194,0,0,164,194,0,0,174,194,0,0,182,194,0,0,190,194,0,0,200,194,0,0,216,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,224,193,0,0,208,193,0,0,192,193,0,0,176,193,0,0,160,193,0,0,160,193,0,0,184,193,0,0,232,193,0,0,240,193,0,0,248,193,0,0,224,193,0,0,216,193,0,0,224,193,0,0,224,193,0,0,224,193,0,0,12,194,0,0,32,194,0,0,4,194,0,0,0,194,0,0,232,193,0,0,240,193,0,0,240,193,0,0,240,193,0,0,20,194,0,0,52,194,0,0,36,194,0,0,20,194,0,0,24,194,0,0,52,194,0,0,60,194,0,0,60,194,0,0,64,194,0,0,84,194,0,0,68,194,0,0,64,194,0,0,72,194,0,0,68,194,0,0,68,194,0,0,76,194,0,0,80,194,0,0,104,194,0,0,96,194,0,0,100,194,0,0,96,194,0,0,112,194,0,0,116,194,0,0,120,194,0,0,140,194,0,0,144,194,0,0,148,194,0,0,156,194,0,0,166,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,212,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,210,194,0,0,200,194,0,0,190,194,0,0,182,194,0,0,174,194,0,0,166,194,0,0,160,194,0,0,156,194,0,0,152,194,0,0,156,194,0,0,156,194,0,0,162,194,0,0,166,194,0,0,170,194,0,0,172,194,0,0,170,194,0,0,172,194,0,0,174,194,0,0,180,194,0,0,194,194,0,0,214,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,162,194,0,0,154,194,0,0,146,194,0,0,140,194,0,0,134,194,0,0,134,194,0,0,136,194,0,0,150,194,0,0,146,194,0,0,140,194,0,0,138,194,0,0,140,194,0,0,144,194,0,0,150,194,0,0,158,194,0,0,168,194,0,0,166,194,0,0,168,194,0,0,172,194,0,0,176,194,0,0,178,194,0,0,178,194,0,0,186,194,0,0,196,194,0,0,210,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,160,194,0,0,152,194,0,0,142,194,0,0,136,194,0,0,136,194,0,0,130,194,0,0,124,194,0,0,124,194,0,0,120,194,0,0,120,194,0,0,128,194,0,0,130,194,0,0,128,194,0,0,116,194,0,0,120,194,0,0,124,194,0,0,128,194,0,0,132,194,0,0,136,194,0,0,146,194,0,0,146,194,0,0,148,194,0,0,150,194,0,0,152,194,0,0,162,194,0,0,166,194,0,0,170,194,0,0,176,194,0,0,178,194,0,0,184,194,0,0,190,194,0,0,200,194,0,0,216,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,160,194,0,0,150,194,0,0,142,194,0,0,136,194,0,0,130,194,0,0,124,194,0,0,120,194,0,0,116,194,0,0,116,194,0,0,116,194,0,0,116,194,0,0,108,194,0,0,96,194,0,0,100,194,0,0,84,194,0,0,72,194,0,0,104,194,0,0,80,194,0,0,72,194,0,0,72,194,0,0,80,194,0,0,84,194,0,0,88,194,0,0,104,194,0,0,134,194,0,0,124,194,0,0,134,194,0,0,136,194,0,0,144,194,0,0,150,194,0,0,156,194,0,0,160,194,0,0,162,194,0,0,162,194,0,0,164,194,0,0,170,194,0,0,178,194,0,0,180,194,0,0,186,194,0,0,194,194,0,0,202,194,0,0,214,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,130,194,0,0,116,194,0,0,108,194,0,0,100,194,0,0,96,194,0,0,92,194,0,0,92,194,0,0,96,194,0,0,96,194,0,0,100,194,0,0,92,194,0,0,84,194,0,0,80,194,0,0,60,194,0,0,48,194,0,0,48,194,0,0,72,194,0,0,48,194,0,0,36,194,0,0,28,194,0,0,28,194,0,0,40,194,0,0,32,194,0,0,56,194,0,0,76,194,0,0,68,194,0,0,72,194,0,0,84,194,0,0,88,194,0,0,124,194,0,0,112,194,0,0,116,194,0,0,120,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,140,194,0,0,146,194,0,0,148,194,0,0,150,194,0,0,152,194,0,0,150,194,0,0,158,194,0,0,170,194,0,0,178,194,0,0,182,194,0,0,192,194,0,0,204,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,80,194,0,0,72,194,0,0,68,194,0,0,68,194,0,0,64,194,0,0,64,194,0,0,64,194,0,0,68,194,0,0,72,194,0,0,72,194,0,0,68,194,0,0,56,194,0,0,44,194,0,0,28,194,0,0,12,194,0,0,4,194,0,0,24,194,0,0,16,194,0,0,0,194,0,0,232,193,0,0,0,194,0,0,0,194,0,0,0,194,0,0,12,194,0,0,48,194,0,0,28,194,0,0,24,194,0,0,24,194,0,0,56,194,0,0,72,194,0,0,52,194,0,0,56,194,0,0,84,194,0,0,72,194,0,0,72,194,0,0,72,194,0,0,88,194,0,0,88,194,0,0,84,194,0,0,84,194,0,0,96,194,0,0,100,194,0,0,108,194,0,0,132,194,0,0,140,194,0,0,144,194,0,0,148,194,0,0,158,194,0,0,166,194,0,0,170,194,0,0,180,194,0,0,194,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,172,194,0,0,160,194,0,0,150,194,0,0,150,194,0,0,158,194,0,0,160,194,0,0,158,194,0,0,160,194,0,0,162,194,0,0,164,194,0,0,176,194,0,0,190,194,0,0,206,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,176,194,0,0,166,194,0,0,158,194,0,0,156,194,0,0,150,194,0,0,142,194,0,0,134,194,0,0,136,194,0,0,146,194,0,0,146,194,0,0,144,194,0,0,146,194,0,0,150,194,0,0,154,194,0,0,160,194,0,0,164,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,214,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,210,194,0,0,202,194,0,0,192,194,0,0,180,194,0,0,172,194,0,0,162,194,0,0,154,194,0,0,146,194,0,0,138,194,0,0,132,194,0,0,116,194,0,0,120,194,0,0,132,194,0,0,128,194,0,0,120,194,0,0,130,194,0,0,132,194,0,0,140,194,0,0,144,194,0,0,152,194,0,0,162,194,0,0,160,194,0,0,168,194,0,0,180,194,0,0,190,194,0,0,204,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,206,194,0,0,194,194,0,0,184,194,0,0,176,194,0,0,166,194,0,0,158,194,0,0,148,194,0,0,140,194,0,0,132,194,0,0,108,194,0,0,84,194,0,0,104,194,0,0,120,194,0,0,92,194,0,0,88,194,0,0,88,194,0,0,88,194,0,0,104,194,0,0,116,194,0,0,120,194,0,0,144,194,0,0,140,194,0,0,144,194,0,0,150,194,0,0,156,194,0,0,160,194,0,0,162,194,0,0,160,194,0,0,166,194,0,0,166,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,214,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,160,194,0,0,150,194,0,0,140,194,0,0,132,194,0,0,120,194,0,0,96,194,0,0,64,194,0,0,48,194,0,0,64,194,0,0,56,194,0,0,56,194,0,0,44,194,0,0,56,194,0,0,64,194,0,0,64,194,0,0,76,194,0,0,104,194,0,0,104,194,0,0,108,194,0,0,112,194,0,0,120,194,0,0,120,194,0,0,116,194,0,0,116,194,0,0,130,194,0,0,128,194,0,0,130,194,0,0,136,194,0,0,140,194,0,0,148,194],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE+30720);allocate([0,0,150,194,0,0,156,194,0,0,162,194,0,0,172,194,0,0,190,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,160,194,0,0,150,194,0,0,140,194,0,0,130,194,0,0,116,194,0,0,92,194,0,0,68,194,0,0,28,194,0,0,4,194,0,0,32,194,0,0,12,194,0,0,0,194,0,0,24,194,0,0,32,194,0,0,4,194,0,0,12,194,0,0,20,194,0,0,56,194,0,0,36,194,0,0,52,194,0,0,48,194,0,0,56,194,0,0,40,194,0,0,52,194,0,0,56,194,0,0,80,194,0,0,72,194,0,0,72,194,0,0,72,194,0,0,88,194,0,0,88,194,0,0,92,194,0,0,100,194,0,0,120,194,0,0,128,194,0,0,132,194,0,0,136,194,0,0,140,194,0,0,152,194,0,0,162,194,0,0,180,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,196,194,0,0,180,194,0,0,170,194,0,0,164,194,0,0,166,194,0,0,160,194,0,0,156,194,0,0,168,194,0,0,158,194,0,0,160,194,0,0,166,194,0,0,174,194,0,0,178,194,0,0,182,194,0,0,186,194,0,0,198,194,0,0,212,194,0,0,234,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,196,194,0,0,180,194,0,0,170,194,0,0,160,194,0,0,150,194,0,0,140,194,0,0,136,194,0,0,148,194,0,0,144,194,0,0,148,194,0,0,154,194,0,0,160,194,0,0,164,194,0,0,170,194,0,0,174,194,0,0,184,194,0,0,178,194,0,0,182,194,0,0,190,194,0,0,200,194,0,0,212,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,196,194,0,0,180,194,0,0,166,194,0,0,150,194,0,0,142,194,0,0,124,194,0,0,128,194,0,0,134,194,0,0,120,194,0,0,128,194,0,0,134,194,0,0,140,194,0,0,146,194,0,0,154,194,0,0,162,194,0,0,168,194,0,0,166,194,0,0,170,194,0,0,178,194,0,0,180,194,0,0,186,194,0,0,196,194,0,0,208,194,0,0,218,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,206,194,0,0,192,194,0,0,176,194,0,0,162,194,0,0,150,194,0,0,136,194,0,0,104,194,0,0,88,194,0,0,96,194,0,0,88,194,0,0,96,194,0,0,96,194,0,0,104,194,0,0,112,194,0,0,124,194,0,0,132,194,0,0,148,194,0,0,138,194,0,0,144,194,0,0,144,194,0,0,150,194,0,0,148,194,0,0,154,194,0,0,162,194,0,0,162,194,0,0,164,194,0,0,168,194,0,0,174,194,0,0,186,194,0,0,192,194,0,0,198,194,0,0,208,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,204,194,0,0,192,194,0,0,182,194,0,0,170,194,0,0,160,194,0,0,148,194,0,0,136,194,0,0,112,194,0,0,76,194,0,0,56,194,0,0,64,194,0,0,56,194,0,0,44,194,0,0,52,194,0,0,60,194,0,0,60,194,0,0,68,194,0,0,64,194,0,0,96,194,0,0,84,194,0,0,92,194,0,0,104,194,0,0,100,194,0,0,124,194,0,0,104,194,0,0,112,194,0,0,132,194,0,0,128,194,0,0,134,194,0,0,140,194,0,0,140,194,0,0,148,194,0,0,154,194,0,0,168,194,0,0,172,194,0,0,178,194,0,0,182,194,0,0,186,194,0,0,188,194,0,0,202,194,0,0,218,194,0,0,236,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,176,194,0,0,166,194,0,0,156,194,0,0,146,194,0,0,136,194,0,0,112,194,0,0,84,194,0,0,48,194,0,0,12,194,0,0,24,194,0,0,24,194,0,0,8,194,0,0,8,194,0,0,16,194,0,0,32,194,0,0,36,194,0,0,48,194,0,0,76,194,0,0,52,194,0,0,56,194,0,0,60,194,0,0,56,194,0,0,88,194,0,0,72,194,0,0,68,194,0,0,72,194,0,0,72,194,0,0,72,194,0,0,76,194,0,0,88,194,0,0,100,194,0,0,104,194,0,0,112,194,0,0,132,194,0,0,132,194,0,0,132,194,0,0,128,194,0,0,130,194,0,0,136,194,0,0,154,194,0,0,164,194,0,0,174,194,0,0,190,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,204,194,0,0,194,194,0,0,184,194,0,0,174,194,0,0,166,194,0,0,156,194,0,0,150,194,0,0,164,194,0,0,158,194,0,0,166,194,0,0,170,194,0,0,178,194,0,0,184,194,0,0,190,194,0,0,196,194,0,0,202,194,0,0,210,194,0,0,218,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,212,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,172,194,0,0,162,194,0,0,156,194,0,0,148,194,0,0,138,194,0,0,148,194,0,0,148,194,0,0,152,194,0,0,158,194,0,0,166,194,0,0,168,194,0,0,172,194,0,0,178,194,0,0,184,194,0,0,194,194,0,0,186,194,0,0,200,194,0,0,206,194,0,0,214,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,212,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,174,194,0,0,166,194,0,0,160,194,0,0,150,194,0,0,138,194,0,0,112,194,0,0,132,194,0,0,132,194,0,0,136,194,0,0,140,194,0,0,148,194,0,0,156,194,0,0,158,194,0,0,162,194,0,0,162,194,0,0,166,194,0,0,168,194,0,0,174,194,0,0,186,194,0,0,192,194,0,0,198,194,0,0,206,194,0,0,214,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,178,194,0,0,170,194,0,0,164,194,0,0,156,194,0,0,142,194,0,0,120,194,0,0,92,194,0,0,104,194,0,0,104,194,0,0,88,194,0,0,88,194,0,0,92,194,0,0,108,194,0,0,116,194,0,0,120,194,0,0,140,194,0,0,132,194,0,0,132,194,0,0,134,194,0,0,140,194,0,0,144,194,0,0,150,194,0,0,156,194,0,0,168,194,0,0,168,194,0,0,168,194,0,0,176,194,0,0,182,194,0,0,180,194,0,0,190,194,0,0,196,194,0,0,204,194,0,0,206,194,0,0,212,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,188,194,0,0,180,194,0,0,174,194,0,0,164,194,0,0,158,194,0,0,146,194,0,0,134,194,0,0,104,194,0,0,60,194,0,0,72,194,0,0,52,194,0,0,36,194,0,0,52,194,0,0,64,194,0,0,48,194,0,0,48,194,0,0,68,194,0,0,88,194,0,0,76,194,0,0,64,194,0,0,60,194,0,0,68,194,0,0,72,194,0,0,76,194,0,0,100,194,0,0,104,194,0,0,112,194,0,0,124,194,0,0,138,194,0,0,140,194,0,0,138,194,0,0,142,194,0,0,148,194,0,0,156,194,0,0,164,194,0,0,180,194,0,0,190,194,0,0,202,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,202,194,0,0,194,194,0,0,186,194,0,0,180,194,0,0,170,194,0,0,160,194,0,0,154,194,0,0,144,194,0,0,130,194,0,0,96,194,0,0,64,194,0,0,20,194,0,0,32,194,0,0,16,194,0,0,8,194,0,0,32,194,0,0,72,194,0,0,60,194,0,0,24,194,0,0,36,194,0,0,60,194,0,0,24,194,0,0,12,194,0,0,28,194,0,0,24,194,0,0,44,194,0,0,32,194,0,0,52,194,0,0,72,194,0,0,52,194,0,0,48,194,0,0,60,194,0,0,72,194,0,0,92,194,0,0,64,194,0,0,64,194,0,0,80,194,0,0,132,194,0,0,140,194,0,0,152,194,0,0,164,194,0,0,180,194,0,0,194,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,172,194,0,0,158,194,0,0,152,194,0,0,166,194,0,0,162,194,0,0,170,194,0,0,174,194,0,0,178,194,0,0,186,194,0,0,196,194,0,0,204,194,0,0,214,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,172,194,0,0,158,194,0,0,142,194,0,0,154,194,0,0,148,194,0,0,154,194,0,0,158,194,0,0,162,194,0,0,168,194,0,0,170,194,0,0,180,194,0,0,184,194,0,0,186,194,0,0,184,194,0,0,196,194,0,0,202,194,0,0,216,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,206,194,0,0,196,194,0,0,186,194,0,0,174,194,0,0,156,194,0,0,136,194,0,0,130,194,0,0,132,194,0,0,120,194,0,0,130,194,0,0,134,194,0,0,140,194,0,0,146,194,0,0,150,194,0,0,156,194,0,0,164,194,0,0,164,194,0,0,166,194,0,0,168,194,0,0,182,194,0,0,186,194,0,0,196,194,0,0,204,194,0,0,212,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,164,194,0,0,148,194,0,0,120,194,0,0,100,194,0,0,104,194,0,0,96,194,0,0,76,194,0,0,80,194,0,0,80,194,0,0,88,194,0,0,88,194,0,0,104,194,0,0,132,194,0,0,108,194,0,0,112,194,0,0,124,194,0,0,132,194,0,0,138,194,0,0,146,194,0,0,158,194,0,0,166,194,0,0,168,194,0,0,160,194,0,0,162,194,0,0,162,194,0,0,164,194,0,0,176,194,0,0,184,194,0,0,196,194,0,0,210,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,204,194,0,0,194,194,0,0,184,194,0,0,168,194,0,0,158,194,0,0,138,194,0,0,100,194,0,0,60,194,0,0,80,194,0,0,60,194,0,0,48,194,0,0,52,194,0,0,72,194,0,0,80,194,0,0,40,194,0,0,40,194,0,0,84,194,0,0,44,194,0,0,44,194,0,0,64,194,0,0,76,194,0,0,96,194,0,0,92,194,0,0,80,194,0,0,100,194,0,0,108,194,0,0,116,194,0,0,120,194,0,0,134,194,0,0,142,194,0,0,156,194,0,0,166,194,0,0,172,194,0,0,188,194,0,0,196,194,0,0,206,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,190,194,0,0,180,194,0,0,168,194,0,0,156,194,0,0,140,194,0,0,116,194,0,0,76,194,0,0,36,194,0,0,32,194,0,0,24,194,0,0,32,194,0,0,56,194,0,0,80,194,0,0,76,194,0,0,36,194,0,0,32,194,0,0,56,194,0,0,32,194,0,0,24,194,0,0,24,194,0,0,36,194,0,0,56,194,0,0,36,194,0,0,56,194,0,0,60,194,0,0,44,194,0,0,44,194,0,0,52,194,0,0,36,194,0,0,52,194,0,0,96,194,0,0,134,194,0,0,136,194,0,0,166,194,0,0,174,194,0,0,180,194,0,0,190,194,0,0,204,194,0,0,214,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,218,194,0,0,210,194,0,0,202,194,0,0,192,194,0,0,182,194,0,0,168,194,0,0,154,194,0,0,164,194,0,0,164,194,0,0,170,194,0,0,178,194,0,0,188,194,0,0,200,194,0,0,212,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,212,194,0,0,206,194,0,0,196,194,0,0,184,194,0,0,170,194,0,0,160,194,0,0,142,194,0,0,150,194,0,0,144,194,0,0,152,194,0,0,160,194,0,0,168,194,0,0,172,194,0,0,178,194,0,0,186,194,0,0,200,194,0,0,214,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,208,194,0,0,202,194,0,0,194,194,0,0,184,194,0,0,176,194,0,0,168,194,0,0,160,194,0,0,128,194,0,0,132,194,0,0,124,194,0,0,128,194,0,0,132,194,0,0,138,194,0,0,146,194,0,0,154,194,0,0,166,194,0,0,166,194,0,0,172,194,0,0,182,194,0,0,196,194,0,0,208,194,0,0,222,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,208,194,0,0,202,194,0,0,194,194,0,0,184,194,0,0,180,194,0,0,168,194,0,0,148,194,0,0,100,194,0,0,104,194,0,0,80,194,0,0,92,194,0,0,88,194,0,0,72,194,0,0,80,194,0,0,72,194,0,0,80,194,0,0,124,194,0,0,120,194,0,0,138,194,0,0,152,194,0,0,154,194,0,0,156,194,0,0,156,194,0,0,158,194,0,0,164,194,0,0,176,194,0,0,188,194,0,0,200,194,0,0,212,194,0,0,222,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,212,194,0,0,204,194,0,0,196,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,166,194,0,0,156,194,0,0,140,194,0,0,72,194,0,0,72,194,0,0,36,194,0,0,48,194,0,0,68,194,0,0,60,194,0,0,72,194,0,0,72,194,0,0,48,194,0,0,92,194,0,0,56,194,0,0,60,194,0,0,64,194,0,0,64,194,0,0,88,194,0,0,68,194,0,0,68,194,0,0,104,194,0,0,120,194,0,0,142,194,0,0,162,194,0,0,174,194,0,0,184,194,0,0,194,194,0,0,204,194,0,0,216,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,212,194,0,0,204,194,0,0,196,194,0,0,190,194,0,0,180,194,0,0,170,194,0,0,166,194,0,0,156,194,0,0,140,194,0,0,52,194,0,0,44,194,0,0,36,194,0,0,60,194,0,0,72,194,0,0,76,194,0,0,72,194,0,0,68,194,0,0,52,194,0,0,60,194,0,0,36,194,0,0,48,194,0,0,36,194,0,0,28,194,0,0,44,194,0,0,24,194,0,0,20,194,0,0,32,194,0,0,36,194,0,0,48,194,0,0,72,194,0,0,104,194,0,0,130,194,0,0,146,194,0,0,158,194,0,0,170,194,0,0,184,194,0,0,194,194,0,0,202,194,0,0,210,194,0,0,218,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,200,194,0,0,190,194,0,0,174,194,0,0,162,194,0,0,170,194,0,0,166,194,0,0,176,194,0,0,186,194,0,0,200,194,0,0,214,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,202,194,0,0,190,194,0,0,176,194,0,0,166,194,0,0,152,194,0,0,146,194,0,0,144,194,0,0,158,194,0,0,168,194,0,0,180,194,0,0,190,194,0,0,200,194,0,0,210,194,0,0,220,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,208,194,0,0,196,194,0,0,184,194,0,0,174,194,0,0,162,194,0,0,140,194,0,0,130,194,0,0,120,194,0,0,134,194,0,0,142,194,0,0,148,194,0,0,160,194,0,0,170,194,0,0,182,194,0,0,190,194,0,0,198,194,0,0,206,194,0,0,216,194,0,0,222,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,206,194,0,0,194,194,0,0,180,194,0,0,170,194,0,0,152,194,0,0,112,194,0,0,96,194,0,0,88,194,0,0,112,194,0,0,120,194,0,0,116,194,0,0,96,194,0,0,124,194,0,0,130,194,0,0,146,194,0,0,148,194,0,0,154,194,0,0,150,194,0,0,156,194,0,0,162,194,0,0,172,194,0,0,174,194,0,0,176,194,0,0,182,194,0,0,188,194,0,0,196,194,0,0,206,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,194,194,0,0,184,194,0,0,172,194,0,0,162,194,0,0,158,194,0,0,140,194,0,0,100,194,0,0,76,194,0,0,60,194,0,0,76,194,0,0,104,194,0,0,112,194,0,0,96,194,0,0,84,194,0,0,72,194,0,0,104,194,0,0,80,194,0,0,72,194,0,0,72,194,0,0,84,194,0,0,92,194,0,0,128,194,0,0,138,194,0,0,142,194,0,0,170,194,0,0,164,194,0,0,156,194,0,0,162,194,0,0,170,194,0,0,190,194,0,0,204,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,200,194,0,0,194,194,0,0,184,194,0,0,170,194,0,0,166,194,0,0,158,194,0,0,144,194,0,0,68,194,0,0,32,194,0,0,44,194,0,0,44,194,0,0,88,194,0,0,96,194,0,0,76,194,0,0,72,194,0,0,32,194,0,0,44,194,0,0,24,194,0,0,16,194,0,0,12,194,0,0,20,194,0,0,24,194,0,0,20,194,0,0,48,194,0,0,88,194,0,0,112,194,0,0,100,194,0,0,112,194,0,0,140,194,0,0,150,194,0,0,168,194,0,0,184,194,0,0,206,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,204,194,0,0,190,194,0,0,178,194,0,0,164,194,0,0,166,194,0,0,168,194,0,0,180,194,0,0,184,194,0,0,198,194,0,0,214,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,202,194,0,0,190,194,0,0,178,194,0,0,166,194,0,0,144,194,0,0,148,194,0,0,156,194,0,0,170,194,0,0,176,194,0,0,176,194,0,0,180,194,0,0,184,194,0,0,196,194,0,0,210,194,0,0,222,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,218,194,0,0,206,194,0,0,194,194,0,0,186,194,0,0,174,194,0,0,162,194,0,0,140,194,0,0,140,194,0,0,134,194,0,0,150,194,0,0,146,194,0,0,152,194,0,0,158,194,0,0,162,194,0,0,166,194,0,0,176,194,0,0,178,194,0,0,194,194,0,0,206,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,214,194,0,0,200,194,0,0,188,194,0,0,176,194,0,0,166,194,0,0,150,194,0,0,124,194,0,0,108,194,0,0,108,194,0,0,124,194,0,0,132,194,0,0,112,194,0,0,120,194,0,0,134,194,0,0,134,194,0,0,154,194,0,0,152,194,0,0,162,194,0,0,176,194,0,0,172,194,0,0,184,194,0,0,192,194,0,0,204,194,0,0,218,194,0,0,232,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,196,194,0,0,184,194,0,0,172,194,0,0,162,194,0,0,146,194,0,0,96,194,0,0,80,194,0,0,60,194,0,0,92,194,0,0,112,194,0,0,104,194,0,0,80,194,0,0,76,194,0,0,52,194,0,0,68,194,0,0,72,194,0,0,84,194,0,0,88,194,0,0,116,194,0,0,142,194,0,0,140,194,0,0,138,194,0,0,156,194,0,0,158,194,0,0,174,194,0,0,180,194,0,0,192,194,0,0,208,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,206,194,0,0,192,194,0,0,180,194,0,0,172,194,0,0,156,194,0,0,140,194,0,0,76,194,0,0,40,194,0,0,60,194,0,0,64,194,0,0,92,194,0,0,88,194,0,0,88,194,0,0,84,194,0,0,40,194,0,0,12,194,0,0,224,193,0,0,4,194,0,0,24,194,0,0,20,194,0,0,48,194,0,0,60,194,0,0,68,194,0,0,88,194,0,0,124,194,0,0,136,194,0,0,156,194,0,0,164,194,0,0,178,194,0,0,188,194,0,0,198,194,0,0,208,194,0,0,218,194,0,0,228,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,180,194,0,0,158,194,0,0,170,194,0,0,162,194,0,0,164,194,0,0,164,194,0,0,178,194,0,0,188,194,0,0,198,194,0,0,206,194,0,0,218,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,194,194,0,0,170,194,0,0,144,194,0,0,148,194,0,0,140,194,0,0,140,194,0,0,140,194,0,0,152,194,0,0,170,194,0,0,182,194,0,0,186,194,0,0,194,194,0,0,206,194,0,0,218,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,224,194,0,0,186,194,0,0,162,194,0,0,136,194,0,0,120,194,0,0,112,194,0,0,112,194,0,0,100,194,0,0,124,194,0,0,140,194,0,0,154,194,0,0,164,194,0,0,180,194,0,0,186,194,0,0,196,194,0,0,208,194,0,0,218,194,0,0,226,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,226,194,0,0,200,194,0,0,186,194,0,0,168,194,0,0,124,194,0,0,104,194,0,0,64,194,0,0,84,194,0,0,88,194,0,0,80,194,0,0,80,194,0,0,100,194,0,0,128,194,0,0,132,194,0,0,152,194,0,0,166,194,0,0,162,194,0,0,170,194,0,0,170,194,0,0,180,194,0,0,190,194,0,0,196,194,0,0,202,194,0,0,206,194,0,0,212,194,0,0,216,194,0,0,222,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,210,194,0,0,190,194,0,0,172,194,0,0,148,194,0,0,84,194,0,0,72,194,0,0,24,194,0,0,44,194,0,0,68,194,0,0,44,194,0,0,40,194,0,0,28,194,0,0,28,194,0,0,56,194,0,0,80,194,0,0,100,194,0,0,96,194,0,0,144,194,0,0,138,194,0,0,148,194,0,0,162,194,0,0,174,194,0,0,184,194,0,0,188,194,0,0,194,194,0,0,198,194,0,0,204,194,0,0,210,194,0,0,216,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,216,194,0,0,198,194,0,0,180,194,0,0,152,194,0,0,132,194,0,0,52,194,0,0,44,194,0,0,36,194,0,0,48,194,0,0,60,194,0,0,44,194,0,0,60,194,0,0,32,194,0,0,240,193,0,0,248,193,0,0,248,193,0,0,28,194,0,0,4,194,0,0,32,194,0,0,36,194,0,0,44,194,0,0,84,194,0,0,108,194,0,0,140,194,0,0,146,194,0,0,154,194,0,0,158,194,0,0,164,194,0,0,168,194,0,0,174,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,182,194,0,0,152,194,0,0,150,194,0,0,170,194,0,0,186,194,0,0,196,194,0,0,208,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,182,194,0,0,140,194,0,0,140,194,0,0,150,194,0,0,172,194,0,0,178,194,0,0,188,194,0,0,196,194,0,0,202,194,0,0,212,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,190,194,0,0,160,194,0,0,112,194,0,0,130,194,0,0,128,194,0,0,148,194,0,0,166,194,0,0,176,194,0,0,182,194],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE+40960);allocate([0,0,190,194,0,0,198,194,0,0,206,194,0,0,214,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,190,194,0,0,160,194,0,0,104,194,0,0,92,194,0,0,68,194,0,0,132,194,0,0,136,194,0,0,142,194,0,0,156,194,0,0,156,194,0,0,160,194,0,0,176,194,0,0,170,194,0,0,178,194,0,0,194,194,0,0,200,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,190,194,0,0,160,194,0,0,84,194,0,0,80,194,0,0,36,194,0,0,108,194,0,0,108,194,0,0,68,194,0,0,104,194,0,0,96,194,0,0,124,194,0,0,172,194,0,0,158,194,0,0,180,194,0,0,186,194,0,0,196,194,0,0,206,194,0,0,214,194,0,0,224,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,194,194,0,0,182,194,0,0,146,194,0,0,52,194,0,0,32,194,0,0,4,194,0,0,84,194,0,0,116,194,0,0,68,194,0,0,88,194,0,0,72,194,0,0,72,194,0,0,112,194,0,0,80,194,0,0,134,194,0,0,148,194,0,0,162,194,0,0,184,194,0,0,192,194,0,0,200,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,226,194,0,0,212,194,0,0,198,194,0,0,184,194,0,0,154,194,0,0,160,194,0,0,176,194,0,0,194,194,0,0,212,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,232,194,0,0,218,194,0,0,204,194,0,0,190,194,0,0,178,194,0,0,148,194,0,0,144,194,0,0,176,194,0,0,174,194,0,0,190,194,0,0,204,194,0,0,218,194,0,0,232,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,232,194,0,0,218,194,0,0,204,194,0,0,190,194,0,0,178,194,0,0,150,194,0,0,132,194,0,0,148,194,0,0,154,194,0,0,156,194,0,0,172,194,0,0,174,194,0,0,180,194,0,0,192,194,0,0,210,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,230,194,0,0,216,194,0,0,202,194,0,0,188,194,0,0,176,194,0,0,132,194,0,0,96,194,0,0,116,194,0,0,140,194,0,0,130,194,0,0,156,194,0,0,144,194,0,0,166,194,0,0,168,194,0,0,186,194,0,0,196,194,0,0,210,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,210,194,0,0,190,194,0,0,178,194,0,0,164,194,0,0,100,194,0,0,80,194,0,0,80,194,0,0,108,194,0,0,96,194,0,0,108,194,0,0,104,194,0,0,138,194,0,0,134,194,0,0,176,194,0,0,164,194,0,0,164,194,0,0,178,194,0,0,188,194,0,0,200,194,0,0,216,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,202,194,0,0,192,194,0,0,180,194,0,0,166,194,0,0,154,194,0,0,88,194,0,0,44,194,0,0,24,194,0,0,72,194,0,0,64,194,0,0,80,194,0,0,64,194,0,0,40,194,0,0,40,194,0,0,76,194,0,0,80,194,0,0,84,194,0,0,108,194,0,0,130,194,0,0,142,194,0,0,156,194,0,0,170,194,0,0,190,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,240,194,0,0,210,194,0,0,172,194,0,0,136,194,0,0,156,194,0,0,158,194,0,0,180,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,240,194,0,0,210,194,0,0,172,194,0,0,132,194,0,0,146,194,0,0,154,194,0,0,176,194,0,0,192,194,0,0,210,194,0,0,230,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,240,194,0,0,210,194,0,0,184,194,0,0,160,194,0,0,116,194,0,0,128,194,0,0,136,194,0,0,160,194,0,0,174,194,0,0,184,194,0,0,200,194,0,0,220,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,240,194,0,0,208,194,0,0,182,194,0,0,158,194,0,0,80,194,0,0,112,194,0,0,88,194,0,0,128,194,0,0,138,194,0,0,154,194,0,0,160,194,0,0,164,194,0,0,168,194,0,0,170,194,0,0,174,194,0,0,176,194,0,0,180,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,236,194,0,0,200,194,0,0,174,194,0,0,154,194,0,0,68,194,0,0,72,194,0,0,48,194,0,0,104,194,0,0,116,194,0,0,116,194,0,0,134,194,0,0,130,194,0,0,120,194,0,0,120,194,0,0,120,194,0,0,130,194,0,0,136,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,230,194,0,0,196,194,0,0,168,194,0,0,120,194,0,0,68,194,0,0,48,194,0,0,24,194,0,0,56,194,0,0,68,194,0,0,68,194,0,0,56,194,0,0,28,194,0,0,20,194,0,0,28,194,0,0,32,194,0,0,40,194,0,0,44,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,176,194,0,0,148,194,0,0,154,194,0,0,164,194,0,0,164,194,0,0,170,194,0,0,180,194,0,0,188,194,0,0,198,194,0,0,208,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,176,194,0,0,132,194,0,0,140,194,0,0,162,194,0,0,160,194,0,0,162,194,0,0,168,194,0,0,176,194,0,0,182,194,0,0,186,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,176,194,0,0,116,194,0,0,124,194,0,0,140,194,0,0,142,194,0,0,148,194,0,0,154,194,0,0,160,194,0,0,166,194,0,0,170,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,172,194,0,0,120,194,0,0,124,194,0,0,120,194,0,0,120,194,0,0,104,194,0,0,80,194,0,0,72,194,0,0,72,194,0,0,80,194,0,0,88,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,236,194,0,0,216,194,0,0,168,194,0,0,84,194,0,0,72,194,0,0,72,194,0,0,72,194,0,0,92,194,0,0,60,194,0,0,52,194,0,0,32,194,0,0,32,194,0,0,32,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,236,194,0,0,200,194,0,0,146,194,0,0,44,194,0,0,20,194,0,0,40,194,0,0,44,194,0,0,84,194,0,0,24,194,0,0,20,194,0,0,12,194,0,0,12,194,0,0,24,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,182,194,0,0,168,194,0,0,148,194,0,0,160,194,0,0,160,194,0,0,160,194,0,0,160,194,0,0,160,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,182,194,0,0,168,194,0,0,148,194,0,0,136,194,0,0,136,194,0,0,136,194,0,0,136,194,0,0,136,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,172,194,0,0,156,194,0,0,140,194,0,0,112,194,0,0,52,194,0,0,240,193,0,0,168,193,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,174,194,0,0,156,194,0,0,134,194,0,0,64,194,0,0,24,194,0,0,232,193,0,0,168,193,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,172,194,0,0,138,194,0,0,96,194,0,0,52,194,0,0,12,194,0,0,4,194,0,0,232,193,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,0,220,194,0,0,200,194,0,0,166,194,0,0,142,194,0,0,64,194,0,0,216,193,0,0,24,194,0,0,20,194,0,0,8,194,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,0,192,121,196,118,111,114,98,105,115,0],"i8",ALLOC_NONE,Runtime.GLOBAL_BASE+51200);var tempDoublePtr=STATICTOP;STATICTOP+=16;function __exit(status){Module["exit"](status)}function _exit(status){__exit(status)}Module["_i64Subtract"]=_i64Subtract;function ___setErrNo(value){if(Module["___errno_location"])HEAP32[Module["___errno_location"]()>>2]=value;return value}var ERRNO_CODES={EPERM:1,ENOENT:2,ESRCH:3,EINTR:4,EIO:5,ENXIO:6,E2BIG:7,ENOEXEC:8,EBADF:9,ECHILD:10,EAGAIN:11,EWOULDBLOCK:11,ENOMEM:12,EACCES:13,EFAULT:14,ENOTBLK:15,EBUSY:16,EEXIST:17,EXDEV:18,ENODEV:19,ENOTDIR:20,EISDIR:21,EINVAL:22,ENFILE:23,EMFILE:24,ENOTTY:25,ETXTBSY:26,EFBIG:27,ENOSPC:28,ESPIPE:29,EROFS:30,EMLINK:31,EPIPE:32,EDOM:33,ERANGE:34,ENOMSG:42,EIDRM:43,ECHRNG:44,EL2NSYNC:45,EL3HLT:46,EL3RST:47,ELNRNG:48,EUNATCH:49,ENOCSI:50,EL2HLT:51,EDEADLK:35,ENOLCK:37,EBADE:52,EBADR:53,EXFULL:54,ENOANO:55,EBADRQC:56,EBADSLT:57,EDEADLOCK:35,EBFONT:59,ENOSTR:60,ENODATA:61,ETIME:62,ENOSR:63,ENONET:64,ENOPKG:65,EREMOTE:66,ENOLINK:67,EADV:68,ESRMNT:69,ECOMM:70,EPROTO:71,EMULTIHOP:72,EDOTDOT:73,EBADMSG:74,ENOTUNIQ:76,EBADFD:77,EREMCHG:78,ELIBACC:79,ELIBBAD:80,ELIBSCN:81,ELIBMAX:82,ELIBEXEC:83,ENOSYS:38,ENOTEMPTY:39,ENAMETOOLONG:36,ELOOP:40,EOPNOTSUPP:95,EPFNOSUPPORT:96,ECONNRESET:104,ENOBUFS:105,EAFNOSUPPORT:97,EPROTOTYPE:91,ENOTSOCK:88,ENOPROTOOPT:92,ESHUTDOWN:108,ECONNREFUSED:111,EADDRINUSE:98,ECONNABORTED:103,ENETUNREACH:101,ENETDOWN:100,ETIMEDOUT:110,EHOSTDOWN:112,EHOSTUNREACH:113,EINPROGRESS:115,EALREADY:114,EDESTADDRREQ:89,EMSGSIZE:90,EPROTONOSUPPORT:93,ESOCKTNOSUPPORT:94,EADDRNOTAVAIL:99,ENETRESET:102,EISCONN:106,ENOTCONN:107,ETOOMANYREFS:109,EUSERS:87,EDQUOT:122,ESTALE:116,ENOTSUP:95,ENOMEDIUM:123,EILSEQ:84,EOVERFLOW:75,ECANCELED:125,ENOTRECOVERABLE:131,EOWNERDEAD:130,ESTRPIPE:86};function _sysconf(name){switch(name){case 30:return PAGE_SIZE;case 85:return totalMemory/PAGE_SIZE;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 80:case 81:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 79:return 0;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:{if(typeof navigator==="object")return navigator["hardwareConcurrency"]||1;return 1}}___setErrNo(ERRNO_CODES.EINVAL);return-1}Module["_memset"]=_memset;Module["_bitshift64Shl"]=_bitshift64Shl;function _abort(){Module["abort"]()}function _emscripten_memcpy_big(dest,src,num){HEAPU8.set(HEAPU8.subarray(src,src+num),dest);return dest}Module["_memcpy"]=_memcpy;Module["_i64Add"]=_i64Add;var _llvm_pow_f64=Math_pow;function _ogvjs_callback_audio(buffers,channels,sampleCount){var HEAPU32=Module.HEAPU32;var HEAPF32=Module.HEAPF32;var outputBuffers=[];if(buffers!==0){var inPtr,inArray,outArray;for(var channel=0;channel<channels;channel++){inPtr=HEAPU32[buffers/4+channel];inArray=HEAPF32.subarray(inPtr/4,inPtr/4+sampleCount);outArray=new Float32Array(inArray);outputBuffers.push(outArray)}}Module.audioBuffer=outputBuffers}function _ogvjs_callback_init_audio(channels,rate){Module.audioFormat={channels:channels,rate:rate};Module.loadedMetadata=true}var _llvm_fabs_f32=Math_abs;Module["_llvm_bswap_i32"]=_llvm_bswap_i32;function _sbrk(bytes){var self=_sbrk;if(!self.called){DYNAMICTOP=alignMemoryPage(DYNAMICTOP);self.called=true;assert(Runtime.dynamicAlloc);self.alloc=Runtime.dynamicAlloc;Runtime.dynamicAlloc=(function(){abort("cannot dynamically allocate, sbrk now has control")})}var ret=DYNAMICTOP;if(bytes!=0){var success=self.alloc(bytes);if(!success)return-1>>>0}return ret}function _time(ptr){var ret=Date.now()/1e3|0;if(ptr){HEAP32[ptr>>2]=ret}return ret}var _llvm_sqrt_f64=Math_sqrt;function _pthread_self(){return 0}STACK_BASE=STACKTOP=Runtime.alignMemory(STATICTOP);staticSealed=true;STACK_MAX=STACK_BASE+TOTAL_STACK;DYNAMIC_BASE=DYNAMICTOP=Runtime.alignMemory(STACK_MAX);var cttz_i8=allocate([8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0],"i8",ALLOC_DYNAMIC);function invoke_iiiii(index,a1,a2,a3,a4){try{return Module["dynCall_iiiii"](index,a1,a2,a3,a4)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_vi(index,a1){try{Module["dynCall_vi"](index,a1)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_vii(index,a1,a2){try{Module["dynCall_vii"](index,a1,a2)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_ii(index,a1){try{return Module["dynCall_ii"](index,a1)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_viii(index,a1,a2,a3){try{Module["dynCall_viii"](index,a1,a2,a3)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_iiiiiiiii(index,a1,a2,a3,a4,a5,a6,a7,a8){try{return Module["dynCall_iiiiiiiii"](index,a1,a2,a3,a4,a5,a6,a7,a8)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_iii(index,a1,a2){try{return Module["dynCall_iii"](index,a1,a2)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}function invoke_iiiiii(index,a1,a2,a3,a4,a5){try{return Module["dynCall_iiiiii"](index,a1,a2,a3,a4,a5)}catch(e){if(typeof e!=="number"&&e!=="longjmp")throw e;asm["setThrew"](1,0)}}Module.asmGlobalArg={"Math":Math,"Int8Array":Int8Array,"Int16Array":Int16Array,"Int32Array":Int32Array,"Uint8Array":Uint8Array,"Uint16Array":Uint16Array,"Uint32Array":Uint32Array,"Float32Array":Float32Array,"Float64Array":Float64Array,"NaN":NaN,"Infinity":Infinity};Module.asmLibraryArg={"abort":abort,"assert":assert,"invoke_iiiii":invoke_iiiii,"invoke_vi":invoke_vi,"invoke_vii":invoke_vii,"invoke_ii":invoke_ii,"invoke_viii":invoke_viii,"invoke_iiiiiiiii":invoke_iiiiiiiii,"invoke_iii":invoke_iii,"invoke_iiiiii":invoke_iiiiii,"_pthread_self":_pthread_self,"_emscripten_memcpy_big":_emscripten_memcpy_big,"_llvm_pow_f64":_llvm_pow_f64,"_sysconf":_sysconf,"_llvm_sqrt_f64":_llvm_sqrt_f64,"_llvm_fabs_f32":_llvm_fabs_f32,"_abort":_abort,"___setErrNo":___setErrNo,"_sbrk":_sbrk,"_time":_time,"_ogvjs_callback_audio":_ogvjs_callback_audio,"_ogvjs_callback_init_audio":_ogvjs_callback_init_audio,"_exit":_exit,"__exit":__exit,"STACKTOP":STACKTOP,"STACK_MAX":STACK_MAX,"tempDoublePtr":tempDoublePtr,"ABORT":ABORT,"cttz_i8":cttz_i8};// EMSCRIPTEN_START_ASM var asm=(function(global,env,buffer) {
// EMSCRIPTEN_START_FUNCS function Ia(a){a=a|0;var b=0;b=i;i=i+a|0;i=i+15&-16;return b|0}function Ja(){return i|0}function Ka(a){a=a|0;i=a}function La(a,b){a=a|0;b=b|0;i=a;j=b}function Ma(a,b){a=a|0;b=b|0;if(!n){n=a;o=b}}function Na(b){b=b|0;a[k>>0]=a[b>>0];a[k+1>>0]=a[b+1>>0];a[k+2>>0]=a[b+2>>0];a[k+3>>0]=a[b+3>>0]}function Oa(b){b=b|0;a[k>>0]=a[b>>0];a[k+1>>0]=a[b+1>>0];a[k+2>>0]=a[b+2>>0];a[k+3>>0]=a[b+3>>0];a[k+4>>0]=a[b+4>>0];a[k+5>>0]=a[b+5>>0];a[k+6>>0]=a[b+6>>0];a[k+7>>0]=a[b+7>>0]}function Pa(a){a=a|0;C=a}function Qa(){return C|0}function Ra(b){b=b|0;var d=0;c[b>>2]=0;c[b+4>>2]=0;c[b+8>>2]=0;c[b+12>>2]=0;d=ed(256)|0;c[b+8>>2]=d;c[b+12>>2]=d;a[d>>0]=0;c[b+16>>2]=256;return}function Sa(b,e,f){b=b|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0;do if(f>>>0<=32){g=b+16|0;h=c[g>>2]|0;i=b+12|0;j=c[i>>2]|0;if((c[b>>2]|0)<(h+-4|0))k=j;else{if(!j)return;if((h|0)>2147483391)break;j=b+8|0;l=hd(c[j>>2]|0,h+256|0)|0;if(!l)break;c[j>>2]=l;c[g>>2]=(c[g>>2]|0)+256;g=l+(c[b>>2]|0)|0;c[i>>2]=g;k=g}g=c[152+(f<<2)>>2]&e;l=b+4|0;j=c[l>>2]|0;h=j+f|0;a[k>>0]=d[k>>0]|0|g<<j;do if((((h|0)>7?(a[(c[i>>2]|0)+1>>0]=g>>>(8-(c[l>>2]|0)|0),(h|0)>15):0)?(a[(c[i>>2]|0)+2>>0]=g>>>(16-(c[l>>2]|0)|0),(h|0)>23):0)?(a[(c[i>>2]|0)+3>>0]=g>>>(24-(c[l>>2]|0)|0),(h|0)>31):0){j=c[l>>2]|0;if(!j){a[(c[i>>2]|0)+4>>0]=0;break}else{a[(c[i>>2]|0)+4>>0]=g>>>(32-j|0);break}}while(0);g=(h|0)/8|0;c[b>>2]=(c[b>>2]|0)+g;c[i>>2]=(c[i>>2]|0)+g;c[l>>2]=h&7;return}while(0);k=c[b+8>>2]|0;if(k|0)fd(k);c[b>>2]=0;c[b+4>>2]=0;c[b+8>>2]=0;c[b+12>>2]=0;c[b+16>>2]=0;return}function Ta(a){a=a|0;var b=0;b=c[a+8>>2]|0;if(b|0)fd(b);c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+16>>2]=0;return}function Ua(a,b,d){a=a|0;b=b|0;d=d|0;c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+12>>2]=b;c[a+8>>2]=b;c[a+16>>2]=d;return}function Va(a,b){a=a|0;b=b|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;if(b>>>0>32){e=-1;return e|0}f=c[152+(b<<2)>>2]|0;g=c[a+4>>2]|0;h=g+b|0;b=c[a>>2]|0;i=c[a+16>>2]|0;if((b|0)>=(i+-4|0)){if((b|0)>(i-(h+7>>3)|0)){e=-1;return e|0}if(!h){e=0;return e|0}}i=c[a+12>>2]|0;a=(d[i>>0]|0)>>>g;if((h|0)>8){b=(d[i+1>>0]|0)<<8-g|a;if((h|0)>16){j=(d[i+2>>0]|0)<<16-g|b;if((h|0)>24){k=(d[i+3>>0]|0)<<24-g|j;if((h|0)<33|(g|0)==0)l=k;else l=(d[i+4>>0]|0)<<32-g|k}else l=j}else l=b}else l=a;e=l&f;return e|0}function Wa(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0;d=a+4|0;e=(c[d>>2]|0)+b|0;b=c[a>>2]|0;f=c[a+16>>2]|0;if((b|0)>(f-(e+7>>3)|0)){c[a+12>>2]=0;c[a>>2]=f;g=1;c[d>>2]=g;return}else{f=(e|0)/8|0;h=a+12|0;c[h>>2]=(c[h>>2]|0)+f;c[a>>2]=b+f;g=e&7;c[d>>2]=g;return}}function Xa(a,b){a=a|0;b=b|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;do if(b>>>0>32){e=a;f=a+4|0;g=c[a+16>>2]|0}else{h=c[152+(b<<2)>>2]|0;i=a+4|0;j=c[i>>2]|0;k=j+b|0;l=c[a>>2]|0;m=c[a+16>>2]|0;if((l|0)>=(m+-4|0)){if((l|0)>(m-(k+7>>3)|0)){e=a;f=i;g=m;break}if(!k){n=0;return n|0}}m=a+12|0;o=c[m>>2]|0;p=(d[o>>0]|0)>>>j;if((k|0)>8){q=(d[o+1>>0]|0)<<8-j|p;if((k|0)>16){r=(d[o+2>>0]|0)<<16-j|q;if((k|0)>24){s=(d[o+3>>0]|0)<<24-j|r;if((k|0)<33|(j|0)==0)t=s;else t=(d[o+4>>0]|0)<<32-j|s}else t=r}else t=q}else t=p;p=(k|0)/8|0;c[m>>2]=o+p;c[a>>2]=l+p;c[i>>2]=k&7;n=t&h;return n|0}while(0);c[a+12>>2]=0;c[e>>2]=g;c[f>>2]=1;n=-1;return n|0}function Ya(a){a=a|0;return (((c[a+4>>2]|0)+7|0)/8|0)+(c[a>>2]|0)|0}function Za(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;d=a+836|0;e=c[a+840>>2]|0;Sa(b,c[a>>2]|0,5);if((c[a>>2]|0)>0){f=a+4|0;g=0;h=-1;while(1){i=f+(g<<2)|0;Sa(b,c[i>>2]|0,4);j=c[i>>2]|0;i=(h|0)<(j|0)?j:h;g=g+1|0;if((g|0)>=(c[a>>2]|0)){k=i;break}else h=i}if((k|0)>=0){h=a+128|0;g=a+192|0;f=a+256|0;i=a+320|0;j=0;while(1){Sa(b,(c[h+(j<<2)>>2]|0)+-1|0,3);l=g+(j<<2)|0;Sa(b,c[l>>2]|0,2);if(!((c[l>>2]|0)!=0?(Sa(b,c[f+(j<<2)>>2]|0,8),(c[l>>2]|0)==31):0)){m=0;n=8}if((n|0)==8)while(1){n=0;Sa(b,(c[i+(j<<5)+(m<<2)>>2]|0)+1|0,8);m=m+1|0;if((m|0)>=(1<<c[l>>2]|0))break;else n=8}if((j|0)==(k|0))break;else j=j+1|0}}}Sa(b,(c[a+832>>2]|0)+-1|0,2);j=e+-1|0;if((e|0)==0|(j|0)==0){Sa(b,0,4);o=0}else{e=j;k=0;while(1){n=k+1|0;e=e>>>1;if(!e){p=n;break}else k=n}Sa(b,p,4);p=j;j=0;while(1){k=j+1|0;p=p>>>1;if(!p){o=k;break}else j=k}}j=c[a>>2]|0;if((j|0)<=0)return;p=a+4|0;k=a+128|0;e=j;j=0;n=0;m=0;while(1){j=(c[k+(c[p+(n<<2)>>2]<<2)>>2]|0)+j|0;if((m|0)<(j|0)){i=m;do{Sa(b,c[d+(i+2<<2)>>2]|0,o);i=i+1|0}while((i|0)!=(j|0));q=c[a>>2]|0;r=j}else{q=e;r=m}n=n+1|0;if((n|0)>=(q|0))break;else{e=q;m=r}}return}function _a(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0;d=i;i=i+272|0;e=d;f=c[a+28>>2]|0;a=gd(1,1120)|0;g=Xa(b,5)|0;c[a>>2]=g;a:do if((g|0)>0){h=a+4|0;j=0;k=-1;while(1){l=Xa(b,4)|0;c[h+(j<<2)>>2]=l;if((l|0)<0)break a;m=(k|0)<(l|0)?l:k;j=j+1|0;if((j|0)>=(c[a>>2]|0)){n=m;break}else k=m}if((n|0)>=0){k=a+128|0;j=a+192|0;h=a+256|0;m=f+24|0;l=a+320|0;o=0;while(1){c[k+(o<<2)>>2]=(Xa(b,3)|0)+1;p=Xa(b,2)|0;q=j+(o<<2)|0;c[q>>2]=p;if((p|0)<0)break a;if(!p)r=c[h+(o<<2)>>2]|0;else{p=Xa(b,8)|0;c[h+(o<<2)>>2]=p;r=p}if((r|0)<0)break a;if((r|0)>=(c[m>>2]|0))break a;if((c[q>>2]|0)!=31){p=0;do{s=Xa(b,8)|0;c[l+(o<<5)+(p<<2)>>2]=s+-1;if((s|0)<0)break a;p=p+1|0;if((s|0)>(c[m>>2]|0))break a}while((p|0)<(1<<c[q>>2]|0))}if((o|0)<(n|0))o=o+1|0;else{t=18;break}}}else t=18}else t=18;while(0);b:do if((t|0)==18?(c[a+832>>2]=(Xa(b,2)|0)+1,n=Xa(b,4)|0,(n|0)>=0):0){r=c[a>>2]|0;if((r|0)>0){f=a+4|0;g=a+128|0;o=a+836|0;m=1<<n;l=r;r=0;h=0;j=0;while(1){k=(c[g+(c[f+(h<<2)>>2]<<2)>>2]|0)+r|0;if((k|0)>63)break b;if((j|0)<(k|0)){q=j;while(1){p=Xa(b,n)|0;c[o+(q+2<<2)>>2]=p;if(!((p|0)>-1&(p|0)<(m|0)))break b;p=q+1|0;if((p|0)<(k|0))q=p;else{u=p;break}}v=c[a>>2]|0;w=u}else{v=l;w=j}h=h+1|0;if((h|0)>=(v|0)){x=o;y=m;z=k;break}else{l=v;r=k;j=w}}}else{x=a+836|0;y=1<<n;z=0}c[x>>2]=0;c[a+840>>2]=y;j=z+2|0;if((z|0)>-2){r=0;do{c[e+(r<<2)>>2]=x+(r<<2);r=r+1|0}while((r|0)<(j|0))}Yc(e,j,4,11);c:do if((j|0)>1){r=c[c[e>>2]>>2]|0;n=1;while(1){l=r;r=c[c[e+(n<<2)>>2]>>2]|0;n=n+1|0;if((l|0)==(r|0))break;if((n|0)>=(j|0))break c}if(!a)A=0;else break b;i=d;return A|0}while(0);A=a;i=d;return A|0}while(0);fd(a);A=0;i=d;return A|0}function $a(a,b){a=a|0;b=b|0;return (c[c[a>>2]>>2]|0)-(c[c[b>>2]>>2]|0)|0}function ab(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;a=i;i=i+272|0;d=a;e=gd(1,1312)|0;c[e+1296>>2]=b;f=b+836|0;g=e+1288|0;c[g>>2]=c[b+840>>2];h=c[b>>2]|0;if((h|0)>0){j=b+4|0;k=b+128|0;l=0;m=0;while(1){n=(c[k+(c[j+(l<<2)>>2]<<2)>>2]|0)+m|0;l=l+1|0;if((l|0)>=(h|0)){o=n;break}else m=n}m=o+2|0;c[e+1284>>2]=m;if((o|0)>-2){p=m;q=o;r=7}else{Yc(d,m,4,11);s=o}}else{c[e+1284>>2]=2;p=2;q=0;r=7}if((r|0)==7){r=0;do{c[d+(r<<2)>>2]=f+(r<<2);r=r+1|0}while((r|0)<(p|0));Yc(d,p,4,11);r=f;o=e+260|0;m=0;do{c[o+(m<<2)>>2]=(c[d+(m<<2)>>2]|0)-r>>2;m=m+1|0}while((m|0)<(p|0));m=e+260|0;r=e+520|0;d=0;do{c[r+(c[m+(d<<2)>>2]<<2)>>2]=d;d=d+1|0}while((d|0)<(p|0));d=e+260|0;m=0;do{c[e+(m<<2)>>2]=c[f+(c[d+(m<<2)>>2]<<2)>>2];m=m+1|0}while((m|0)<(p|0));s=q}switch(c[b+832>>2]|0){case 1:{c[e+1292>>2]=256;break}case 2:{c[e+1292>>2]=128;break}case 3:{c[e+1292>>2]=86;break}case 4:{c[e+1292>>2]=64;break}default:{}}if((s|0)<=0){i=a;return e|0}b=e+1032|0;q=e+780|0;p=0;do{m=p+2|0;d=c[f+(m<<2)>>2]|0;r=1;o=c[g>>2]|0;h=0;l=0;j=0;while(1){k=c[f+(h<<2)>>2]|0;n=(k|0)>(j|0)&(k|0)<(d|0);t=n?h:l;u=(k|0)<(o|0)&(k|0)>(d|0);v=u?h:r;h=h+1|0;if((h|0)>=(m|0)){w=v;x=t;break}else{r=v;o=u?k:o;l=t;j=n?k:j}}c[b+(p<<2)>>2]=x;c[q+(p<<2)>>2]=w;p=p+1|0}while((p|0)!=(s|0));i=a;return e|0}function bb(a){a=a|0;if(a|0)fd(a);return}function cb(a){a=a|0;if(a|0)fd(a);return}function db(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;d=c[b+1296>>2]|0;e=c[(c[(c[(c[a+64>>2]|0)+4>>2]|0)+28>>2]|0)+2848>>2]|0;f=a+4|0;if((Xa(f,1)|0)!=1){g=0;return g|0}h=b+1284|0;i=eb(a,c[h>>2]<<2)|0;a=b+1292|0;j=(c[a>>2]|0)+-1|0;if(!j)k=0;else{l=j;j=0;while(1){m=j+1|0;l=l>>>1;if(!l){k=m;break}else j=m}}c[i>>2]=Xa(f,k)|0;k=(c[a>>2]|0)+-1|0;if(!k)n=0;else{j=k;k=0;while(1){l=k+1|0;j=j>>>1;if(!j){n=l;break}else k=l}}c[i+4>>2]=Xa(f,n)|0;a:do if((c[d>>2]|0)>0){n=0;k=2;b:while(1){j=c[d+4+(n<<2)>>2]|0;l=c[d+128+(j<<2)>>2]|0;m=c[d+192+(j<<2)>>2]|0;o=1<<m;if(m){p=fb(e+((c[d+256+(j<<2)>>2]|0)*56|0)|0,f)|0;if((p|0)==-1){g=0;q=29;break}else r=p}else r=0;if((l|0)>0){p=o+-1|0;o=r;s=0;do{t=c[d+320+(j<<5)+((o&p)<<2)>>2]|0;o=o>>m;if((t|0)>-1){u=fb(e+(t*56|0)|0,f)|0;c[i+(s+k<<2)>>2]=u;if((u|0)==-1){g=0;q=29;break b}}else c[i+(s+k<<2)>>2]=0;s=s+1|0}while((s|0)<(l|0))}n=n+1|0;if((n|0)>=(c[d>>2]|0))break a;else k=l+k|0}if((q|0)==29)return g|0}while(0);if((c[h>>2]|0)<=2){g=i;return g|0}q=b+1032|0;f=b+780|0;b=2;do{e=b+-2|0;r=q+(e<<2)|0;k=c[r>>2]|0;n=c[d+836+(k<<2)>>2]|0;s=f+(e<<2)|0;e=c[s>>2]|0;m=c[i+(k<<2)>>2]&32767;k=(c[i+(e<<2)>>2]&32767)-m|0;o=(_((k|0)>-1?k:0-k|0,(c[d+836+(b<<2)>>2]|0)-n|0)|0)/((c[d+836+(e<<2)>>2]|0)-n|0)|0;n=((k|0)<0?0-o|0:o)+m|0;m=(c[a>>2]|0)-n|0;o=i+(b<<2)|0;k=c[o>>2]|0;if(!k)c[o>>2]=n|32768;else{do if((k|0)<(((m|0)<(n|0)?m:n)<<1|0))if(!(k&1)){v=k>>1;break}else{v=0-(k+1>>1)|0;break}else if((m|0)>(n|0)){v=k-n|0;break}else{v=~(k-m);break}while(0);c[o>>2]=v+n&32767;m=i+(c[r>>2]<<2)|0;c[m>>2]=c[m>>2]&32767;m=i+(c[s>>2]<<2)|0;c[m>>2]=c[m>>2]&32767}b=b+1|0}while((b|0)<(c[h>>2]|0));g=i;return g|0}function eb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0;d=b+7&-8;b=a+72|0;e=c[b>>2]|0;f=a+76|0;g=a+68|0;h=c[g>>2]|0;if((e+d|0)<=(c[f>>2]|0)){i=h;j=e;k=i+j|0;l=j+d|0;c[b>>2]=l;return k|0}if(h|0){m=ed(8)|0;n=a+80|0;c[n>>2]=(c[n>>2]|0)+e;e=a+84|0;c[m+4>>2]=c[e>>2];c[m>>2]=h;c[e>>2]=m}c[f>>2]=d;f=ed(d)|0;c[g>>2]=f;c[b>>2]=0;i=f;j=0;k=i+j|0;l=j+d|0;c[b>>2]=l;return k|0}function fb(a,b){a=a|0;b=b|0;var d=0,e=0;if((c[a+8>>2]|0)<=0){d=-1;return d|0}e=gb(a,b)|0;if((e|0)<=-1){d=-1;return d|0}d=c[(c[a+24>>2]|0)+(e<<2)>>2]|0;return d|0}function gb(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;e=c[b+40>>2]|0;f=Va(d,c[b+36>>2]|0)|0;do if((f|0)>-1){g=c[(c[b+32>>2]|0)+(f<<2)>>2]|0;if((g|0)<0){h=(c[b+8>>2]|0)-(g&32767)|0;i=g>>>15&32767;break}j=g+-1|0;Wa(d,a[(c[b+28>>2]|0)+j>>0]|0);k=j;return k|0}else{h=c[b+8>>2]|0;i=0}while(0);f=Va(d,e)|0;j=(f|0)<0;if(j&(e|0)>1){g=e;while(1){l=g+-1|0;m=Va(d,l)|0;n=(m|0)<0;if(n&(l|0)>1)g=l;else{o=n;p=m;q=l;break}}}else{o=j;p=f;q=e}if(o){k=-1;return k|0}o=qd(p|0)|0;p=o>>>4&252645135|o<<4&-252645136;o=p>>>2&858993459|p<<2&-858993460;p=o>>>1&1431655765|o<<1&-1431655766;o=h-i|0;if((o|0)>1){e=c[b+20>>2]|0;f=o;o=h;h=i;while(1){j=f>>1;g=(c[e+(j+h<<2)>>2]|0)>>>0>p>>>0;l=(g?0:j)+h|0;o=o-(g?j:0)|0;f=o-l|0;if((f|0)<=1){r=l;break}else h=l}}else r=i;i=a[(c[b+28>>2]|0)+r>>0]|0;if((i|0)>(q|0)){Wa(d,q);k=-1;return k|0}else{Wa(d,i);k=r;return k|0}return 0}function hb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0.0;f=c[b+1296>>2]|0;h=(c[(c[(c[(c[a+64>>2]|0)+4>>2]|0)+28>>2]|0)+(c[a+28>>2]<<2)>>2]|0)/2|0;if(!d){md(e|0,0,h<<2|0)|0;i=0;return i|0}a=c[f+832>>2]|0;j=_(a,c[d>>2]|0)|0;k=(j|0)<0?0:(j|0)>255?255:j;j=c[b+1284>>2]|0;if((j|0)>1){l=b+260|0;b=0;m=1;n=0;o=k;while(1){p=c[l+(m<<2)>>2]|0;q=c[d+(p<<2)>>2]|0;if((q&32767|0)==(q|0)){r=c[f+836+(p<<2)>>2]|0;p=_(a,q)|0;q=(p|0)<0?0:(p|0)>255?255:p;p=q-o|0;s=r-n|0;t=(p|0)/(s|0)|0;u=p>>31|1;v=_(t,s)|0;w=((p|0)>-1?p:0-p|0)-((v|0)>-1?v:0-v|0)|0;v=(h|0)>(r|0)?r:h;if((v|0)>(n|0)){p=e+(n<<2)|0;g[p>>2]=+g[p>>2]*+g[33128+(o<<2)>>2]}p=n+1|0;if((p|0)<(v|0)){x=p;p=0;y=o;while(1){z=p+w|0;A=(z|0)<(s|0);y=y+t+(A?0:u)|0;B=e+(x<<2)|0;g[B>>2]=+g[B>>2]*+g[33128+(y<<2)>>2];x=x+1|0;if((x|0)>=(v|0)){C=r;D=r;E=q;break}else p=z-(A?0:s)|0}}else{C=r;D=r;E=q}}else{C=b;D=n;E=o}m=m+1|0;if((m|0)>=(j|0)){F=C;G=E;break}else{b=C;n=D;o=E}}}else{F=0;G=k}if((F|0)>=(h|0)){i=1;return i|0}H=+g[33128+(G<<2)>>2];G=F;do{F=e+(G<<2)|0;g[F>>2]=+g[F>>2]*H;G=G+1|0}while((G|0)!=(h|0));i=1;return i|0}function ib(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0;d=c[a+28>>2]|0;a=ed(96)|0;e=Xa(b,8)|0;c[a>>2]=e;f=Xa(b,16)|0;c[a+4>>2]=f;g=Xa(b,16)|0;c[a+8>>2]=g;c[a+12>>2]=Xa(b,6)|0;c[a+16>>2]=Xa(b,8)|0;h=Xa(b,4)|0;i=a+20|0;c[i>>2]=h+1;a:do if((e|0)<1){if(!a){j=0;return j|0}}else if((f|0)>=1?!((h|0)<0|(g|0)<1):0){if((h|0)<=-1){j=a;return j|0}k=a+24|0;l=d+24|0;m=0;while(1){n=Xa(b,8)|0;c[k+(m<<2)>>2]=n;if((n|0)<0)break a;if((n|0)>=(c[l>>2]|0))break a;o=c[d+1824+(n<<2)>>2]|0;if(!(c[o+12>>2]|0))break a;m=m+1|0;if((c[o>>2]|0)<1)break a;if((m|0)>=(c[i>>2]|0)){j=a;break}}return j|0}while(0);fd(a);j=0;return j|0}function jb(a,b){a=a|0;b=b|0;a=gd(1,32)|0;c[a+4>>2]=c[b>>2];c[a>>2]=c[b+8>>2];c[a+20>>2]=b;c[a+8>>2]=gd(2,4)|0;return a|0}function kb(a){a=a|0;if(a|0)fd(a);return}function lb(a){a=a|0;var b=0,d=0,e=0,f=0,g=0;if(!a)return;b=a+8|0;d=c[b>>2]|0;if(d|0){e=c[d>>2]|0;if(!e)f=d;else{fd(e);f=c[b>>2]|0}e=c[f+4>>2]|0;if(!e)g=f;else{fd(e);g=c[b>>2]|0}fd(g)}fd(a);return}function mb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,h=0,i=0,j=0.0,k=0.0,l=0,m=0,n=0;d=c[b+20>>2]|0;e=a+4|0;f=d+12|0;h=Xa(e,c[f>>2]|0)|0;if((h|0)<=0){i=0;return i|0}j=+(h|0)/+((1<<c[f>>2])+-1|0)*+(c[d+16>>2]|0);f=d+20|0;h=Xa(e,nb(c[f>>2]|0)|0)|0;if((h|0)==-1){i=0;return i|0}if((h|0)>=(c[f>>2]|0)){i=0;return i|0}f=(c[(c[(c[(c[a+64>>2]|0)+4>>2]|0)+28>>2]|0)+2848>>2]|0)+((c[d+24+(h<<2)>>2]|0)*56|0)|0;h=b+4|0;b=eb(a,((c[f>>2]|0)+(c[h>>2]|0)<<2)+4|0)|0;if((ob(f,b,e,c[h>>2]|0)|0)==-1){i=0;return i|0}e=c[h>>2]|0;if((e|0)>0){h=0;k=0.0;while(1){a:do if((h|0)<(e|0)){a=c[f>>2]|0;d=h;l=0;while(1){if((l|0)>=(a|0)){m=d;break a}n=b+(d<<2)|0;g[n>>2]=+g[n>>2]+k;n=d+1|0;if((n|0)<(e|0)){d=n;l=l+1|0}else{m=n;break}}}else m=h;while(0);if((m|0)<(e|0)){h=m;k=+g[b+(m+-1<<2)>>2]}else break}}g[b+(e<<2)>>2]=j;i=b;return i|0}function nb(a){a=a|0;var b=0,c=0,d=0;if(!a)b=0;else{c=a;a=0;while(1){d=a+1|0;c=c>>>1;if(!c){b=d;break}else a=d}}return b|0}function ob(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0;f=(e|0)>0;if((c[a+8>>2]|0)<=0){if(!f){g=0;return g|0}md(b|0,0,e<<2|0)|0;g=0;return g|0}if(!f){g=0;return g|0}f=a+16|0;h=0;while(1){i=gb(a,d)|0;if((i|0)==-1){g=-1;j=11;break}k=c[a>>2]|0;l=(c[f>>2]|0)+((_(k,i)|0)<<2)|0;a:do if((h|0)<(e|0)){i=h;m=0;while(1){if((m|0)>=(k|0)){n=i;break a}o=i+1|0;c[b+(i<<2)>>2]=c[l+(m<<2)>>2];if((o|0)<(e|0)){i=o;m=m+1|0}else{n=o;break}}}else n=h;while(0);if((n|0)<(e|0))h=n;else{g=0;j=11;break}}if((j|0)==11)return g|0;return 0}function pb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0.0,o=0.0,p=0.0,q=0.0,r=0,s=0,t=0,u=0,v=0;f=c[b+20>>2]|0;h=c[a+28>>2]|0;i=b+8|0;j=(c[i>>2]|0)+(h<<2)|0;if(!(c[j>>2]|0)){k=c[(c[(c[(c[a+64>>2]|0)+4>>2]|0)+28>>2]|0)+(h<<2)>>2]|0;a=(k|0)/2|0;l=c[b>>2]|0;m=f+4|0;n=+(c[m>>2]|0);c[j>>2]=ed((a<<2)+4|0)|0;a:do if((k|0)>1){o=+(l|0)/(+V(+(n*n*4.624999938585006e-09))*2.240000009536743+n*4.999999873689376e-05+ +V(+(n*3.699999942909926e-04))*13.100000381469727);p=+(c[m>>2]|0)*.5/+(a|0);q=o;j=c[(c[i>>2]|0)+(h<<2)>>2]|0;r=l;s=0;while(1){o=+(s|0)*p;t=~~+M(+((+V(+(o*o*1.8499999754340024e-08))*2.240000009536743+ +V(+(o*7.399999885819852e-04))*13.100000381469727+o*9.999999747378752e-05)*q));c[j+(s<<2)>>2]=(t|0)<(r|0)?t:r+-1|0;t=s+1|0;if((t|0)>=(a|0)){u=t;break a}r=c[b>>2]|0;s=t}}else u=0;while(0);c[(c[(c[i>>2]|0)+(h<<2)>>2]|0)+(u<<2)>>2]=-1;c[b+12+(h<<2)>>2]=a}if(!d){md(e|0,0,c[b+12+(h<<2)>>2]<<2|0)|0;v=0;return v|0}else{a=c[b+4>>2]|0;qb(e,c[(c[i>>2]|0)+(h<<2)>>2]|0,c[b+12+(h<<2)>>2]|0,c[b>>2]|0,d,a,+g[d+(a<<2)>>2],+(c[f+16>>2]|0));v=1;return v|0}return 0}function qb(a,b,d,e,f,h,i,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;i=+i;j=+j;var k=0.0,l=0,m=0.0,n=0,o=0.0,p=0.0,q=0.0,r=0,s=0,t=0,u=0,v=0.0,w=0.0,x=0.0,y=0.0,z=0.0,A=0;k=3.141592653589793/+(e|0);if((h|0)>0){e=0;do{l=f+(e<<2)|0;g[l>>2]=+Q(+(+g[l>>2]))*2.0;e=e+1|0}while((e|0)!=(h|0))}if((d|0)<=0)return;m=i;i=j;if((h|0)<=1){e=(h|0)==1;l=0;while(1){n=c[b+(l<<2)>>2]|0;j=+Q(+(+(n|0)*k))*2.0;if(e){o=(j-+g[f>>2])*.5;p=4.0-j*j;q=o*o}else{p=2.0-j;q=(j+2.0)*.25}j=+X(+((m/+O(+(q+p*.25))-i)*.1151292473077774));r=a+(l<<2)|0;g[r>>2]=+g[r>>2]*j;r=l+1|0;if((c[b+(r<<2)>>2]|0)==(n|0)){s=r;while(1){t=a+(s<<2)|0;g[t>>2]=+g[t>>2]*j;t=s+1|0;if((c[b+(t<<2)>>2]|0)==(n|0))s=t;else{u=t;break}}}else u=r;if((u|0)<(d|0))l=u;else break}return}u=h+-2|0;l=((u&-2)+3|0)==(h|0);e=f+((u|1)+1<<2)|0;u=0;while(1){s=c[b+(u<<2)>>2]|0;p=+Q(+(+(s|0)*k))*2.0;n=1;q=.5;j=.5;while(1){o=(p-+g[f+(n+-1<<2)>>2])*j;v=(p-+g[f+(n<<2)>>2])*q;n=n+2|0;if((n|0)>=(h|0)){w=o;x=v;break}else{q=v;j=o}}if(l){j=(p-+g[e>>2])*w;y=x*x*(4.0-p*p);z=j*j}else{y=x*x*(2.0-p);z=w*w*(p+2.0)}j=+X(+((m/+O(+(z+y))-i)*.1151292473077774));n=a+(u<<2)|0;g[n>>2]=+g[n>>2]*j;n=u+1|0;if((c[b+(n<<2)>>2]|0)==(s|0)){r=n;while(1){t=a+(r<<2)|0;g[t>>2]=+g[t>>2]*j;t=r+1|0;if((c[b+(t<<2)>>2]|0)==(s|0))r=t;else{A=t;break}}}else A=n;if((A|0)<(d|0))u=A;else break}return}function rb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;d=gd(1,2840)|0;e=c[a+28>>2]|0;c[d>>2]=Xa(b,24)|0;c[d+4>>2]=Xa(b,24)|0;c[d+8>>2]=(Xa(b,24)|0)+1;a=Xa(b,6)|0;f=d+12|0;c[f>>2]=a+1;g=Xa(b,8)|0;h=d+20|0;c[h>>2]=g;a:do if((g|0)>=0){if((a|0)>-1){i=d+24|0;j=0;k=0;while(1){l=Xa(b,3)|0;m=Xa(b,1)|0;if((m|0)<0){n=25;break a}if(m){m=Xa(b,5)|0;if(!(m>>31&2))o=((m|0)<0?0:m<<3)|l;else{n=25;break a}}else o=l;c[i+(k<<2)>>2]=o;if(!o)p=0;else{l=o;m=0;while(1){q=(l&1)+m|0;l=l>>>1;if(!l){p=q;break}else m=q}}m=p+j|0;k=k+1|0;if((k|0)>=(c[f>>2]|0)){r=m;break}else j=m}j=(r|0)>0;if(j){k=d+280|0;i=0;while(1){m=Xa(b,8)|0;if((m|0)<0)break a;c[k+(i<<2)>>2]=m;i=i+1|0;if((i|0)>=(r|0)){s=j;t=r;break}}}else{s=0;t=r}}else{s=0;t=0}j=c[h>>2]|0;i=c[e+24>>2]|0;if((j|0)<(i|0)){if(s){k=d+280|0;m=0;do{l=c[k+(m<<2)>>2]|0;if((l|0)>=(i|0))break a;m=m+1|0;if(!(c[(c[e+1824+(l<<2)>>2]|0)+12>>2]|0))break a}while((m|0)<(t|0))}m=c[e+1824+(j<<2)>>2]|0;i=c[m+4>>2]|0;k=c[m>>2]|0;if((k|0)>=1){m=c[f>>2]|0;l=k;k=1;while(1){q=_(m,k)|0;if((q|0)>(i|0))break a;if((l|0)>1){l=l+-1|0;k=q}else{u=q;break}}c[d+16>>2]=u;v=d;return v|0}}}else n=25;while(0);if((n|0)==25?(d|0)==0:0){v=0;return v|0}fd(d);v=0;return v|0}function sb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;d=gd(1,44)|0;e=c[(c[a+4>>2]|0)+28>>2]|0;c[d>>2]=b;a=c[b+12>>2]|0;f=d+4|0;c[f>>2]=a;g=e+2848|0;e=c[g>>2]|0;c[d+12>>2]=e;h=e+((c[b+20>>2]|0)*56|0)|0;c[d+16>>2]=h;e=c[h>>2]|0;h=gd(a,4)|0;c[d+20>>2]=h;if((a|0)>0){i=b+24|0;j=b+280|0;b=0;k=0;l=0;while(1){m=i+(k<<2)|0;n=c[m>>2]|0;if(n){o=n;n=0;while(1){p=n+1|0;o=o>>>1;if(!o){q=p;r=n;break}else n=p}n=(q|0)>(l|0)?q:l;c[h+(k<<2)>>2]=gd(q,4)|0;if((r|0)<0){s=b;t=n}else{o=c[m>>2]|0;p=h+(k<<2)|0;u=b;v=0;while(1){if(!(o&1<<v))w=u;else{c[(c[p>>2]|0)+(v<<2)>>2]=(c[g>>2]|0)+((c[j+(u<<2)>>2]|0)*56|0);w=u+1|0}v=v+1|0;if((v|0)==(q|0)){s=w;t=n;break}else u=w}}}else{s=b;t=l}k=k+1|0;if((k|0)>=(a|0)){x=t;break}else{b=s;l=t}}}else x=0;t=d+24|0;c[t>>2]=1;l=(e|0)>0;if(l){s=c[f>>2]|0;b=1;a=0;while(1){k=_(b,s)|0;a=a+1|0;if((a|0)==(e|0)){y=k;break}else b=k}c[t>>2]=y;z=y}else z=1;c[d+8>>2]=x;x=ed(z<<2)|0;y=d+28|0;c[y>>2]=x;if((z|0)<=0)return d|0;t=e<<2;if(!l){l=0;do{c[x+(l<<2)>>2]=ed(t)|0;l=l+1|0}while((l|0)<(z|0));return d|0}l=c[f>>2]|0;f=c[y>>2]|0;y=0;do{c[x+(y<<2)>>2]=ed(t)|0;b=c[f+(y<<2)>>2]|0;a=z;s=0;k=y;do{a=(a|0)/(l|0)|0;w=(k|0)/(a|0)|0;k=k-(_(w,a)|0)|0;c[b+(s<<2)>>2]=w;s=s+1|0}while((s|0)!=(e|0));y=y+1|0}while((y|0)<(z|0));return d|0}function tb(a){a=a|0;if(a|0)fd(a);return}function ub(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;if(!a)return;b=a+4|0;d=c[b>>2]|0;e=a+20|0;if((d|0)>0){f=d;d=0;while(1){g=c[(c[e>>2]|0)+(d<<2)>>2]|0;if(!g)h=f;else{fd(g);h=c[b>>2]|0}d=d+1|0;if((d|0)>=(h|0))break;else f=h}}fd(c[e>>2]|0);e=a+24|0;h=a+28|0;if((c[e>>2]|0)>0){f=0;do{fd(c[(c[h>>2]|0)+(f<<2)>>2]|0);f=f+1|0}while((f|0)<(c[e>>2]|0))}fd(c[h>>2]|0);fd(a);return}function vb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0;if((f|0)>0){g=0;h=0}else return 0;while(1){if(!(c[e+(g<<2)>>2]|0))i=h;else{c[d+(h<<2)>>2]=c[d+(g<<2)>>2];i=h+1|0}g=g+1|0;if((g|0)==(f|0)){j=i;break}else h=i}if(!j)return 0;xb(a,b,d,j,3);return 0}function wb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;f=i;if((c[a+8>>2]|0)<=0){h=0;i=f;return h|0}j=c[a>>2]|0;k=(e|0)/(j|0)|0;e=i;i=i+((1*(k<<2)|0)+15&-16)|0;l=(k|0)>0;a:do if(l){m=a+16|0;n=0;while(1){o=gb(a,d)|0;if((o|0)==-1){h=-1;break}p=c[a>>2]|0;c[e+(n<<2)>>2]=(c[m>>2]|0)+((_(p,o)|0)<<2);n=n+1|0;if((n|0)>=(k|0)){q=p;break a}}i=f;return h|0}else q=j;while(0);if((q|0)<1|l^1){h=0;i=f;return h|0}else{r=0;s=0}while(1){l=0;do{j=b+(l+s<<2)|0;g[j>>2]=+g[j>>2]+ +g[(c[e+(l<<2)>>2]|0)+(r<<2)>>2];l=l+1|0}while((l|0)!=(k|0));r=r+1|0;if((r|0)>=(q|0)){h=0;break}else s=s+k|0}i=f;return h|0}function xb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0;g=i;h=c[b>>2]|0;j=c[h+8>>2]|0;k=b+16|0;l=c[c[k>>2]>>2]|0;m=c[a+36>>2]>>1;n=c[h+4>>2]|0;o=((n|0)<(m|0)?n:m)-(c[h>>2]|0)|0;if((o|0)<=0){i=g;return}m=(o|0)/(j|0)|0;o=i;i=i+((1*(e<<2)|0)+15&-16)|0;n=(e|0)>0;if(n){p=((l+-1+m|0)/(l|0)|0)<<2;q=0;do{c[o+(q<<2)>>2]=eb(a,p)|0;q=q+1|0}while((q|0)!=(e|0))}q=b+8|0;p=c[q>>2]|0;if((p|0)<=0){i=g;return}r=(m|0)>0;s=(l|0)>0;t=b+20|0;u=a+4|0;a=h+16|0;v=b+28|0;b=0-l|0;w=(e|0)<1;x=p;p=0;a:while(1){if(r){y=1<<p;z=(p|0)!=0|w;A=0;B=0;while(1){if(!z){C=0;do{D=fb(c[k>>2]|0,u)|0;if((D|0)==-1){E=26;break a}if((D|0)>=(c[a>>2]|0)){E=26;break a}F=c[(c[v>>2]|0)+(D<<2)>>2]|0;c[(c[o+(C<<2)>>2]|0)+(B<<2)>>2]=F;C=C+1|0;if(!F){E=26;break a}}while((C|0)<(e|0))}do if(s&(A|0)<(m|0)){if(n){G=A;H=0}else{C=A-m|0;I=A-(C>>>0<b>>>0?b:C)|0;break}while(1){C=_(G,j)|0;F=0;do{D=(c[h>>2]|0)+C|0;J=c[(c[(c[o+(F<<2)>>2]|0)+(B<<2)>>2]|0)+(H<<2)>>2]|0;if((c[h+24+(J<<2)>>2]&y|0?(K=c[(c[(c[t>>2]|0)+(J<<2)>>2]|0)+(p<<2)>>2]|0,K|0):0)?(Aa[f&7](K,(c[d+(F<<2)>>2]|0)+(D<<2)|0,u,j)|0)==-1:0){E=26;break a}F=F+1|0}while((F|0)<(e|0));H=H+1|0;F=G+1|0;if(!((H|0)<(l|0)&(F|0)<(m|0))){I=F;break}else G=F}}else I=A;while(0);if((I|0)<(m|0)){A=I;B=B+1|0}else break}L=c[q>>2]|0}else L=x;p=p+1|0;if((p|0)>=(L|0)){E=26;break}else x=L}if((E|0)==26){i=g;return}}function yb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;Sa(b,c[a>>2]|0,24);Sa(b,c[a+4>>2]|0,24);Sa(b,(c[a+8>>2]|0)+-1|0,24);d=a+12|0;Sa(b,(c[d>>2]|0)+-1|0,6);Sa(b,c[a+20>>2]|0,8);if((c[d>>2]|0)<=0)return;e=a+24|0;f=0;g=0;while(1){h=e+(g<<2)|0;i=c[h>>2]|0;if(i){j=i;k=0;while(1){j=j>>>1;if(!j){l=k;break}else k=k+1|0}if((l|0)>2){Sa(b,i,3);Sa(b,1,1);Sa(b,c[h>>2]>>3,5)}else m=9}else m=9;if((m|0)==9){m=0;Sa(b,i,4)}k=c[h>>2]|0;if(!k)n=0;else{j=k;k=0;while(1){o=(j&1)+k|0;j=j>>>1;if(!j){n=o;break}else k=o}}k=n+f|0;g=g+1|0;if((g|0)>=(c[d>>2]|0)){p=k;break}else f=k}if((p|0)<=0)return;f=a+280|0;a=0;do{Sa(b,c[f+(a<<2)>>2]|0,8);a=a+1|0}while((a|0)!=(p|0));return}function zb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0.0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0;if((f|0)>0){g=0;h=0}else{i=0;return i|0}while(1){if(!(c[e+(g<<2)>>2]|0))j=h;else{c[d+(h<<2)>>2]=c[d+(g<<2)>>2];j=h+1|0}g=g+1|0;if((g|0)==(f|0)){k=j;break}else h=j}if(!k){i=0;return i|0}j=c[b>>2]|0;h=c[j+8>>2]|0;f=c[j+12>>2]|0;g=((c[j+4>>2]|0)-(c[j>>2]|0)|0)/(h|0)|0;e=eb(a,k<<2)|0;l=100.0/+(h|0);m=(k|0)>0;if(m){n=g<<2;o=0;do{p=eb(a,n)|0;c[e+(o<<2)>>2]=p;md(p|0,0,n|0)|0;o=o+1|0}while((o|0)!=(k|0))}if((g|0)>0){o=(h|0)>0;n=f+-1|0;a=(f|0)>1;f=0;do{p=_(f,h)|0;q=(c[j>>2]|0)+p|0;a:do if(m){if(!o){if(a)r=0;else{p=0;while(1){c[(c[e+(p<<2)>>2]|0)+(f<<2)>>2]=0;p=p+1|0;if((p|0)==(k|0))break a}}while(1){p=0;while(1){if((c[j+2328+(p<<2)>>2]|0)>=0?c[j+2584+(p<<2)>>2]|0:0){s=p;break}t=p+1|0;if((t|0)<(n|0))p=t;else{s=t;break}}c[(c[e+(r<<2)>>2]|0)+(f<<2)>>2]=s;r=r+1|0;if((r|0)==(k|0))break a}}if(a)u=0;else{p=0;while(1){c[(c[e+(p<<2)>>2]|0)+(f<<2)>>2]=0;p=p+1|0;if((p|0)==(k|0))break a}}do{p=c[d+(u<<2)>>2]|0;t=0;v=0;w=0;while(1){x=c[p+(q+v<<2)>>2]|0;y=(x|0)>-1?x:0-x|0;x=(y|0)>(w|0)?y:w;z=y+t|0;v=v+1|0;if((v|0)==(h|0)){A=z;B=x;break}else{t=z;w=x}}w=~~(+(A|0)*l);t=0;while(1){if((B|0)<=(c[j+2328+(t<<2)>>2]|0)?(v=c[j+2584+(t<<2)>>2]|0,(v|0)<0|(w|0)<(v|0)):0){C=t;break}v=t+1|0;if((v|0)<(n|0))t=v;else{C=v;break}}c[(c[e+(u<<2)>>2]|0)+(f<<2)>>2]=C;u=u+1|0}while((u|0)!=(k|0))}while(0);f=f+1|0}while((f|0)!=(g|0))}g=b+40|0;c[g>>2]=(c[g>>2]|0)+1;i=e;return i|0}function Ab(a,b,d,e,f,g,h,i){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;var j=0,k=0,l=0,m=0;if((g|0)>0){j=0;k=0}else return 0;while(1){if(!(c[f+(j<<2)>>2]|0))l=k;else{c[e+(k<<2)>>2]=c[e+(j<<2)>>2];l=k+1|0}j=j+1|0;if((j|0)==(g|0)){m=l;break}else k=l}if(!m)return 0;Bb(a,d,e,m,h);return 0}function Bb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0,ua=0,va=0,wa=0,xa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0;g=i;i=i+1088|0;h=g+1056|0;j=g+1024|0;k=g+512|0;l=g;m=c[b>>2]|0;n=c[m+8>>2]|0;o=c[m+12>>2]|0;p=b+16|0;q=c[c[p>>2]>>2]|0;r=((c[m+4>>2]|0)-(c[m>>2]|0)|0)/(n|0)|0;md(k|0,0,512)|0;md(l|0,0,512)|0;s=b+8|0;t=c[s>>2]|0;if((t|0)<=0){i=g;return}u=(r|0)>0;v=(q|0)>0;w=(e|0)>0;x=b+20|0;y=b+32|0;z=(q|0)>1;A=b+36|0;b=(e|0)<1;B=t;t=0;while(1){if(u){C=(t|0)==0;D=1<<t;E=b|C^1;F=0;while(1){a:do if(!E){if(z)G=0;else{H=0;while(1){I=c[(c[f+(H<<2)>>2]|0)+(F<<2)>>2]|0;J=c[p>>2]|0;if((I|0)<(c[J+4>>2]|0)){K=Cb(J,I,a)|0;c[A>>2]=(c[A>>2]|0)+K}H=H+1|0;if((H|0)==(e|0))break a}}do{H=c[f+(G<<2)>>2]|0;K=1;I=c[H+(F<<2)>>2]|0;while(1){J=_(I,o)|0;L=K+F|0;if((L|0)<(r|0))M=(c[H+(L<<2)>>2]|0)+J|0;else M=J;K=K+1|0;if((K|0)==(q|0)){N=M;break}else I=M}I=c[p>>2]|0;if((N|0)<(c[I+4>>2]|0)){K=Cb(I,N,a)|0;c[A>>2]=(c[A>>2]|0)+K}G=G+1|0}while((G|0)!=(e|0))}while(0);if(v&(F|0)<(r|0)){K=F;I=0;while(1){H=_(K,n)|0;J=(c[m>>2]|0)+H|0;if(w){H=0;do{L=f+(H<<2)|0;O=c[L>>2]|0;P=c[O+(K<<2)>>2]|0;if(C){Q=l+(P<<2)|0;c[Q>>2]=(c[Q>>2]|0)+n}if(c[m+24+(P<<2)>>2]&D|0?(Q=c[(c[(c[x>>2]|0)+(P<<2)>>2]|0)+(t<<2)>>2]|0,Q|0):0){P=(c[d+(H<<2)>>2]|0)+(J<<2)|0;R=c[Q>>2]|0;S=(n|0)/(R|0)|0;if((S|0)>0){T=Q+48|0;U=Q+52|0;V=Q+44|0;W=Q+12|0;X=Q+4|0;Y=R;Z=0;$=0;while(1){aa=P+((_($,R)|0)<<2)|0;ba=c[T>>2]|0;ca=c[U>>2]|0;da=c[V>>2]|0;ea=da>>1;c[h>>2]=0;c[h+4>>2]=0;c[h+8>>2]=0;c[h+12>>2]=0;c[h+16>>2]=0;c[h+20>>2]=0;c[h+24>>2]=0;c[h+28>>2]=0;fa=(Y|0)>0;do if((ca|0)==1){if(!fa){ga=0;break}ha=da+-1|0;od(h|0,aa|0,Y<<2|0)|0;ia=0;ja=0;ka=Y;while(1){ka=ka+-1|0;la=(c[aa+(ka<<2)>>2]|0)-ba|0;if((la|0)<(ea|0))ma=(ea-la<<1)+-1|0;else ma=la-ea<<1;la=_(ja,da)|0;na=((ma|0)<0?0:(ma|0)>=(da|0)?ha:ma)+la|0;ia=ia+1|0;if((ia|0)==(Y|0)){ga=na;break}else ja=na}}else{if(!fa){ga=0;break}ja=(ca>>1)-ba|0;ia=da+-1|0;ha=0;ka=0;na=Y;while(1){na=na+-1|0;la=(ja+(c[aa+(na<<2)>>2]|0)|0)/(ca|0)|0;if((la|0)<(ea|0))oa=(ea-la<<1)+-1|0;else oa=la-ea<<1;pa=_(ka,da)|0;qa=((oa|0)<0?0:(oa|0)>=(da|0)?ia:oa)+pa|0;c[h+(na<<2)>>2]=(_(la,ca)|0)+ba;ha=ha+1|0;if((ha|0)==(Y|0)){ga=qa;break}else ka=qa}}while(0);ea=c[(c[W>>2]|0)+8>>2]|0;if((c[ea+(ga<<2)>>2]|0)<1){c[j>>2]=0;c[j+4>>2]=0;c[j+8>>2]=0;c[j+12>>2]=0;c[j+16>>2]=0;c[j+20>>2]=0;c[j+24>>2]=0;c[j+28>>2]=0;ka=(_(da+-1|0,ca)|0)+ba|0;ha=c[X>>2]|0;b:do if((ha|0)>0){if(fa){ra=-1;sa=0;ta=ga}else{na=-1;ia=0;ja=ga;while(1){do if((c[ea+(ia<<2)>>2]|0)>0){if(!((na|0)==-1|(na|0)>0)){ua=na;va=ja;break};c[h>>2]=c[j>>2];c[h+4>>2]=c[j+4>>2];c[h+8>>2]=c[j+8>>2];c[h+12>>2]=c[j+12>>2];c[h+16>>2]=c[j+16>>2];c[h+20>>2]=c[j+20>>2];c[h+24>>2]=c[j+24>>2];c[h+28>>2]=c[j+28>>2];ua=0;va=ia}else{ua=na;va=ja}while(0);qa=c[j>>2]|0;if((qa|0)<(ka|0)){wa=j;xa=qa}else{qa=j;la=0;while(1){la=la+1|0;c[qa>>2]=0;pa=j+(la<<2)|0;ya=c[pa>>2]|0;if((ya|0)<(ka|0)){wa=pa;xa=ya;break}else qa=pa}}if((xa|0)>-1){qa=xa+ca|0;c[wa>>2]=qa;za=qa}else za=xa;c[wa>>2]=0-za;ia=ia+1|0;if((ia|0)==(ha|0)){Aa=va;break b}else{na=ua;ja=va}}}while(1){do if((c[ea+(sa<<2)>>2]|0)>0){ja=0;na=0;while(1){ia=(c[j+(ja<<2)>>2]|0)-(c[aa+(ja<<2)>>2]|0)|0;qa=(_(ia,ia)|0)+na|0;ja=ja+1|0;if((ja|0)==(Y|0)){Ba=qa;break}else na=qa}if(!((ra|0)==-1|(Ba|0)<(ra|0))){Ca=ra;Da=ta;break};c[h>>2]=c[j>>2];c[h+4>>2]=c[j+4>>2];c[h+8>>2]=c[j+8>>2];c[h+12>>2]=c[j+12>>2];c[h+16>>2]=c[j+16>>2];c[h+20>>2]=c[j+20>>2];c[h+24>>2]=c[j+24>>2];c[h+28>>2]=c[j+28>>2];Ca=Ba;Da=sa}else{Ca=ra;Da=ta}while(0);na=c[j>>2]|0;if((na|0)<(ka|0)){Ea=j;Fa=na}else{na=j;ja=0;while(1){ja=ja+1|0;c[na>>2]=0;qa=j+(ja<<2)|0;ia=c[qa>>2]|0;if((ia|0)<(ka|0)){Ea=qa;Fa=ia;break}else na=qa}}if((Fa|0)>-1){na=Fa+ca|0;c[Ea>>2]=na;Ga=na}else Ga=Fa;c[Ea>>2]=0-Ga;sa=sa+1|0;if((sa|0)==(ha|0)){Aa=Da;break}else{ra=Ca;ta=Da}}}else Aa=ga;while(0);Ha=Aa}else Ha=ga;if(fa&(Ha|0)>-1){ha=aa;ca=0;while(1){c[ha>>2]=(c[ha>>2]|0)-(c[h+(ca<<2)>>2]|0);ca=ca+1|0;if((ca|0)==(Y|0))break;else ha=ha+4|0}}ha=(Cb(Q,Ha,a)|0)+Z|0;ca=$+1|0;if((ca|0)==(S|0)){Ia=ha;break}Y=c[Q>>2]|0;Z=ha;$=ca}Ja=c[L>>2]|0;Ka=Ia}else{Ja=O;Ka=0}c[y>>2]=(c[y>>2]|0)+Ka;$=k+(c[Ja+(K<<2)>>2]<<2)|0;c[$>>2]=(c[$>>2]|0)+Ka}H=H+1|0}while((H|0)!=(e|0))}I=I+1|0;H=K+1|0;if(!((I|0)<(q|0)&(H|0)<(r|0))){La=H;break}else K=H}}else La=F;if((La|0)<(r|0))F=La;else break}Ma=c[s>>2]|0}else Ma=B;t=t+1|0;if((t|0)>=(Ma|0))break;else B=Ma}i=g;return}function Cb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0;if((b|0)<0){e=0;return e|0}f=a+12|0;g=c[f>>2]|0;if((c[g+4>>2]|0)<=(b|0)){e=0;return e|0}Sa(d,c[(c[a+20>>2]|0)+(b<<2)>>2]|0,c[(c[g+8>>2]|0)+(b<<2)>>2]|0);e=c[(c[(c[f>>2]|0)+8>>2]|0)+(b<<2)>>2]|0;return e|0}function Db(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0;if((f|0)>0){g=0;h=0}else return 0;while(1){if(!(c[e+(g<<2)>>2]|0))i=h;else{c[d+(h<<2)>>2]=c[d+(g<<2)>>2];i=h+1|0}g=g+1|0;if((g|0)==(f|0)){j=i;break}else h=i}if(!j)return 0;xb(a,b,d,j,4);return 0}function Eb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0;if((c[a+8>>2]|0)<=0){f=0;return f|0}if((c[a>>2]|0)>8){if((e|0)<=0){f=0;return f|0}h=a+16|0;i=0;while(1){j=gb(a,d)|0;if((j|0)==-1){f=-1;k=28;break}l=c[a>>2]|0;m=(c[h>>2]|0)+((_(l,j)|0)<<2)|0;if((l|0)>0){j=i;n=0;while(1){o=j+1|0;p=b+(j<<2)|0;g[p>>2]=+g[p>>2]+ +g[m+(n<<2)>>2];n=n+1|0;if((n|0)>=(l|0)){q=o;break}else j=o}}else q=i;if((q|0)<(e|0))i=q;else{f=0;k=28;break}}if((k|0)==28)return f|0}q=a+16|0;if((e|0)>0)r=0;else{f=0;return f|0}a:while(1){b:while(1){i=gb(a,d)|0;if((i|0)==-1){f=-1;k=28;break a}h=c[q>>2]|0;switch(c[a>>2]|0){case 8:{s=i;t=h;k=20;break b;break}case 7:{u=i;v=h;k=21;break b;break}case 6:{w=i;x=h;k=22;break b;break}case 5:{y=i;z=h;k=23;break b;break}case 4:{A=i;B=h;k=24;break b;break}case 3:{C=i;D=h;k=25;break b;break}case 2:{E=i;F=h;k=26;break b;break}case 1:{G=i;H=h;k=27;break b;break}default:{}}}if((k|0)==20){k=0;h=t+(s<<3<<2)|0;i=b+(r<<2)|0;g[i>>2]=+g[i>>2]+ +g[h>>2];I=h;J=r+1|0;K=1;k=10}else if((k|0)==21){k=0;I=v+(u*7<<2)|0;J=r;K=0;k=10}else if((k|0)==22){k=0;L=x+(w*6<<2)|0;M=r;N=0;k=11}else if((k|0)==23){k=0;O=z+(y*5<<2)|0;P=r;Q=0;k=12}else if((k|0)==24){k=0;R=B+(A<<2<<2)|0;S=r;T=0;k=13}else if((k|0)==25){k=0;U=D+(C*3<<2)|0;V=r;W=0;k=14}else if((k|0)==26){k=0;X=F+(E<<1<<2)|0;Y=r;Z=0;k=15}else if((k|0)==27){k=0;$=H+(G<<2)|0;aa=r;ba=0}if((k|0)==10){k=0;h=b+(J<<2)|0;g[h>>2]=+g[h>>2]+ +g[I+(K<<2)>>2];L=I;M=J+1|0;N=K+1|0;k=11}if((k|0)==11){k=0;h=b+(M<<2)|0;g[h>>2]=+g[h>>2]+ +g[L+(N<<2)>>2];O=L;P=M+1|0;Q=N+1|0;k=12}if((k|0)==12){k=0;h=b+(P<<2)|0;g[h>>2]=+g[h>>2]+ +g[O+(Q<<2)>>2];R=O;S=P+1|0;T=Q+1|0;k=13}if((k|0)==13){k=0;h=b+(S<<2)|0;g[h>>2]=+g[h>>2]+ +g[R+(T<<2)>>2];U=R;V=S+1|0;W=T+1|0;k=14}if((k|0)==14){k=0;h=b+(V<<2)|0;g[h>>2]=+g[h>>2]+ +g[U+(W<<2)>>2];X=U;Y=V+1|0;Z=W+1|0;k=15}if((k|0)==15){k=0;h=b+(Y<<2)|0;g[h>>2]=+g[h>>2]+ +g[X+(Z<<2)>>2];$=X;aa=Y+1|0;ba=Z+1|0}r=aa+1|0;h=b+(aa<<2)|0;g[h>>2]=+g[h>>2]+ +g[$+(ba<<2)>>2];if((r|0)>=(e|0)){f=0;k=28;break}}if((k|0)==28)return f|0;return 0}function Fb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0;if((f|0)>0){g=0;h=0}else{i=0;return i|0}while(1){j=((c[e+(g<<2)>>2]|0)!=0&1)+h|0;g=g+1|0;if((g|0)==(f|0)){k=j;break}else h=j}if(!k){i=0;return i|0}k=c[b>>2]|0;h=c[k+8>>2]|0;g=c[k+12>>2]|0;e=((c[k+4>>2]|0)-(c[k>>2]|0)|0)/(h|0)|0;j=eb(a,4)|0;l=e<<2;m=eb(a,l)|0;c[j>>2]=m;md(m|0,0,l|0)|0;a:do if((e|0)>0){m=g+-1|0;a=(g|0)>1;n=c[j>>2]|0;if((h|0)<=0){if(a)o=0;else{md(n|0,0,l|0)|0;break}while(1){p=0;while(1){if((c[k+2328+(p<<2)>>2]|0)>=0?(c[k+2584+(p<<2)>>2]|0)>=0:0){q=p;break}r=p+1|0;if((r|0)<(m|0))p=r;else{q=r;break}}c[n+(o<<2)>>2]=q;o=o+1|0;if((o|0)==(e|0))break a}}p=(c[k>>2]|0)/(f|0)|0;if((f|0)>1){s=0;t=p}else{r=0;u=p;while(1){p=c[d>>2]|0;v=0;w=u;x=0;while(1){y=c[p+(w<<2)>>2]|0;z=(y|0)>-1?y:0-y|0;y=(z|0)>(x|0)?z:x;z=w+1|0;v=v+f|0;if((v|0)>=(h|0)){A=z;B=y;break}else{w=z;x=y}}b:do if(a){x=0;while(1){if((B|0)<=(c[k+2328+(x<<2)>>2]|0)?(c[k+2584+(x<<2)>>2]|0)>=0:0){C=x;break b}w=x+1|0;if((w|0)<(m|0))x=w;else{C=w;break}}}else C=0;while(0);c[n+(r<<2)>>2]=C;x=r+1|0;if((x|0)==(e|0))break a;else{r=x;u=A}}}while(1){u=c[d>>2]|0;r=0;x=0;w=t;v=0;while(1){p=c[u+(w<<2)>>2]|0;y=(p|0)>-1?p:0-p|0;p=r;z=1;while(1){D=c[(c[d+(z<<2)>>2]|0)+(w<<2)>>2]|0;E=(D|0)>-1?D:0-D|0;D=(E|0)>(p|0)?E:p;z=z+1|0;if((z|0)==(f|0)){F=D;break}else p=D}p=(y|0)>(v|0)?y:v;z=w+1|0;x=x+f|0;if((x|0)>=(h|0)){G=F;H=z;I=p;break}else{r=F;w=z;v=p}}c:do if(a){v=0;while(1){if((I|0)<=(c[k+2328+(v<<2)>>2]|0)?(G|0)<=(c[k+2584+(v<<2)>>2]|0):0){J=v;break c}w=v+1|0;if((w|0)<(m|0))v=w;else{J=w;break}}}else J=0;while(0);c[n+(s<<2)>>2]=J;v=s+1|0;if((v|0)==(e|0))break;else{s=v;t=H}}}while(0);H=b+40|0;c[H>>2]=(c[H>>2]|0)+1;i=j;return i|0}function Gb(a,b,d,e,f,g,h,j){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;j=j|0;var k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;j=i;i=i+16|0;k=j;l=c[b+36>>2]|0;m=(l|0)/2|0;n=eb(b,_(g<<2,m)|0)|0;c[k>>2]=n;if((g|0)<=0){i=j;return 0}if((l|0)>1){l=0;b=0;while(1){o=c[e+(l<<2)>>2]|0;p=(c[f+(l<<2)>>2]|0)!=0&1;q=0;r=l;while(1){c[n+(r<<2)>>2]=c[o+(q<<2)>>2];q=q+1|0;if((q|0)>=(m|0))break;else r=r+g|0}r=p+b|0;l=l+1|0;if((l|0)==(g|0)){s=r;break}else b=r}}else{b=0;l=0;while(1){m=((c[f+(b<<2)>>2]|0)!=0&1)+l|0;b=b+1|0;if((b|0)==(g|0)){s=m;break}else l=m}}if(!s){i=j;return 0}Bb(a,d,k,1,h);i=j;return 0}function Hb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0;g=c[b>>2]|0;h=c[g+8>>2]|0;i=b+16|0;j=c[c[i>>2]>>2]|0;k=(_(c[a+36>>2]|0,f)|0)>>1;l=c[g+4>>2]|0;m=((l|0)<(k|0)?l:k)-(c[g>>2]|0)|0;if((m|0)<=0)return 0;k=(m|0)/(h|0)|0;m=eb(a,((j+-1+k|0)/(j|0)|0)<<2)|0;a:do if((f|0)>0){l=0;while(1){if(c[e+(l<<2)>>2]|0){n=l;break a}o=l+1|0;if((o|0)<(f|0))l=o;else{n=o;break}}}else n=0;while(0);if((n|0)==(f|0))return 0;n=b+8|0;if((c[n>>2]|0)<=0)return 0;e=(k|0)>0;l=a+4|0;a=g+16|0;o=b+28|0;p=(j|0)>0;q=b+20|0;b=0;b:while(1){c:do if(e){r=1<<b;if(!b){s=0;t=0}else{u=0;v=0;while(1){if(p&(u|0)<(k|0)){w=m+(v<<2)|0;x=u;y=0;while(1){z=c[(c[w>>2]|0)+(y<<2)>>2]|0;if((c[g+24+(z<<2)>>2]&r|0?(A=c[(c[(c[q>>2]|0)+(z<<2)>>2]|0)+(b<<2)>>2]|0,A|0):0)?(z=_(x,h)|0,(Ib(A,d,(c[g>>2]|0)+z|0,f,l,h)|0)==-1):0){B=28;break b}y=y+1|0;z=x+1|0;if(!((y|0)<(j|0)&(z|0)<(k|0))){C=z;break}else x=z}}else C=u;if((C|0)<(k|0)){u=C;v=v+1|0}else break c}}while(1){v=fb(c[i>>2]|0,l)|0;if((v|0)==-1){B=28;break b}if((v|0)>=(c[a>>2]|0)){B=28;break b}u=c[(c[o>>2]|0)+(v<<2)>>2]|0;v=m+(t<<2)|0;c[v>>2]=u;if(!u){B=28;break b}d:do if(p&(s|0)<(k|0)){x=u;y=s;w=0;while(1){z=c[x+(w<<2)>>2]|0;if((c[g+24+(z<<2)>>2]&r|0?(A=c[c[(c[q>>2]|0)+(z<<2)>>2]>>2]|0,A|0):0)?(z=_(y,h)|0,(Ib(A,d,(c[g>>2]|0)+z|0,f,l,h)|0)==-1):0){B=28;break b}z=w+1|0;A=y+1|0;if(!((z|0)<(j|0)&(A|0)<(k|0))){D=A;break d}x=c[v>>2]|0;y=A;w=z}}else D=s;while(0);if((D|0)<(k|0)){s=D;t=t+1|0}else break}}while(0);b=b+1|0;if((b|0)>=(c[n>>2]|0)){B=28;break}}if((B|0)==28)return 0;return 0}function Ib(a,b,d,e,f,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;if((c[a+8>>2]|0)<=0){i=0;return i|0}j=(d|0)/(e|0)|0;k=(h+d|0)/(e|0)|0;if((j|0)>=(k|0)){i=0;return i|0}d=a+16|0;h=0;l=j;while(1){j=gb(a,f)|0;if((j|0)==-1){i=-1;m=8;break}n=c[a>>2]|0;o=(c[d>>2]|0)+((_(n,j)|0)<<2)|0;if((n|0)>0){j=h;p=l;q=0;while(1){r=j+1|0;s=(c[b+(j<<2)>>2]|0)+(p<<2)|0;g[s>>2]=+g[s>>2]+ +g[o+(q<<2)>>2];s=(r|0)==(e|0);t=(s&1)+p|0;u=s?0:r;q=q+1|0;if((q|0)>=(n|0)){v=u;w=t;break}else{j=u;p=t}}}else{v=h;w=l}if((w|0)<(k|0)){h=v;l=w}else{i=0;m=8;break}}if((m|0)==8)return i|0;return 0}function Jb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;if((c[b>>2]|0)>1){Sa(d,1,1);Sa(d,(c[b>>2]|0)+-1|0,4)}else Sa(d,0,1);e=b+1156|0;if((c[e>>2]|0)>0){Sa(d,1,1);Sa(d,(c[e>>2]|0)+-1|0,8);if((c[e>>2]|0)>0){f=b+1160|0;g=a+4|0;h=b+2184|0;i=0;do{j=c[f+(i<<2)>>2]|0;k=c[g>>2]|0;l=k+-1|0;if((k|0)==0|(l|0)==0)m=0;else{k=l;l=0;while(1){n=l+1|0;k=k>>>1;if(!k){m=n;break}else l=n}}Sa(d,j,m);l=c[h+(i<<2)>>2]|0;k=c[g>>2]|0;n=k+-1|0;if((k|0)==0|(n|0)==0)o=0;else{k=n;n=0;while(1){p=n+1|0;k=k>>>1;if(!k){o=p;break}else n=p}}Sa(d,l,o);i=i+1|0}while((i|0)<(c[e>>2]|0))}}else Sa(d,0,1);Sa(d,0,2);e=c[b>>2]|0;if((e|0)>1){i=a+4|0;if((c[i>>2]|0)>0){a=b+4|0;o=0;do{Sa(d,c[a+(o<<2)>>2]|0,4);o=o+1|0}while((o|0)<(c[i>>2]|0));q=c[b>>2]|0;r=17}}else{q=e;r=17}if((r|0)==17?(q|0)<=0:0)return;q=b+1028|0;r=b+1092|0;e=0;do{Sa(d,0,8);Sa(d,c[q+(e<<2)>>2]|0,8);Sa(d,c[r+(e<<2)>>2]|0,8);e=e+1|0}while((e|0)<(c[b>>2]|0));return}function Kb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;d=gd(1,3208)|0;e=c[a+28>>2]|0;md(d|0,0,3208)|0;f=Xa(b,1)|0;a:do if((f|0)<0){if(!d){g=0;return g|0}}else{if(f){h=Xa(b,4)|0;c[d>>2]=h+1;if((h|0)<0)break}else c[d>>2]=1;h=Xa(b,1)|0;if((h|0)>=0){if(h|0){h=Xa(b,8)|0;i=d+1156|0;c[i>>2]=h+1;if((h|0)<0)break;h=a+4|0;j=d+1160|0;k=d+2184|0;l=c[h>>2]|0;m=0;do{n=l+-1|0;if((l|0)==0|(n|0)==0)o=0;else{p=n;n=0;while(1){q=n+1|0;p=p>>>1;if(!p){o=q;break}else n=q}}n=Xa(b,o)|0;c[j+(m<<2)>>2]=n;p=c[h>>2]|0;q=p+-1|0;if((p|0)==0|(q|0)==0)r=0;else{p=q;q=0;while(1){s=q+1|0;p=p>>>1;if(!p){r=s;break}else q=s}}q=Xa(b,r)|0;c[k+(m<<2)>>2]=q;if((n|0)==(q|0)|(q|n|0)<0)break a;l=c[h>>2]|0;m=m+1|0;if(!((n|0)<(l|0)&(q|0)<(l|0)))break a}while((m|0)<(c[i>>2]|0))}if(!(Xa(b,2)|0)){i=c[d>>2]|0;if((i|0)>1){m=a+4|0;if((c[m>>2]|0)>0){l=d+4|0;h=0;while(1){k=Xa(b,4)|0;c[l+(h<<2)>>2]=k;j=c[d>>2]|0;h=h+1|0;if((k|0)<0|(k|0)>=(j|0))break a;if((h|0)>=(c[m>>2]|0)){t=j;u=20;break}}}}else{t=i;u=20}if((u|0)==20?(t|0)<=0:0){g=d;return g|0}m=d+1028|0;h=e+16|0;l=d+1092|0;j=e+20|0;k=0;while(1){Xa(b,8)|0;q=Xa(b,8)|0;c[m+(k<<2)>>2]=q;if((q|0)<0?1:(q|0)>=(c[h>>2]|0))break a;q=Xa(b,8)|0;c[l+(k<<2)>>2]=q;k=k+1|0;if((q|0)<0?1:(q|0)>=(c[j>>2]|0))break a;if((k|0)>=(c[d>>2]|0)){g=d;break}}return g|0}}}while(0);fd(d);g=0;return g|0}function Lb(a){a=a|0;if(a|0)fd(a);return}function Mb(a){a=a|0;var b=0,d=0,e=0,f=0,h=0,j=0,l=0,m=0,n=0,o=0,p=0,q=0.0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0.0,B=0.0,C=0,D=0,E=0,F=0,G=0.0,H=0.0,I=0,J=0,K=0,L=0,M=0.0,O=0.0,P=0,Q=0,R=0.0,S=0,T=0.0,U=0.0,V=0.0,W=0.0,X=0,Y=0,Z=0,_=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0;b=i;d=c[a+64>>2]|0;e=c[d+4>>2]|0;f=c[e+28>>2]|0;h=c[d+104>>2]|0;d=c[a+104>>2]|0;j=c[a+36>>2]|0;l=e+4|0;e=c[l>>2]<<2;m=i;i=i+((1*e|0)+15&-16)|0;n=eb(a,e)|0;e=eb(a,c[l>>2]<<2)|0;o=eb(a,c[l>>2]<<2)|0;p=d+4|0;q=+g[p>>2];r=c[l>>2]|0;s=i;i=i+((1*(r<<2)|0)+15&-16)|0;t=a+28|0;u=c[t>>2]|0;v=c[f+544+(u<<2)>>2]|0;w=(c[h+56>>2]|0)+((c[d+8>>2]|0)*52|0)+((u|0?2:0)*52|0)|0;x=a+40|0;c[x>>2]=u;a:do if((r|0)>0){y=(j|0)/2|0;z=y<<2;A=+N(+(4.0/+(j|0)));B=+((g[k>>2]=A,c[k>>2]|0)>>>0)*7.177114298428933e-07+-764.6162109375+.345;C=h+4|0;D=a+24|0;E=a+32|0;A=B+-764.6162109375;F=j+-1|0;G=B+-382.30810546875;if((F|0)>1){H=q;I=0}else{B=q;J=0;while(1){K=c[(c[a>>2]|0)+(J<<2)>>2]|0;c[e+(J<<2)>>2]=eb(a,z)|0;L=n+(J<<2)|0;c[L>>2]=eb(a,z)|0;Nb(K,C,f,c[D>>2]|0,c[t>>2]|0,c[E>>2]|0);Ob(c[c[h+12+(c[t>>2]<<2)>>2]>>2]|0,K,c[L>>2]|0);Qb(h+20+((c[t>>2]|0)*12|0)|0,K);M=A+ +((c[K>>2]&2147483647)>>>0)*7.177114298428933e-07+.345;g[K>>2]=M;O=M>0.0?0.0:M;g[s+(J<<2)>>2]=O;M=O>B?O:B;J=J+1|0;if((J|0)>=(c[l>>2]|0)){P=z;Q=y;R=M;break a}else B=M}}while(1){J=c[(c[a>>2]|0)+(I<<2)>>2]|0;c[e+(I<<2)>>2]=eb(a,z)|0;K=n+(I<<2)|0;c[K>>2]=eb(a,z)|0;Nb(J,C,f,c[D>>2]|0,c[t>>2]|0,c[E>>2]|0);Ob(c[c[h+12+(c[t>>2]<<2)>>2]>>2]|0,J,c[K>>2]|0);Qb(h+20+((c[t>>2]|0)*12|0)|0,J);B=A+ +((c[J>>2]&2147483647)>>>0)*7.177114298428933e-07+.345;g[J>>2]=B;K=s+(I<<2)|0;g[K>>2]=B;M=B;L=1;while(1){B=+g[J+(L<<2)>>2];S=L+1|0;O=+g[J+(S<<2)>>2];T=+N(+(O*O+B*B));B=G+ +((g[k>>2]=T,c[k>>2]|0)>>>0)*3.5885571492144663e-07+.345;g[J+(S>>1<<2)>>2]=B;if(B>M){g[K>>2]=B;U=B}else U=M;L=L+2|0;if((L|0)>=(F|0)){V=U;break}else M=U}if(V>0.0){g[K>>2]=0.0;W=0.0}else W=V;M=W>H?W:H;I=I+1|0;if((I|0)>=(c[l>>2]|0)){P=z;Q=y;R=M;break}else H=M}}else{y=(j|0)/2|0;P=y<<2;Q=y;R=q}while(0);I=eb(a,P)|0;r=eb(a,P)|0;P=c[l>>2]|0;b:do if((P|0)>0){y=(j|0)>1;z=h+48|0;F=0;while(1){E=c[v+4+(F<<2)>>2]|0;D=c[n+(F<<2)>>2]|0;C=c[(c[a>>2]|0)+(F<<2)>>2]|0;L=C+(Q<<2)|0;c[x>>2]=u;J=eb(a,60)|0;S=o+(F<<2)|0;c[S>>2]=J;X=J;J=X+60|0;do{c[X>>2]=0;X=X+4|0}while((X|0)<(J|0));if(y){X=0;do{g[L+(X<<2)>>2]=+((c[D+(X<<2)>>2]&2147483647)>>>0)*7.177114298428933e-07+-764.6162109375+.345;X=X+1|0}while((X|0)<(Q|0))}Ub(w,L,I);Wb(w,C,r,R,+g[s+(F<<2)>>2]);Yb(w,I,r,1,C,D,L);X=v+1028+(E<<2)|0;J=c[X>>2]|0;if((c[f+800+(J<<2)>>2]|0)!=1){Y=-1;break}K=Zb(a,c[(c[z>>2]|0)+(J<<2)>>2]|0,L,C)|0;c[(c[S>>2]|0)+28>>2]=K;if($b(a)|0?c[(c[S>>2]|0)+28>>2]|0:0){Yb(w,I,r,2,C,D,L);K=Zb(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,L,C)|0;c[(c[S>>2]|0)+56>>2]=K;Yb(w,I,r,0,C,D,L);K=Zb(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,L,C)|0;c[c[S>>2]>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K>>2]|0,c[K+28>>2]|0,9362)|0;c[(c[S>>2]|0)+4>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J>>2]|0,c[J+28>>2]|0,18724)|0;c[(c[S>>2]|0)+8>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K>>2]|0,c[K+28>>2]|0,28086)|0;c[(c[S>>2]|0)+12>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J>>2]|0,c[J+28>>2]|0,37449)|0;c[(c[S>>2]|0)+16>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K>>2]|0,c[K+28>>2]|0,46811)|0;c[(c[S>>2]|0)+20>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J>>2]|0,c[J+28>>2]|0,56173)|0;c[(c[S>>2]|0)+24>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K+28>>2]|0,c[K+56>>2]|0,9362)|0;c[(c[S>>2]|0)+32>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J+28>>2]|0,c[J+56>>2]|0,18724)|0;c[(c[S>>2]|0)+36>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K+28>>2]|0,c[K+56>>2]|0,28086)|0;c[(c[S>>2]|0)+40>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J+28>>2]|0,c[J+56>>2]|0,37449)|0;c[(c[S>>2]|0)+44>>2]=K;K=c[S>>2]|0;J=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[K+28>>2]|0,c[K+56>>2]|0,46811)|0;c[(c[S>>2]|0)+48>>2]=J;J=c[S>>2]|0;K=ac(a,c[(c[z>>2]|0)+(c[X>>2]<<2)>>2]|0,c[J+28>>2]|0,c[J+56>>2]|0,56173)|0;c[(c[S>>2]|0)+52>>2]=K}F=F+1|0;K=c[l>>2]|0;if((F|0)>=(K|0)){Z=z;_=K;break b}}i=b;return Y|0}else{Z=h+48|0;_=P}while(0);g[p>>2]=R;p=_<<2;_=i;i=i+((1*p|0)+15&-16)|0;P=i;i=i+((1*p|0)+15&-16)|0;p=($b(a)|0)!=0;r=h+44|0;I=a+24|0;s=a+32|0;Q=f+2868|0;x=h+52|0;h=p?0:7;while(1){p=c[d+12+(h<<2)>>2]|0;Sa(p,0,1);Sa(p,u,c[r>>2]|0);if(c[t>>2]|0){Sa(p,c[I>>2]|0,1);Sa(p,c[s>>2]|0,1)}j=c[l>>2]|0;if((j|0)>0){z=0;do{c[m+(z<<2)>>2]=bc(p,a,c[(c[Z>>2]|0)+(c[v+1028+(c[v+4+(z<<2)>>2]<<2)>>2]<<2)>>2]|0,c[(c[o+(z<<2)>>2]|0)+(h<<2)>>2]|0,c[e+(z<<2)>>2]|0)|0;z=z+1|0;F=c[l>>2]|0}while((z|0)<(F|0));$=F}else $=j;cc(h,Q,w,v,n,e,m,c[f+3240+((c[t>>2]|0)*60|0)+(h<<2)>>2]|0,$);if((c[v>>2]|0)>0){z=0;do{F=c[v+1092+(z<<2)>>2]|0;y=c[l>>2]|0;if((y|0)>0){K=y;y=0;J=0;while(1){if((c[v+4+(J<<2)>>2]|0)==(z|0)){c[P+(y<<2)>>2]=(c[m+(J<<2)>>2]|0)!=0&1;c[_+(y<<2)>>2]=c[e+(J<<2)>>2];aa=c[l>>2]|0;ba=y+1|0}else{aa=K;ba=y}J=J+1|0;if((J|0)>=(aa|0)){ca=ba;break}else{K=aa;y=ba}}}else ca=0;y=f+1312+(F<<2)|0;K=Ha[c[(c[34152+(c[y>>2]<<2)>>2]|0)+20>>2]&7](a,c[(c[x>>2]|0)+(F<<2)>>2]|0,_,P,ca)|0;J=c[l>>2]|0;if((J|0)>0){S=0;C=0;while(1){if((c[v+4+(C<<2)>>2]|0)==(z|0)){c[_+(S<<2)>>2]=c[e+(C<<2)>>2];da=S+1|0}else da=S;C=C+1|0;if((C|0)>=(J|0)){ea=da;break}else S=da}}else ea=0;Fa[c[(c[34152+(c[y>>2]<<2)>>2]|0)+24>>2]&3](p,a,c[(c[x>>2]|0)+(F<<2)>>2]|0,_,P,ea,K,z)|0;z=z+1|0}while((z|0)<(c[v>>2]|0))}z=($b(a)|0)!=0;if((h|0)<((z?14:7)|0))h=h+1|0;else{Y=0;break}}i=b;return Y|0}function Nb(a,b,d,e,f,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;i=(f|0)!=0;j=i?e:0;e=i?h:0;h=c[456+(c[b+(j<<2)>>2]<<2)>>2]|0;i=c[456+(c[b+(e<<2)>>2]<<2)>>2]|0;b=c[d+(f<<2)>>2]|0;f=c[d+(j<<2)>>2]|0;j=c[d+(e<<2)>>2]|0;e=(b|0)/4|0;d=(f|0)/4|0;k=e-d|0;l=(f|0)/2|0;f=((b|0)/2|0)+e+((j|0)/-4|0)|0;m=(j|0)/2|0;n=f+m|0;if((k|0)>0){md(a|0,0,e-d<<2|0)|0;o=k}else o=0;if((o|0)<(k+l|0)){k=e+l-o-d|0;d=o;o=0;while(1){l=a+(d<<2)|0;g[l>>2]=+g[l>>2]*+g[h+(o<<2)>>2];o=o+1|0;if((o|0)==(k|0))break;else d=d+1|0}}if((j|0)>1){j=f;d=m;while(1){d=d+-1|0;m=a+(j<<2)|0;g[m>>2]=+g[m>>2]*+g[i+(d<<2)>>2];m=j+1|0;if((m|0)>=(n|0)){p=m;break}else j=m}}else p=f;if((b|0)<=(p|0))return;md(a+(p<<2)|0,0,b-p<<2|0)|0;return}function Ob(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0.0,B=0.0,C=0,D=0,E=0,F=0,G=0,H=0,I=0.0,J=0.0,K=0.0,L=0.0,M=0.0,N=0.0,O=0.0,P=0.0;e=i;f=c[a>>2]|0;h=f>>1;j=f>>2;k=f>>3;l=i;i=i+((1*(f<<2)|0)+15&-16)|0;m=l+(h<<2)|0;n=b+(h<<2)+(j<<2)|0;o=a+8|0;p=c[o>>2]|0;q=p+(h<<2)|0;if((k|0)>0){r=(k+-1|0)>>>1;s=r<<1;t=h+-2-s|0;u=j+h+-4-(r<<2)|0;r=q;v=0;w=n;x=n+4|0;while(1){y=w;w=w+-16|0;z=r;r=r+-8|0;A=+g[x>>2]+ +g[y+-8>>2];B=+g[x+8>>2]+ +g[w>>2];y=z+-4|0;g[m+(v<<2)>>2]=+g[r>>2]*A+B*+g[y>>2];g[m+((v|1)<<2)>>2]=+g[r>>2]*B-+g[y>>2]*A;v=v+2|0;if((v|0)>=(k|0))break;else x=x+16|0}C=p+(t<<2)|0;D=s+2|0;E=b+(u<<2)|0}else{C=q;D=0;E=n}n=b+4|0;q=h-k|0;if((D|0)<(q|0)){u=(h+-1-D-k|0)>>>1;k=u<<1;s=D+k|0;t=(u<<2)+5|0;u=-2-k|0;k=C;x=D;v=E;E=n;while(1){r=k;k=k+-8|0;A=+g[v+-8>>2]-+g[E>>2];v=v+-16|0;B=+g[v>>2]-+g[E+8>>2];w=r+-4|0;g[m+(x<<2)>>2]=+g[k>>2]*A+B*+g[w>>2];g[m+((x|1)<<2)>>2]=+g[k>>2]*B-+g[w>>2]*A;x=x+2|0;if((x|0)>=(q|0))break;else E=E+16|0}F=C+(u<<2)|0;G=s+2|0;H=b+(t<<2)|0}else{F=C;G=D;H=n}if((G|0)<(h|0)){n=F;F=G;G=b+(f<<2)|0;f=H;while(1){H=n;n=n+-8|0;A=-+g[G+-8>>2]-+g[f>>2];G=G+-16|0;B=-+g[G>>2]-+g[f+8>>2];b=H+-4|0;g[m+(F<<2)>>2]=+g[n>>2]*A+B*+g[b>>2];g[m+((F|1)<<2)>>2]=+g[n>>2]*B-+g[b>>2]*A;F=F+2|0;if((F|0)>=(h|0))break;else f=f+16|0}}Pb(c[a+4>>2]|0,p,m,h);m=c[a>>2]|0;p=c[o>>2]|0;o=l+(m>>1<<2)|0;f=p+(m<<2)|0;m=c[a+12>>2]|0;F=l;n=o;while(1){G=o+(c[m>>2]<<2)|0;b=o+(c[m+4>>2]<<2)|0;A=+g[G+4>>2];B=+g[b+4>>2];I=A-B;J=+g[G>>2];K=+g[b>>2];L=K+J;M=+g[f>>2];N=+g[f+4>>2];O=N*I+L*M;P=N*L-M*I;b=n;n=n+-16|0;I=(B+A)*.5;A=(J-K)*.5;g[F>>2]=O+I;g[b+-8>>2]=I-O;g[F+4>>2]=P+A;g[b+-4>>2]=P-A;G=o+(c[m+8>>2]<<2)|0;H=o+(c[m+12>>2]<<2)|0;A=+g[G+4>>2];P=+g[H+4>>2];O=A-P;I=+g[G>>2];K=+g[H>>2];J=K+I;B=+g[f+8>>2];M=+g[f+12>>2];L=M*O+J*B;N=M*J-B*O;O=(P+A)*.5;A=(I-K)*.5;g[F+8>>2]=L+O;g[n>>2]=O-L;g[F+12>>2]=N+A;g[b+-12>>2]=N-A;F=F+16|0;if(F>>>0>=n>>>0)break;else{f=f+16|0;m=m+16|0}}if((j|0)<=0){i=e;return}m=a+16|0;a=p+(h<<2)|0;p=0;f=l;l=d+(h<<2)|0;while(1){l=l+-4|0;h=f+4|0;n=a+4|0;g[d+(p<<2)>>2]=(+g[n>>2]*+g[h>>2]+ +g[a>>2]*+g[f>>2])*+g[m>>2];g[l>>2]=(+g[n>>2]*+g[f>>2]-+g[a>>2]*+g[h>>2])*+g[m>>2];p=p+1|0;if((p|0)==(j|0))break;else{a=a+8|0;f=f+8|0}}i=e;return}function Pb(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,h=0,i=0,j=0,k=0.0,l=0,m=0.0,n=0.0,o=0,p=0.0,q=0,r=0.0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0.0,C=0,D=0,E=0,F=0.0,G=0.0,H=0,I=0,J=0,K=0,L=0.0,M=0.0,N=0,O=0,P=0,Q=0,R=0.0,S=0.0,T=0,U=0,V=0,W=0.0,X=0.0,Y=0.0,Z=0.0,$=0.0,aa=0.0,ba=0.0,ca=0.0,da=0.0;e=a+-6|0;if((a|0)>6){a=b;f=c+(d<<2)|0;h=c+(d>>1<<2)+-32|0;while(1){i=f;f=f+-32|0;j=i+-8|0;k=+g[j>>2];l=h+24|0;m=+g[l>>2];n=k-m;o=i+-4|0;p=+g[o>>2];q=h+28|0;r=p-+g[q>>2];g[j>>2]=m+k;g[o>>2]=+g[q>>2]+p;o=a+4|0;g[l>>2]=+g[a>>2]*n+ +g[o>>2]*r;g[q>>2]=+g[a>>2]*r-+g[o>>2]*n;o=i+-16|0;n=+g[o>>2];q=h+16|0;r=+g[q>>2];p=n-r;l=i+-12|0;k=+g[l>>2];j=h+20|0;m=k-+g[j>>2];g[o>>2]=r+n;g[l>>2]=+g[j>>2]+k;l=a+20|0;o=a+16|0;g[q>>2]=+g[o>>2]*p+ +g[l>>2]*m;g[j>>2]=+g[o>>2]*m-+g[l>>2]*p;l=i+-24|0;p=+g[l>>2];o=h+8|0;m=+g[o>>2];k=p-m;j=i+-20|0;n=+g[j>>2];q=h+12|0;r=n-+g[q>>2];g[l>>2]=m+p;g[j>>2]=+g[q>>2]+n;j=a+36|0;l=a+32|0;g[o>>2]=+g[l>>2]*k+ +g[j>>2]*r;g[q>>2]=+g[l>>2]*r-+g[j>>2]*k;k=+g[f>>2];r=+g[h>>2];n=k-r;j=i+-28|0;p=+g[j>>2];i=h+4|0;m=p-+g[i>>2];g[f>>2]=r+k;g[j>>2]=+g[i>>2]+p;j=a+52|0;l=a+48|0;g[h>>2]=+g[l>>2]*n+ +g[j>>2]*m;g[i>>2]=+g[l>>2]*m-+g[j>>2]*n;h=h+-32|0;if(h>>>0<c>>>0)break;else a=a+64|0}}if((e|0)>1){a=1;do{h=1<<a;if((a|0)!=31){f=d>>a;j=4<<a;l=f>>1;i=0;do{q=c+((_(i,f)|0)<<2)|0;o=b;s=q+(f<<2)|0;t=q+(l<<2)+-32|0;while(1){u=s;s=s+-32|0;v=u+-8|0;n=+g[v>>2];w=t+24|0;m=+g[w>>2];p=n-m;x=u+-4|0;k=+g[x>>2];y=t+28|0;r=k-+g[y>>2];g[v>>2]=m+n;g[x>>2]=+g[y>>2]+k;x=o+4|0;g[w>>2]=+g[o>>2]*p+ +g[x>>2]*r;g[y>>2]=+g[o>>2]*r-+g[x>>2]*p;x=o+(j<<2)|0;y=u+-16|0;p=+g[y>>2];w=t+16|0;r=+g[w>>2];k=p-r;v=u+-12|0;n=+g[v>>2];z=t+20|0;m=n-+g[z>>2];g[y>>2]=r+p;g[v>>2]=+g[z>>2]+n;v=x+4|0;g[w>>2]=+g[x>>2]*k+ +g[v>>2]*m;g[z>>2]=+g[x>>2]*m-+g[v>>2]*k;v=x+(j<<2)|0;x=u+-24|0;k=+g[x>>2];z=t+8|0;m=+g[z>>2];n=k-m;w=u+-20|0;p=+g[w>>2];y=t+12|0;r=p-+g[y>>2];g[x>>2]=m+k;g[w>>2]=+g[y>>2]+p;w=v+4|0;g[z>>2]=+g[v>>2]*n+ +g[w>>2]*r;g[y>>2]=+g[v>>2]*r-+g[w>>2]*n;w=v+(j<<2)|0;n=+g[s>>2];r=+g[t>>2];p=n-r;v=u+-28|0;k=+g[v>>2];u=t+4|0;m=k-+g[u>>2];g[s>>2]=r+n;g[v>>2]=+g[u>>2]+k;v=w+4|0;g[t>>2]=+g[w>>2]*p+ +g[v>>2]*m;g[u>>2]=+g[w>>2]*m-+g[v>>2]*p;t=t+-32|0;if(t>>>0<q>>>0)break;else o=w+(j<<2)|0}i=i+1|0}while((i|0)<(h|0))}a=a+1|0}while((a|0)!=(e|0))}if((d|0)>0)A=0;else return;do{e=c+(A<<2)|0;a=e+120|0;p=+g[a>>2];b=e+56|0;m=+g[b>>2];h=e+124|0;k=+g[h>>2];i=e+60|0;n=+g[i>>2];g[a>>2]=m+p;g[h>>2]=n+k;g[b>>2]=p-m;g[i>>2]=k-n;j=e+112|0;n=+g[j>>2];l=e+48|0;k=+g[l>>2];m=n-k;f=e+116|0;p=+g[f>>2];o=e+52|0;r=+g[o>>2];B=p-r;g[j>>2]=k+n;g[f>>2]=r+p;g[l>>2]=m*.9238795042037964-B*.3826834261417389;g[o>>2]=B*.9238795042037964+m*.3826834261417389;q=e+104|0;m=+g[q>>2];t=e+40|0;B=+g[t>>2];p=m-B;s=e+108|0;r=+g[s>>2];w=e+44|0;n=+g[w>>2];k=r-n;g[q>>2]=B+m;g[s>>2]=n+r;g[t>>2]=(p-k)*.7071067690849304;g[w>>2]=(k+p)*.7071067690849304;v=e+96|0;p=+g[v>>2];u=e+32|0;k=+g[u>>2];r=p-k;y=e+100|0;n=+g[y>>2];z=e+36|0;m=+g[z>>2];B=n-m;g[v>>2]=k+p;g[y>>2]=m+n;n=r*.3826834261417389-B*.9238795042037964;m=B*.3826834261417389+r*.9238795042037964;x=e+88|0;r=+g[x>>2];C=e+24|0;B=+g[C>>2];p=r-B;D=e+28|0;k=+g[D>>2];E=e+92|0;F=+g[E>>2];G=k-F;g[x>>2]=B+r;g[E>>2]=F+k;g[D>>2]=p;H=e+16|0;k=+g[H>>2];I=e+80|0;F=+g[I>>2];r=k-F;J=e+20|0;B=+g[J>>2];K=e+84|0;L=+g[K>>2];M=B-L;g[I>>2]=F+k;g[K>>2]=L+B;B=M*.9238795042037964+r*.3826834261417389;L=M*.3826834261417389-r*.9238795042037964;N=e+8|0;r=+g[N>>2];O=e+72|0;M=+g[O>>2];k=r-M;P=e+12|0;F=+g[P>>2];Q=e+76|0;R=+g[Q>>2];S=F-R;g[O>>2]=M+r;g[Q>>2]=R+F;F=(S+k)*.7071067690849304;R=(S-k)*.7071067690849304;k=+g[e>>2];T=e+64|0;S=+g[T>>2];r=k-S;U=e+4|0;M=+g[U>>2];V=e+68|0;W=+g[V>>2];X=M-W;Y=S+k;g[T>>2]=Y;k=W+M;g[V>>2]=k;M=X*.3826834261417389+r*.9238795042037964;W=X*.9238795042037964-r*.3826834261417389;r=W-m;X=M-n;S=M+n;n=W+m;m=X+r;W=r-X;X=+g[w>>2];r=R-X;M=+g[t>>2];Z=M-F;$=M+F;F=X+R;R=+g[l>>2];X=R-B;M=+g[o>>2];aa=M-L;ba=R+B;B=M+L;L=X-aa;M=aa+X;X=+g[b>>2];aa=X-G;R=+g[i>>2];ca=R-p;da=G+X;X=p+R;R=aa+r;p=aa-r;r=(L+m)*.7071067690849304;aa=(L-m)*.7071067690849304;g[C>>2]=r+R;g[H>>2]=R-r;r=(M-W)*.7071067690849304;R=ca-Z;g[e>>2]=r+p;g[N>>2]=p-r;r=(M+W)*.7071067690849304;W=ca+Z;g[P>>2]=R+aa;g[U>>2]=R-aa;g[D>>2]=W+r;g[J>>2]=W-r;r=da+$;W=da-$;$=ba+S;da=ba-S;g[b>>2]=r+$;g[l>>2]=r-$;$=B-n;r=X-F;g[u>>2]=W+$;g[t>>2]=W-$;$=B+n;n=X+F;g[w>>2]=r+da;g[z>>2]=r-da;g[i>>2]=n+$;g[o>>2]=n-$;$=+g[y>>2];n=k-$;da=+g[v>>2];r=Y-da;F=da+Y;Y=$+k;k=r+n;$=n-r;r=+g[Q>>2];n=+g[s>>2];da=r-n;X=+g[q>>2];B=+g[O>>2];W=X-B;S=B+X;X=n+r;r=+g[j>>2];n=+g[I>>2];B=r-n;ba=+g[f>>2];aa=+g[K>>2];R=ba-aa;Z=n+r;r=aa+ba;ba=B-R;aa=R+B;B=+g[a>>2];R=+g[x>>2];n=B-R;ca=+g[h>>2];M=+g[E>>2];p=ca-M;m=R+B;B=M+ca;ca=n+da;M=n-da;da=(ba+k)*.7071067690849304;n=(ba-k)*.7071067690849304;g[x>>2]=da+ca;g[I>>2]=ca-da;da=(aa-$)*.7071067690849304;ca=p-W;g[T>>2]=da+M;g[O>>2]=M-da;da=(aa+$)*.7071067690849304;$=p+W;g[Q>>2]=ca+n;g[V>>2]=ca-n;g[E>>2]=$+da;g[K>>2]=$-da;da=m+S;$=m-S;S=Z+F;m=Z-F;g[a>>2]=da+S;g[j>>2]=da-S;S=r-Y;da=B-X;g[v>>2]=$+S;g[q>>2]=$-S;S=r+Y;Y=B+X;g[s>>2]=da+m;g[y>>2]=da-m;g[h>>2]=Y+S;g[f>>2]=Y-S;A=A+32|0}while((A|0)<(d|0));return}function Qb(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;d=c[a>>2]|0;if((d|0)==1)return;e=c[a+4>>2]|0;f=e+(d<<2)|0;g=c[a+8>>2]|0;a=c[g+4>>2]|0;if((a|0)<=0)return;h=a+1|0;i=d;j=0;k=d;l=1;while(1){m=c[g+(h-j<<2)>>2]|0;n=(d|0)/(k|0)|0;k=(k|0)/(m|0)|0;o=_(n,k)|0;i=i-(_(n,m+-1|0)|0)|0;p=1-l|0;a:do switch(m|0){case 4:{q=i+n|0;r=f+(i<<2)+-4|0;s=f+(q<<2)+-4|0;t=f+(q+n<<2)+-4|0;if(!p){Rb(n,k,b,e,r,s,t);u=0;break a}else{Rb(n,k,e,b,r,s,t);u=p;break a}break}case 2:{t=f+(i<<2)+-4|0;if(!p){Sb(n,k,b,e,t);u=0;break a}else{Sb(n,k,e,b,t);u=p;break a}break}default:{t=f+(i<<2)+-4|0;if(!(((n|0)==1?l:p)|0)){Tb(n,m,k,o,b,b,b,e,e,t);u=1;break a}else{Tb(n,m,k,o,e,e,e,b,b,t);u=0;break a}}}while(0);j=j+1|0;if((j|0)==(a|0)){v=u;break}else l=u}if((d|0)>0&(v|0)!=1)w=0;else return;do{c[b+(w<<2)>>2]=c[e+(w<<2)>>2];w=w+1|0}while((w|0)!=(d|0));return}function Rb(a,b,c,d,e,f,h){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;h=h|0;var i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0.0,v=0,w=0,x=0.0,y=0,z=0,A=0.0,B=0.0,C=0.0,D=0.0,E=0,F=0.0,G=0.0,H=0.0,I=0.0;i=_(b,a)|0;j=i<<1;k=(b|0)>0;if(k){l=(a<<2)+-1|0;m=a<<1;n=0;o=i;p=i*3|0;q=0;r=j;while(1){s=c+(o<<2)|0;t=c+(p<<2)|0;u=+g[t>>2]+ +g[s>>2];v=c+(q<<2)|0;w=c+(r<<2)|0;x=+g[w>>2]+ +g[v>>2];y=q<<2;g[d+(y<<2)>>2]=x+u;g[d+(l+y<<2)>>2]=x-u;z=y+m|0;g[d+(z+-1<<2)>>2]=+g[v>>2]-+g[w>>2];g[d+(z<<2)>>2]=+g[t>>2]-+g[s>>2];n=n+1|0;if((n|0)==(b|0))break;else{o=o+a|0;p=p+a|0;q=q+a|0;r=r+a|0}}}if((a|0)<2)return;if((a|0)!=2){if(k){r=a<<1;q=0;p=0;while(1){o=p<<2;n=2;m=p;l=o;s=o+r|0;do{o=m;m=m+2|0;t=l;l=l+2|0;z=s;s=s+-2|0;w=m+i|0;v=n+-2|0;u=+g[e+(v<<2)>>2];x=+g[c+(w+-1<<2)>>2];y=n+-1|0;A=+g[e+(y<<2)>>2];B=+g[c+(w<<2)>>2];C=B*A+x*u;D=B*u-A*x;E=w+i|0;x=+g[f+(v<<2)>>2];A=+g[c+(E+-1<<2)>>2];u=+g[f+(y<<2)>>2];B=+g[c+(E<<2)>>2];F=B*u+A*x;G=B*x-u*A;w=E+i|0;A=+g[h+(v<<2)>>2];u=+g[c+(w+-1<<2)>>2];x=+g[h+(y<<2)>>2];B=+g[c+(w<<2)>>2];H=B*x+u*A;I=B*A-x*u;u=H+C;x=H-C;C=I+D;H=D-I;I=+g[c+(m<<2)>>2];D=I+G;A=I-G;G=+g[c+(o+1<<2)>>2];I=G+F;B=G-F;g[d+((t|1)<<2)>>2]=u+I;g[d+(l<<2)>>2]=C+D;g[d+(z+-3<<2)>>2]=B-H;g[d+(s<<2)>>2]=x-A;z=l+r|0;g[d+(z+-1<<2)>>2]=H+B;g[d+(z<<2)>>2]=x+A;z=s+r|0;g[d+(z+-1<<2)>>2]=I-u;g[d+(z<<2)>>2]=C-D;n=n+2|0}while((n|0)<(a|0));q=q+1|0;if((q|0)==(b|0))break;else p=p+a|0}}if(a&1|0)return}p=a+-1+i|0;q=a<<2;r=a<<1;if(!k)return;k=0;h=p;f=p+j|0;j=a;p=a;while(1){D=+g[c+(h<<2)>>2];C=+g[c+(f<<2)>>2];u=(C+D)*-.7071067690849304;I=(D-C)*.7071067690849304;e=c+(p+-1<<2)|0;g[d+(j+-1<<2)>>2]=I+ +g[e>>2];n=j+r|0;g[d+(n+-1<<2)>>2]=+g[e>>2]-I;e=c+(h+i<<2)|0;g[d+(j<<2)>>2]=u-+g[e>>2];g[d+(n<<2)>>2]=+g[e>>2]+u;k=k+1|0;if((k|0)==(b|0))break;else{h=h+a|0;f=f+a|0;j=j+q|0;p=p+a|0}}return}function Sb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0.0,x=0.0,y=0.0,z=0.0,A=0.0,B=0.0;h=_(b,a)|0;i=a<<1;j=(b|0)>0;if(j){k=i+-1|0;l=0;m=0;n=h;while(1){o=d+(m<<2)|0;p=d+(n<<2)|0;q=m<<1;g[e+(q<<2)>>2]=+g[p>>2]+ +g[o>>2];g[e+(k+q<<2)>>2]=+g[o>>2]-+g[p>>2];l=l+1|0;if((l|0)==(b|0))break;else{m=m+a|0;n=n+a|0}}}if((a|0)<2)return;if((a|0)!=2){if(j){n=0;m=0;l=h;while(1){k=m<<1;p=2;o=l;q=k+i|0;r=m;s=k;do{k=o;o=o+2|0;t=q;q=q+-2|0;u=r;r=r+2|0;v=s;s=s+2|0;w=+g[f+(p+-2<<2)>>2];x=+g[d+(k+1<<2)>>2];y=+g[f+(p+-1<<2)>>2];z=+g[d+(o<<2)>>2];A=z*y+x*w;B=z*w-y*x;k=d+(r<<2)|0;g[e+(s<<2)>>2]=B+ +g[k>>2];g[e+(q<<2)>>2]=B-+g[k>>2];k=d+(u+1<<2)|0;g[e+((v|1)<<2)>>2]=+g[k>>2]+A;g[e+(t+-3<<2)>>2]=+g[k>>2]-A;p=p+2|0}while((p|0)<(a|0));n=n+1|0;if((n|0)==(b|0))break;else{m=m+a|0;l=l+a|0}}}if(((a|0)%2|0|0)==1)return}l=a+-1|0;if(!j)return;j=0;m=a;n=h+l|0;h=l;while(1){g[e+(m<<2)>>2]=-+g[d+(n<<2)>>2];c[e+(m+-1<<2)>>2]=c[d+(h<<2)>>2];j=j+1|0;if((j|0)==(b|0))break;else{m=m+i|0;n=n+a|0;h=h+a|0}}return}function Tb(a,b,d,e,f,h,i,j,k,l){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;i=i|0;j=j|0;k=k|0;l=l|0;var m=0.0,n=0.0,o=0.0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0.0,N=0.0,O=0.0,P=0.0;m=6.2831854820251465/+(b|0);n=+Q(+m);o=+R(+m);p=b+1>>1;q=a+-1>>1;r=_(d,a)|0;s=_(b,a)|0;t=(a|0)==1;do if(!t){if((e|0)>0){u=0;do{c[k+(u<<2)>>2]=c[i+(u<<2)>>2];u=u+1|0}while((u|0)!=(e|0))}u=(b|0)>1;if(u&(d|0)>0){v=1;w=0;do{w=w+r|0;x=0;y=w;while(1){c[j+(y<<2)>>2]=c[h+(y<<2)>>2];x=x+1|0;if((x|0)==(d|0))break;else y=y+a|0}v=v+1|0}while((v|0)!=(b|0))}v=0-a|0;if((q|0)>(d|0)){if(u){w=(d|0)>0;y=(a|0)>2;x=v;z=1;A=0;do{A=A+r|0;x=x+a|0;if(w?(B=x+-1|0,y):0){C=0;D=A-a|0;do{D=D+a|0;E=2;F=B;G=D;do{H=F;F=F+2|0;I=l+(H+1<<2)|0;H=G+1|0;G=G+2|0;J=h+(H<<2)|0;K=l+(F<<2)|0;L=h+(G<<2)|0;g[j+(H<<2)>>2]=+g[L>>2]*+g[K>>2]+ +g[J>>2]*+g[I>>2];g[j+(G<<2)>>2]=+g[L>>2]*+g[I>>2]-+g[J>>2]*+g[K>>2];E=E+2|0}while((E|0)<(a|0));C=C+1|0}while((C|0)!=(d|0))}z=z+1|0}while((z|0)!=(b|0))}}else if(u){z=(a|0)<3|(d|0)<1;A=v;y=1;x=0;do{A=A+a|0;x=x+r|0;if(!z){w=2;C=A+-1|0;D=x;do{B=C;C=C+2|0;D=D+2|0;E=l+(B+1<<2)|0;B=l+(C<<2)|0;G=0;F=D;while(1){K=F+-1|0;J=h+(K<<2)|0;I=h+(F<<2)|0;g[j+(K<<2)>>2]=+g[I>>2]*+g[B>>2]+ +g[J>>2]*+g[E>>2];g[j+(F<<2)>>2]=+g[I>>2]*+g[E>>2]-+g[J>>2]*+g[B>>2];G=G+1|0;if((G|0)==(d|0))break;else F=F+a|0}w=w+2|0}while((w|0)<(a|0))}y=y+1|0}while((y|0)!=(b|0))}y=_(r,b)|0;x=(p|0)>1;if((q|0)<(d|0)){if(!x)break;A=(a|0)<3|(d|0)<1;z=1;v=0;u=y;do{v=v+r|0;u=u-r|0;if(!A){w=2;D=v;C=u;do{D=D+2|0;C=C+2|0;F=0;G=D-a|0;B=C-a|0;do{G=G+a|0;B=B+a|0;E=G+-1|0;J=j+(E<<2)|0;I=B+-1|0;K=j+(I<<2)|0;g[h+(E<<2)>>2]=+g[K>>2]+ +g[J>>2];E=j+(G<<2)|0;L=j+(B<<2)|0;g[h+(I<<2)>>2]=+g[E>>2]-+g[L>>2];g[h+(G<<2)>>2]=+g[L>>2]+ +g[E>>2];g[h+(B<<2)>>2]=+g[K>>2]-+g[J>>2];F=F+1|0}while((F|0)!=(d|0));w=w+2|0}while((w|0)<(a|0))}z=z+1|0}while((z|0)!=(p|0))}else{if(!x)break;z=(d|0)<1|(a|0)<3;u=1;v=0;A=y;do{v=v+r|0;A=A-r|0;if(!z){w=0;C=v;D=A;while(1){F=2;B=C;G=D;do{J=B;B=B+2|0;K=J+1|0;J=j+(K<<2)|0;E=G+1|0;G=G+2|0;L=j+(E<<2)|0;g[h+(K<<2)>>2]=+g[L>>2]+ +g[J>>2];K=j+(B<<2)|0;I=j+(G<<2)|0;g[h+(E<<2)>>2]=+g[K>>2]-+g[I>>2];g[h+(B<<2)>>2]=+g[I>>2]+ +g[K>>2];g[h+(G<<2)>>2]=+g[L>>2]-+g[J>>2];F=F+2|0}while((F|0)<(a|0));w=w+1|0;if((w|0)==(d|0))break;else{C=C+a|0;D=D+a|0}}}u=u+1|0}while((u|0)!=(p|0))}}while(0);l=(e|0)>0;if(l){u=0;do{c[i+(u<<2)>>2]=c[k+(u<<2)>>2];u=u+1|0}while((u|0)!=(e|0))}u=_(e,b)|0;A=(p|0)>1;do if(A){if((d|0)>0){v=1;z=0;y=u;do{z=z+r|0;y=y-r|0;x=0;D=z-a|0;C=y-a|0;do{D=D+a|0;C=C+a|0;w=j+(D<<2)|0;F=j+(C<<2)|0;g[h+(D<<2)>>2]=+g[F>>2]+ +g[w>>2];g[h+(C<<2)>>2]=+g[F>>2]-+g[w>>2];x=x+1|0}while((x|0)!=(d|0));v=v+1|0}while((v|0)!=(p|0));if(!A)break}v=_(b+-1|0,e)|0;y=(p|0)<3|l^1;m=0.0;M=1.0;z=1;x=0;C=u;do{x=x+e|0;C=C-e|0;N=M;M=M*n-m*o;m=N*o+m*n;if(l){D=0;w=x;F=C;G=v;B=e;while(1){g[k+(w<<2)>>2]=+g[i+(B<<2)>>2]*M+ +g[i+(D<<2)>>2];g[k+(F<<2)>>2]=+g[i+(G<<2)>>2]*m;D=D+1|0;if((D|0)==(e|0))break;else{w=w+1|0;F=F+1|0;G=G+1|0;B=B+1|0}}}if(!y){N=m;O=M;B=2;G=e;F=v;do{G=G+e|0;F=F-e|0;P=O;O=O*M-N*m;N=P*m+N*M;w=0;D=x;J=C;L=G;K=F;while(1){I=k+(D<<2)|0;g[I>>2]=+g[I>>2]+ +g[i+(L<<2)>>2]*O;I=k+(J<<2)|0;g[I>>2]=+g[I>>2]+ +g[i+(K<<2)>>2]*N;w=w+1|0;if((w|0)==(e|0))break;else{D=D+1|0;J=J+1|0;L=L+1|0;K=K+1|0}}B=B+1|0}while((B|0)!=(p|0))}z=z+1|0}while((z|0)!=(p|0));if(A&l){z=1;C=0;do{C=C+e|0;x=0;v=C;while(1){y=k+(x<<2)|0;g[y>>2]=+g[y>>2]+ +g[i+(v<<2)>>2];x=x+1|0;if((x|0)==(e|0))break;else v=v+1|0}z=z+1|0}while((z|0)!=(p|0))}}while(0);if((a|0)<(d|0)){if((a|0)>0&(d|0)>0){e=0;do{i=0;k=e;l=e;while(1){c[f+(l<<2)>>2]=c[j+(k<<2)>>2];i=i+1|0;if((i|0)==(d|0))break;else{k=k+a|0;l=l+s|0}}e=e+1|0}while((e|0)!=(a|0))}}else if((d|0)>0&(a|0)>0){e=0;l=0;k=0;while(1){i=0;u=l;h=k;while(1){c[f+(h<<2)>>2]=c[j+(u<<2)>>2];i=i+1|0;if((i|0)==(a|0))break;else{u=u+1|0;h=h+1|0}}e=e+1|0;if((e|0)==(d|0))break;else{l=l+a|0;k=k+s|0}}}k=a<<1;l=_(r,b)|0;if(A&(d|0)>0){b=1;e=0;h=0;u=l;do{e=e+k|0;h=h+r|0;u=u-r|0;i=0;z=e;C=h;v=u;while(1){c[f+(z+-1<<2)>>2]=c[j+(C<<2)>>2];c[f+(z<<2)>>2]=c[j+(v<<2)>>2];i=i+1|0;if((i|0)==(d|0))break;else{z=z+s|0;C=C+a|0;v=v+a|0}}b=b+1|0}while((b|0)!=(p|0))}if(t)return;t=0-a|0;if((q|0)>=(d|0)){if(!A)return;q=(d|0)<1|(a|0)<3;b=1;u=t;h=0;e=0;v=l;do{u=u+k|0;h=h+k|0;e=e+r|0;v=v-r|0;if(!q){C=0;z=u;i=h;x=e;y=v;while(1){B=2;do{F=B+x|0;G=j+(F+-1<<2)|0;K=B+y|0;L=j+(K+-1<<2)|0;J=B+i|0;g[f+(J+-1<<2)>>2]=+g[L>>2]+ +g[G>>2];D=a-B+z|0;g[f+(D+-1<<2)>>2]=+g[G>>2]-+g[L>>2];L=j+(F<<2)|0;F=j+(K<<2)|0;g[f+(J<<2)>>2]=+g[F>>2]+ +g[L>>2];g[f+(D<<2)>>2]=+g[F>>2]-+g[L>>2];B=B+2|0}while((B|0)<(a|0));C=C+1|0;if((C|0)==(d|0))break;else{z=z+s|0;i=i+s|0;x=x+a|0;y=y+a|0}}}b=b+1|0}while((b|0)!=(p|0));return}if(!A)return;A=(a|0)>2;b=(d|0)>0;v=1;e=t;t=0;h=0;u=l;do{e=e+k|0;t=t+k|0;h=h+r|0;u=u-r|0;if(A?(l=e+a|0,b):0){q=2;do{y=0;x=l-q|0;i=q+t|0;z=q+h|0;C=q+u|0;while(1){B=j+(z+-1<<2)|0;L=j+(C+-1<<2)|0;g[f+(i+-1<<2)>>2]=+g[L>>2]+ +g[B>>2];g[f+(x+-1<<2)>>2]=+g[B>>2]-+g[L>>2];L=j+(z<<2)|0;B=j+(C<<2)|0;g[f+(i<<2)>>2]=+g[B>>2]+ +g[L>>2];g[f+(x<<2)>>2]=+g[B>>2]-+g[L>>2];y=y+1|0;if((y|0)==(d|0))break;else{x=x+s|0;i=i+s|0;z=z+a|0;C=C+a|0}}q=q+2|0}while((q|0)<(a|0))}v=v+1|0}while((v|0)!=(p|0));return}function Ub(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0;e=i;f=c[a>>2]|0;h=i;i=i+((1*(f<<2)|0)+15&-16)|0;j=a+24|0;Vb(f,c[j>>2]|0,b,d,140.0,-1);k=(f|0)>0;if(k){l=0;do{g[h+(l<<2)>>2]=+g[b+(l<<2)>>2]-+g[d+(l<<2)>>2];l=l+1|0}while((l|0)!=(f|0))}l=a+4|0;Vb(f,c[j>>2]|0,h,d,0.0,c[(c[l>>2]|0)+128>>2]|0);if(k)m=0;else{i=e;return}do{j=h+(m<<2)|0;g[j>>2]=+g[b+(m<<2)>>2]-+g[j>>2];m=m+1|0}while((m|0)!=(f|0));if(!k){i=e;return}k=c[l>>2]|0;l=0;do{m=d+(l<<2)|0;b=~~(+g[m>>2]+.5);j=(b|0)>39?39:b;g[m>>2]=+g[k+336+(((j|0)<0?0:j)<<2)>>2]+ +g[h+(l<<2)>>2];l=l+1|0}while((l|0)!=(f|0));i=e;return}function Vb(a,b,d,e,f,h){a=a|0;b=b|0;d=d|0;e=e|0;f=+f;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0.0,r=0.0,s=0.0,t=0.0,u=0.0,v=0.0,w=0.0,x=0.0,y=0.0,z=0,A=0.0,B=0.0,C=0.0,D=0,E=0.0,F=0,G=0,H=0,I=0.0,J=0.0,K=0.0,L=0,M=0.0,N=0.0,O=0.0,P=0.0,Q=0,R=0.0,S=0.0,T=0.0,U=0.0,V=0,W=0.0,X=0,Y=0.0;j=i;k=a<<2;l=i;i=i+((1*k|0)+15&-16)|0;m=i;i=i+((1*k|0)+15&-16)|0;n=i;i=i+((1*k|0)+15&-16)|0;o=i;i=i+((1*k|0)+15&-16)|0;p=i;i=i+((1*k|0)+15&-16)|0;q=+g[d>>2]+f;r=q<1.0?1.0:q;q=r*r*.5;s=q*r;g[l>>2]=q;g[m>>2]=q;g[n>>2]=0.0;g[o>>2]=s;g[p>>2]=0.0;if((a|0)>1){k=1;r=q;t=q;q=0.0;u=0.0;v=s;s=1.0;while(1){w=+g[d+(k<<2)>>2]+f;x=w<1.0?1.0:w;w=x*x;r=w+r;y=w*s;t=y+t;q=y*s+q;v=w*x+v;u=y*x+u;g[l+(k<<2)>>2]=r;g[m+(k<<2)>>2]=t;g[n+(k<<2)>>2]=q;g[o+(k<<2)>>2]=v;g[p+(k<<2)>>2]=u;k=k+1|0;if((k|0)==(a|0))break;else s=s+1.0}}k=c[b>>2]|0;d=k>>16;if((d|0)>-1){z=k;A=0.0;B=0.0;C=1.0;D=0;E=0.0}else{F=k;k=d;d=0;s=0.0;while(1){G=F&65535;H=0-k|0;u=+g[l+(H<<2)>>2]+ +g[l+(G<<2)>>2];v=+g[m+(G<<2)>>2]-+g[m+(H<<2)>>2];q=+g[n+(H<<2)>>2]+ +g[n+(G<<2)>>2];t=+g[o+(H<<2)>>2]+ +g[o+(G<<2)>>2];r=+g[p+(G<<2)>>2]-+g[p+(H<<2)>>2];x=t*q-r*v;y=r*u-t*v;t=q*u-v*v;v=(y*s+x)/t;g[e+(d<<2)>>2]=(v<0.0?0.0:v)-f;H=d+1|0;v=s+1.0;G=c[b+(H<<2)>>2]|0;k=G>>16;if((k|0)>-1){z=G;A=x;B=y;C=t;D=H;E=v;break}else{F=G;d=H;s=v}}}d=z&65535;if((d|0)<(a|0)){F=z;z=d;d=D;s=E;while(1){k=F>>16;v=+g[l+(z<<2)>>2]-+g[l+(k<<2)>>2];t=+g[m+(z<<2)>>2]-+g[m+(k<<2)>>2];y=+g[n+(z<<2)>>2]-+g[n+(k<<2)>>2];x=+g[o+(z<<2)>>2]-+g[o+(k<<2)>>2];u=+g[p+(z<<2)>>2]-+g[p+(k<<2)>>2];q=x*y-u*t;r=u*v-x*t;x=y*v-t*t;t=(r*s+q)/x;g[e+(d<<2)>>2]=(t<0.0?0.0:t)-f;k=d+1|0;t=s+1.0;F=c[b+(k<<2)>>2]|0;z=F&65535;if((z|0)>=(a|0)){I=q;J=r;K=x;L=k;M=t;break}else{d=k;s=t}}}else{I=A;J=B;K=C;L=D;M=E}if((L|0)<(a|0)){D=L;E=M;while(1){M=(E*J+I)/K;g[e+(D<<2)>>2]=(M<0.0?0.0:M)-f;D=D+1|0;if((D|0)==(a|0))break;else E=E+1.0}}if((h|0)<1){i=j;return}D=(h|0)/2|0;L=D-h|0;if((L|0)>-1){N=I;O=J;P=K;Q=0;R=0.0}else{d=h-D|0;z=D;F=L;L=0;K=0.0;while(1){b=0-F|0;J=+g[l+(b<<2)>>2]+ +g[l+(z<<2)>>2];I=+g[m+(z<<2)>>2]-+g[m+(b<<2)>>2];E=+g[n+(b<<2)>>2]+ +g[n+(z<<2)>>2];M=+g[o+(b<<2)>>2]+ +g[o+(z<<2)>>2];C=+g[p+(z<<2)>>2]-+g[p+(b<<2)>>2];B=M*E-C*I;A=C*J-M*I;M=E*J-I*I;I=(A*K+B)/M-f;b=e+(L<<2)|0;if(I<+g[b>>2])g[b>>2]=I;L=L+1|0;I=K+1.0;b=L+D|0;if((L|0)==(d|0)){N=B;O=A;P=M;Q=d;R=I;break}else{z=b;F=b-h|0;K=I}}}F=Q+D|0;if((F|0)<(a|0)){z=a-D|0;d=F;F=Q;K=R;while(1){L=d-h|0;I=+g[l+(d<<2)>>2]-+g[l+(L<<2)>>2];M=+g[m+(d<<2)>>2]-+g[m+(L<<2)>>2];A=+g[n+(d<<2)>>2]-+g[n+(L<<2)>>2];B=+g[o+(d<<2)>>2]-+g[o+(L<<2)>>2];J=+g[p+(d<<2)>>2]-+g[p+(L<<2)>>2];E=B*A-J*M;C=J*I-B*M;B=A*I-M*M;M=(C*K+E)/B-f;L=e+(F<<2)|0;if(M<+g[L>>2])g[L>>2]=M;L=F+1|0;M=K+1.0;if((L|0)==(z|0)){S=E;T=C;U=B;V=z;W=M;break}else{d=L+D|0;F=L;K=M}}}else{S=N;T=O;U=P;V=Q;W=R}if((V|0)<(a|0)){X=V;Y=W}else{i=j;return}while(1){W=(Y*T+S)/U-f;V=e+(X<<2)|0;if(W<+g[V>>2])g[V>>2]=W;X=X+1|0;if((X|0)==(a|0))break;else Y=Y+1.0}i=j;return}function Wb(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=+e;f=+f;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0.0,q=0,r=0.0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0.0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0.0,N=0.0,O=0,P=0,Q=0,R=0;h=i;j=c[a>>2]|0;k=a+40|0;l=c[k>>2]|0;m=i;i=i+((1*(l<<2)|0)+15&-16)|0;n=a+4|0;o=c[n>>2]|0;p=+g[o+4>>2]+f;if((l|0)>0){q=0;do{g[m+(q<<2)>>2]=-9999.0;q=q+1|0}while((q|0)<(l|0))}f=+g[o+8>>2];r=p<f?f:p;l=(j|0)>0;if(l){q=c[a+16>>2]|0;s=0;do{g[d+(s<<2)>>2]=+g[q+(s<<2)>>2]+r;s=s+1|0}while((s|0)!=(j|0));s=c[a+8>>2]|0;r=+g[o+496>>2]-e;if(l){l=a+20|0;o=c[l>>2]|0;q=a+32|0;t=a+36|0;u=a+28|0;v=0;while(1){w=c[o+(v<<2)>>2]|0;x=v;e=+g[b+(v<<2)>>2];a:while(1){y=x;while(1){z=y+1|0;if((z|0)>=(j|0)){A=0;B=z;C=y;D=e;break a}if((c[o+(z<<2)>>2]|0)!=(w|0)){A=1;B=z;C=y;D=e;break a}p=+g[b+(z<<2)>>2];if(p>e){x=z;e=p;continue a}else y=z}}if(D+6.0>+g[d+(C<<2)>>2]?(x=w>>c[q>>2],y=(x|0)>16?16:x,x=c[k>>2]|0,z=c[t>>2]|0,E=~~((r+D+-30.0)*.10000000149011612),F=(E|0)<0?0:E,E=c[(c[s+(((y|0)<0?0:y)<<2)>>2]|0)+(((F|0)>7?7:F)<<2)>>2]|0,F=E+8|0,y=~~+g[E+4>>2],e=+g[E>>2],E=~~e,(E|0)<(y|0)):0){G=E;E=~~((e+-16.0)*+(z|0)-+(z>>1|0)+ +((c[o+(C<<2)>>2]|0)-(c[u>>2]|0)|0));do{if((E|0)>0?(e=+g[F+(G<<2)>>2]+D,H=m+(E<<2)|0,+g[H>>2]<e):0)g[H>>2]=e;E=E+z|0;G=G+1|0}while((G|0)<(y|0)&(E|0)<(x|0))}if(A)v=B;else{I=l;J=t;break}}}else K=7}else K=7;if((K|0)==7){I=a+20|0;J=a+36|0}K=c[J>>2]|0;Xb(m,K,c[k>>2]|0);J=c[a>>2]|0;b:do if((J|0)>1){t=c[I>>2]|0;l=c[t>>2]|0;B=c[a+28>>2]|0;v=(c[n>>2]|0)+32|0;A=1;u=l;C=0;o=l-(K>>1)-B|0;while(1){D=+g[m+(o<<2)>>2];l=((c[t+(A<<2)>>2]|0)+u>>1)-B|0;r=+g[v>>2];e=D>r?r:D;c:do if((o|0)<(l|0)){s=o;D=e;while(1){q=s+1|0;d:do if(D==-9999.0){L=q;M=+g[m+(q<<2)>>2]}else{b=q;while(1){r=+g[m+(b<<2)>>2];if(r>-9999.0&r<D){L=b;M=r;break d}if((b|0)<(l|0))b=b+1|0;else{N=D;O=b;break c}}}while(0);if((L|0)<(l|0)){s=L;D=M}else{N=M;O=L;break}}}else{N=e;O=o}while(0);l=O+B|0;e:do if((C|0)<(J|0)){s=c[I>>2]|0;q=C;while(1){if((c[s+(q<<2)>>2]|0)>(l|0)){P=q;break e}b=d+(q<<2)|0;if(+g[b>>2]<N)g[b>>2]=N;b=q+1|0;if((b|0)<(J|0))q=b;else{P=b;break}}}else P=C;while(0);l=P+1|0;if((l|0)>=(J|0)){Q=P;break b}A=l;u=c[t+(P<<2)>>2]|0;C=P;o=O}}else Q=0;while(0);N=+g[m+((c[k>>2]|0)+-1<<2)>>2];if((Q|0)<(J|0))R=Q;else{i=h;return}do{Q=d+(R<<2)|0;if(+g[Q>>2]<N)g[Q>>2]=N;R=R+1|0}while((R|0)!=(J|0));i=h;return}function Xb(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,j=0,k=0,l=0,m=0.0,n=0,o=0.0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;e=i;f=d<<2;h=i;i=i+((1*f|0)+15&-16)|0;j=i;i=i+((1*f|0)+15&-16)|0;if((d|0)>0){k=0;l=0}else{i=e;return}while(1){do if((l|0)>=2){m=+g[a+(k<<2)>>2];f=l;while(1){n=f+-1|0;o=+g[j+(n<<2)>>2];if(m<o){p=f;q=8;break}if(!((f|0)>1?(k|0)<((c[h+(n<<2)>>2]|0)+b|0):0)){r=f;q=12;break}s=f+-2|0;if(!(o<=+g[j+(s<<2)>>2])){r=f;q=12;break}if((k|0)<((c[h+(s<<2)>>2]|0)+b|0))f=n;else{r=f;q=12;break}}if((q|0)==8){q=0;c[h+(p<<2)>>2]=k;g[j+(p<<2)>>2]=m;t=p;break}else if((q|0)==12){q=0;c[h+(r<<2)>>2]=k;g[j+(r<<2)>>2]=m;t=r;break}}else{c[h+(l<<2)>>2]=k;c[j+(l<<2)>>2]=c[a+(k<<2)>>2];t=l}while(0);f=t+1|0;k=k+1|0;if((k|0)==(d|0)){u=t;v=f;break}else l=f}if((u|0)<=-1){i=e;return}l=b+1|0;b=0;t=0;while(1){if((b|0)<(u|0)?(k=b+1|0,+g[j+(k<<2)>>2]>+g[j+(b<<2)>>2]):0)w=c[h+(k<<2)>>2]|0;else w=l+(c[h+(b<<2)>>2]|0)|0;k=(w|0)>(d|0)?d:w;if((t|0)<(k|0)){r=c[j+(b<<2)>>2]|0;q=t;do{c[a+(q<<2)>>2]=r;q=q+1|0}while((q|0)<(k|0));x=k}else x=t;b=b+1|0;if((b|0)==(v|0))break;else t=x}i=e;return}function Yb(a,b,d,e,f,h,i){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;h=h|0;i=i|0;var j=0,k=0,l=0.0,m=0,n=0,o=0.0,p=0.0,q=0.0,r=0,s=0.0,t=0.0,u=0.0;j=c[a>>2]|0;k=c[a+4>>2]|0;l=+g[k+12+(e<<2)>>2];if((j|0)<=0)return;m=c[(c[a+12>>2]|0)+(e<<2)>>2]|0;n=k+108|0;o=+g[a+48>>2];p=o*.005;q=o*.0003;if((e|0)==1)r=0;else{e=0;do{o=+g[m+(e<<2)>>2]+ +g[b+(e<<2)>>2];s=+g[n>>2];t=o>s?s:o;o=+g[d+(e<<2)>>2]+l;g[f+(e<<2)>>2]=t<o?o:t;e=e+1|0}while((e|0)!=(j|0));return}do{t=+g[m+(r<<2)>>2]+ +g[b+(r<<2)>>2];o=+g[n>>2];s=t>o?o:t;t=+g[d+(r<<2)>>2]+l;g[f+(r<<2)>>2]=s<t?t:s;t=s-+g[i+(r<<2)>>2];s=t+17.200000762939453;if(t>-17.200000762939453){t=1.0-p*s;if(t<0.0)u=9.999999747378752e-05;else u=t}else u=1.0-q*s;e=h+(r<<2)|0;g[e>>2]=+g[e>>2]*u;r=r+1|0}while((r|0)!=(j|0));return}function Zb(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0.0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0,ta=0,ua=0,va=0,wa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0,Na=0,Oa=0,Pa=0,Qa=0,Ra=0,Sa=0,Ta=0,Ua=0,Va=0,Wa=0,Xa=0,Ya=0,Za=0,_a=0,$a=0,ab=0,bb=0,cb=0.0,db=0.0,fb=0,gb=0,hb=0.0,ib=0,jb=0,kb=0,lb=0,mb=0;f=i;i=i+4912|0;h=f+1328|0;j=f+1064|0;k=f+804|0;l=f+544|0;m=f+284|0;n=f+24|0;o=f+20|0;p=f+16|0;q=f+12|0;r=f+8|0;s=f+4|0;t=f;u=c[b+1296>>2]|0;v=c[b+1288>>2]|0;w=c[b+1284>>2]|0;x=(w|0)>0;if(x){y=0;do{c[j+(y<<2)>>2]=-200;y=y+1|0}while((y|0)!=(w|0));if(x){y=0;do{c[k+(y<<2)>>2]=-200;y=y+1|0}while((y|0)!=(w|0));if(x){md(l|0,0,w<<2|0)|0;y=0;do{c[m+(y<<2)>>2]=1;y=y+1|0}while((y|0)!=(w|0));if(x){md(n|0,-1,w<<2|0)|0;if((w|0)<=1){z=0;i=f;return z|0}x=v+-1|0;y=u+1112|0;A=w+-1|0;B=c[b>>2]|0;C=0;D=0;while(1){E=C;C=C+1|0;F=B;B=c[b+(C<<2)>>2]|0;G=h+(E*56|0)|0;H=G;I=H+56|0;do{c[H>>2]=0;H=H+4|0}while((H|0)<(I|0));c[G>>2]=F;c[h+(E*56|0)+4>>2]=B;J=(B|0)<(v|0)?B:x;if((J|0)<(F|0)){K=0;L=0;M=0;N=0;O=0;P=0;Q=0;R=0;S=0;T=0;U=0;V=0}else{W=F;X=0;Y=0;Z=0;$=0;aa=0;ba=0;ca=0;da=0;ea=0;fa=0;ga=0;ha=0;while(1){ia=+g[e+(W<<2)>>2];ja=~~(ia*7.314285755157471+1023.5);ka=(ja|0)>1023;la=(ja|0)<0;ma=ka?1023:la?0:ja;do if(ma)if(!(+g[y>>2]+ +g[d+(W<<2)>>2]>=ia)){na=(_(W,W)|0)+$|0;oa=_(ja,ja)|0;pa=X;qa=Y+1|0;ra=Z;sa=na;ta=aa;ua=W+ba|0;va=ca;wa=(_(ma,W)|0)+da|0;ya=ea;za=(ka?1046529:la?0:oa)+fa|0;Aa=ga;Ba=ma+ha|0;break}else{oa=(_(W,W)|0)+Z|0;na=_(ja,ja)|0;pa=X+1|0;qa=Y;ra=oa;sa=$;ta=W+aa|0;ua=ba;va=(_(ma,W)|0)+ca|0;wa=da;ya=(ka?1046529:la?0:na)+ea|0;za=fa;Aa=ma+ga|0;Ba=ha;break}else{pa=X;qa=Y;ra=Z;sa=$;ta=aa;ua=ba;va=ca;wa=da;ya=ea;za=fa;Aa=ga;Ba=ha}while(0);if((W|0)<(J|0)){W=W+1|0;X=pa;Y=qa;Z=ra;$=sa;aa=ta;ba=ua;ca=va;da=wa;ea=ya;fa=za;ga=Aa;ha=Ba}else{K=pa;L=qa;M=ra;N=sa;O=ta;P=ua;Q=va;R=wa;S=ya;T=za;U=Aa;V=Ba;break}}}c[h+(E*56|0)+8>>2]=O;c[h+(E*56|0)+12>>2]=U;c[h+(E*56|0)+16>>2]=M;c[h+(E*56|0)+20>>2]=S;c[h+(E*56|0)+24>>2]=Q;c[h+(E*56|0)+28>>2]=K;c[h+(E*56|0)+32>>2]=P;c[h+(E*56|0)+36>>2]=V;c[h+(E*56|0)+40>>2]=N;c[h+(E*56|0)+44>>2]=T;c[h+(E*56|0)+48>>2]=R;c[h+(E*56|0)+52>>2]=L;ha=K+D|0;if((C|0)==(A|0)){Ca=ha;break}else D=ha}}else Da=9}else Da=9}else Da=9}else Da=9;if((Da|0)==9){if(w|0){z=0;i=f;return z|0}D=h+4|0;H=h;I=H+56|0;do{c[H>>2]=0;H=H+4|0}while((H|0)<(I|0));c[D>>2]=v;if((v|0)<1){Ea=0;Fa=0;Ga=0;Ha=0;Ia=0;Ja=0;Ka=0;La=0;Ma=0;Na=0;Oa=0;Pa=0}else{D=u+1112|0;H=0;I=0;A=0;C=0;K=0;L=0;R=0;T=0;N=0;V=0;P=0;Q=0;S=0;while(1){ia=+g[e+(H<<2)>>2];M=~~(ia*7.314285755157471+1023.5);U=(M|0)>1023;O=(M|0)<0;Ba=U?1023:O?0:M;do if(Ba)if(!(+g[D>>2]+ +g[d+(H<<2)>>2]>=ia)){Aa=(_(H,H)|0)+K|0;za=_(M,M)|0;Qa=I;Ra=A+1|0;Sa=C;Ta=Aa;Ua=L;Va=H+R|0;Wa=T;Xa=(_(Ba,H)|0)+N|0;Ya=V;Za=(U?1046529:O?0:za)+P|0;_a=Q;$a=Ba+S|0;break}else{za=(_(H,H)|0)+C|0;Aa=_(M,M)|0;Qa=I+1|0;Ra=A;Sa=za;Ta=K;Ua=H+L|0;Va=R;Wa=(_(Ba,H)|0)+T|0;Xa=N;Ya=(U?1046529:O?0:Aa)+V|0;Za=P;_a=Ba+Q|0;$a=S;break}else{Qa=I;Ra=A;Sa=C;Ta=K;Ua=L;Va=R;Wa=T;Xa=N;Ya=V;Za=P;_a=Q;$a=S}while(0);H=H+1|0;if((H|0)==(v|0)){Ea=Qa;Fa=Ra;Ga=Sa;Ha=Ta;Ia=Ua;Ja=Va;Ka=Wa;La=Xa;Ma=Ya;Na=Za;Oa=_a;Pa=$a;break}else{I=Qa;A=Ra;C=Sa;K=Ta;L=Ua;R=Va;T=Wa;N=Xa;V=Ya;P=Za;Q=_a;S=$a}}}c[h+8>>2]=Ia;c[h+12>>2]=Oa;c[h+16>>2]=Ga;c[h+20>>2]=Ma;c[h+24>>2]=Ka;c[h+28>>2]=Ea;c[h+32>>2]=Ja;c[h+36>>2]=Pa;c[h+40>>2]=Ha;c[h+44>>2]=Na;c[h+48>>2]=La;c[h+52>>2]=Fa;Ca=Ea}if(!Ca){z=0;i=f;return z|0}c[o>>2]=-200;c[p>>2]=-200;_b(h,w+-1|0,o,p,u)|0;Ca=c[o>>2]|0;c[j>>2]=Ca;c[k>>2]=Ca;o=c[p>>2]|0;p=k+4|0;c[p>>2]=o;Ea=j+4|0;c[Ea>>2]=o;o=(w|0)>2;do if(o){Fa=u+1112|0;La=u+1096|0;Na=u+1100|0;Ha=u+1104|0;Pa=2;a:while(1){Ja=c[b+520+(Pa<<2)>>2]|0;Ka=c[l+(Ja<<2)>>2]|0;Ma=c[m+(Ja<<2)>>2]|0;Ga=n+(Ka<<2)|0;b:do if((c[Ga>>2]|0)!=(Ma|0)){Oa=c[b+520+(Ka<<2)>>2]|0;Ia=c[b+520+(Ma<<2)>>2]|0;c[Ga>>2]=Ma;$a=c[u+836+(Ka<<2)>>2]|0;S=c[u+836+(Ma<<2)>>2]|0;_a=c[j+(Ka<<2)>>2]|0;Q=k+(Ka<<2)|0;Za=c[Q>>2]|0;if((_a|0)>=0)if((Za|0)<0)ab=_a;else ab=Za+_a>>1;else ab=Za;Za=j+(Ma<<2)|0;_a=c[Za>>2]|0;P=c[k+(Ma<<2)>>2]|0;if((_a|0)>=0)if((P|0)<0)bb=_a;else bb=P+_a>>1;else bb=P;if((ab|0)==-1|(bb|0)==-1){Da=38;break a}P=bb-ab|0;_a=S-$a|0;Ya=(P|0)/(_a|0)|0;V=P>>31|1;ia=+g[e+($a<<2)>>2];Xa=~~(ia*7.314285755157471+1023.5);N=(Xa|0)>1023?1023:(Xa|0)<0?0:Xa;Xa=_(Ya,_a)|0;Wa=((P|0)>-1?P:0-P|0)-((Xa|0)>-1?Xa:0-Xa|0)|0;Xa=ab-N|0;P=_(Xa,Xa)|0;cb=+g[Fa>>2];if(cb+ +g[d+($a<<2)>>2]>=ia){ia=+(ab|0);db=+(N|0);if(!(+g[La>>2]+ia<db)?!(ia-+g[Na>>2]>db):0)Da=42}else Da=42;c:do if((Da|0)==42){Da=0;N=$a+1|0;if((N|0)<(S|0)){Xa=N;N=0;T=P;Va=1;R=ab;while(1){Ua=N+Wa|0;L=(Ua|0)<(_a|0);N=Ua-(L?0:_a)|0;R=R+Ya+(L?0:V)|0;db=+g[e+(Xa<<2)>>2];L=~~(db*7.314285755157471+1023.5);Ua=(L|0)>1023?1023:(L|0)<0?0:L;L=R-Ua|0;Ta=(_(L,L)|0)+T|0;L=Va+1|0;if(Ua|0?+g[d+(Xa<<2)>>2]+cb>=db:0){db=+(R|0);ia=+(Ua|0);if(+g[La>>2]+db<ia)break c;if(db-+g[Na>>2]>ia)break c}Xa=Xa+1|0;if((Xa|0)>=(S|0)){fb=Ta;gb=L;break}else{T=Ta;Va=L}}}else{fb=P;gb=1}ia=+g[La>>2];db=+(gb|0);hb=+g[Ha>>2];if((!(ia*ia/db>hb)?(ia=+g[Na>>2],!(ia*ia/db>hb)):0)?+((fb|0)/(gb|0)|0|0)>hb:0)break;c[j+(Pa<<2)>>2]=-200;c[k+(Pa<<2)>>2]=-200;break b}while(0);c[q>>2]=-200;c[r>>2]=-200;c[s>>2]=-200;c[t>>2]=-200;P=_b(h+(Oa*56|0)|0,Ja-Oa|0,q,r,u)|0;S=_b(h+(Ja*56|0)|0,Ia-Ja|0,s,t,u)|0;V=(P|0)!=0;if(V){c[q>>2]=ab;c[r>>2]=c[s>>2]}if((S|0)!=0?(c[s>>2]=c[r>>2],c[t>>2]=bb,V):0){c[j+(Pa<<2)>>2]=-200;c[k+(Pa<<2)>>2]=-200}else Da=55;d:do if((Da|0)==55){Da=0;V=c[q>>2]|0;c[Q>>2]=V;if(!Ka)c[j>>2]=V;V=c[r>>2]|0;c[j+(Pa<<2)>>2]=V;S=c[s>>2]|0;c[k+(Pa<<2)>>2]=S;P=c[t>>2]|0;c[Za>>2]=P;if((Ma|0)==1)c[p>>2]=P;if((S&V|0)>-1){e:do if((Ja|0)>0){V=Ja;do{S=V;V=V+-1|0;P=m+(V<<2)|0;if((c[P>>2]|0)!=(Ma|0))break e;c[P>>2]=Pa}while((S|0)>1)}while(0);V=Ja+1|0;if((V|0)<(w|0)){S=V;do{V=l+(S<<2)|0;if((c[V>>2]|0)!=(Ka|0))break d;c[V>>2]=Pa;S=S+1|0}while((S|0)<(w|0))}}}while(0)}while(0);Pa=Pa+1|0;if((Pa|0)>=(w|0)){Da=69;break}}if((Da|0)==38)xa(1);else if((Da|0)==69){ib=c[j>>2]|0;jb=c[k>>2]|0;break}}else{ib=Ca;jb=Ca}while(0);Ca=eb(a,w<<2)|0;if((ib|0)>=0)if((jb|0)<0)kb=ib;else kb=jb+ib>>1;else kb=jb;c[Ca>>2]=kb;kb=c[Ea>>2]|0;Ea=c[p>>2]|0;if((kb|0)>=0)if((Ea|0)<0)lb=kb;else lb=Ea+kb>>1;else lb=Ea;c[Ca+4>>2]=lb;if(o){o=2;do{lb=o+-2|0;Ea=c[b+1032+(lb<<2)>>2]|0;kb=c[b+780+(lb<<2)>>2]|0;lb=c[u+836+(Ea<<2)>>2]|0;p=c[Ca+(Ea<<2)>>2]&32767;Ea=(c[Ca+(kb<<2)>>2]&32767)-p|0;jb=(_((Ea|0)>-1?Ea:0-Ea|0,(c[u+836+(o<<2)>>2]|0)-lb|0)|0)/((c[u+836+(kb<<2)>>2]|0)-lb|0)|0;lb=((Ea|0)<0?0-jb|0:jb)+p|0;p=c[j+(o<<2)>>2]|0;jb=c[k+(o<<2)>>2]|0;if((p|0)>=0)if((jb|0)<0)mb=p;else mb=jb+p>>1;else mb=jb;c[Ca+(o<<2)>>2]=(mb|0)<0|(lb|0)==(mb|0)?lb|32768:mb;o=o+1|0}while((o|0)!=(w|0))}z=Ca;i=f;return z|0}function _b(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,i=0,j=0.0,k=0.0,l=0.0,m=0.0,n=0.0,o=0.0,p=0,q=0,r=0.0,s=0.0,t=0.0,u=0.0,v=0.0,w=0.0,x=0.0,y=0.0,z=0.0,A=0.0,B=0.0,C=0.0,D=0.0,E=0.0,F=0.0,G=0.0,H=0.0,I=0.0,J=0.0,K=0.0,L=0.0,M=0,N=0,O=0,P=0,Q=0,R=0;h=c[a>>2]|0;i=c[a+((b+-1|0)*56|0)+4>>2]|0;if((b|0)>0){j=+g[f+1108>>2];k=0.0;f=0;l=0.0;m=0.0;n=0.0;o=0.0;while(1){p=c[a+(f*56|0)+52>>2]|0;q=c[a+(f*56|0)+28>>2]|0;r=+(q+p|0)*j/+(q+1|0)+1.0;s=+(c[a+(f*56|0)+32>>2]|0)+m+r*+(c[a+(f*56|0)+8>>2]|0);t=+(c[a+(f*56|0)+36>>2]|0)+o+ +(c[a+(f*56|0)+12>>2]|0)*r;u=+(c[a+(f*56|0)+40>>2]|0)+l+ +(c[a+(f*56|0)+16>>2]|0)*r;v=+(c[a+(f*56|0)+48>>2]|0)+n+ +(c[a+(f*56|0)+24>>2]|0)*r;w=+(p|0)+k+r*+(q|0);f=f+1|0;if((f|0)==(b|0)){x=w;y=u;z=s;A=v;B=t;break}else{k=w;l=u;m=s;n=v;o=t}}}else{x=0.0;y=0.0;z=0.0;A=0.0;B=0.0}b=c[d>>2]|0;if((b|0)>-1){C=x+1.0;D=y+ +(_(h,h)|0);E=z+ +(h|0);F=+(_(b,h)|0)+A;G=+(b|0)+B}else{C=x;D=y;E=z;F=A;G=B}b=c[e>>2]|0;if((b|0)>-1){H=C+1.0;I=D+ +(_(i,i)|0);J=E+ +(i|0);K=+(_(b,i)|0)+F;L=+(b|0)+G}else{H=C;I=D;J=E;K=F;L=G}G=I*H-J*J;if(!(G>0.0)){c[d>>2]=0;c[e>>2]=0;M=1;return M|0}F=(L*I-J*K)/G;I=(K*H-J*L)/G;c[d>>2]=~~+cd(I*+(h|0)+F);h=~~+cd(I*+(i|0)+F);c[e>>2]=h;i=c[d>>2]|0;if((i|0)>1023){c[d>>2]=1023;N=c[e>>2]|0;O=1023}else{N=h;O=i}if((N|0)>1023){c[e>>2]=1023;P=c[d>>2]|0;Q=1023}else{P=O;Q=N}if((P|0)<0){c[d>>2]=0;R=c[e>>2]|0}else R=Q;if((R|0)>=0){M=0;return M|0}c[e>>2]=0;M=0;return M|0}function $b(a){a=a|0;return (c[(c[(c[a+64>>2]|0)+104>>2]|0)+80>>2]|0)!=0|0}function ac(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0;g=c[b+1284>>2]|0;if(!((d|0)!=0&(e|0)!=0)){h=0;return h|0}b=eb(a,g<<2)|0;if((g|0)<=0){h=b;return h|0}a=65536-f|0;i=0;do{j=d+(i<<2)|0;k=_(c[j>>2]&32767,a)|0;l=e+(i<<2)|0;m=k+32768+(_(c[l>>2]&32767,f)|0)>>16;k=b+(i<<2)|0;c[k>>2]=m;if(c[j>>2]&32768|0?c[l>>2]&32768|0:0)c[k>>2]=m|32768;i=i+1|0}while((i|0)!=(g|0));h=b;return h|0}function bc(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0;g=i;i=i+336|0;h=g+64|0;j=g+32|0;k=g;l=c[d+1296>>2]|0;m=d+1284|0;n=c[m>>2]|0;o=c[(c[(c[b+64>>2]|0)+4>>2]|0)+28>>2]|0;p=c[o+2848>>2]|0;if(!e){Sa(a,0,1);md(f|0,0,((c[b+36>>2]|0)/2|0)<<2|0)|0;q=0;i=g;return q|0}a:do if((n|0)>0){r=l+832|0;s=0;while(1){t=e+(s<<2)|0;u=c[t>>2]|0;v=u&32767;switch(c[r>>2]|0){case 1:{w=v>>>2;break}case 2:{w=v>>>3;break}case 3:{w=(v>>>0)/12|0;break}case 4:{w=v>>>4;break}default:w=v}c[t>>2]=u&32768|w;s=s+1|0;if((s|0)==(n|0))break a}}while(0);c[h>>2]=c[e>>2];w=h+4|0;c[w>>2]=c[e+4>>2];s=d+1292|0;if((n|0)>2){r=2;do{u=r+-2|0;t=c[d+1032+(u<<2)>>2]|0;v=c[d+780+(u<<2)>>2]|0;u=c[l+836+(t<<2)>>2]|0;x=e+(t<<2)|0;t=e+(v<<2)|0;y=c[x>>2]&32767;z=(c[t>>2]&32767)-y|0;A=(_((z|0)>-1?z:0-z|0,(c[l+836+(r<<2)>>2]|0)-u|0)|0)/((c[l+836+(v<<2)>>2]|0)-u|0)|0;u=((z|0)<0?0-A|0:A)+y|0;A=e+(r<<2)|0;z=c[A>>2]|0;if((z&32768|0)!=0|(z|0)==(u|0)){c[A>>2]=u|32768;c[h+(r<<2)>>2]=0}else{A=(c[s>>2]|0)-u|0;v=(A|0)<(u|0)?A:u;A=z-u|0;do if((A|0)<0)if((A|0)<(0-v|0)){B=v+~A|0;break}else{B=~(A<<1);break}else if((v|0)>(A|0)){B=A<<1;break}else{B=v+A|0;break}while(0);c[h+(r<<2)>>2]=B;c[x>>2]=y;c[t>>2]=c[t>>2]&32767}r=r+1|0}while((r|0)!=(n|0))}Sa(a,1,1);n=d+1308|0;c[n>>2]=(c[n>>2]|0)+1;n=(c[s>>2]|0)+-1|0;r=(n|0)==0;if(!r){B=n;A=0;while(1){v=A+1|0;B=B>>>1;if(!B){C=v;break}else A=v}A=d+1304|0;c[A>>2]=(c[A>>2]|0)+(C<<1);C=c[h>>2]|0;if(r){D=C;E=A;F=0}else{r=n;n=0;while(1){B=n+1|0;r=r>>>1;if(!r){D=C;E=A;F=B;break}else n=B}}}else{D=c[h>>2]|0;E=d+1304|0;F=0}Sa(a,D,F);F=c[w>>2]|0;w=(c[s>>2]|0)+-1|0;if(!w)G=0;else{s=w;w=0;while(1){D=w+1|0;s=s>>>1;if(!s){G=D;break}else w=D}}Sa(a,F,G);if((c[l>>2]|0)>0){G=d+1300|0;F=0;w=2;while(1){s=c[l+4+(F<<2)>>2]|0;D=c[l+128+(s<<2)>>2]|0;n=c[l+192+(s<<2)>>2]|0;A=1<<n;c[j>>2]=0;c[j+4>>2]=0;c[j+8>>2]=0;c[j+12>>2]=0;c[j+16>>2]=0;c[j+20>>2]=0;c[j+24>>2]=0;c[j+28>>2]=0;if(n|0){C=(n|0)==31;if(!C){r=0;do{B=c[l+320+(s<<5)+(r<<2)>>2]|0;if((B|0)<0)H=1;else H=c[(c[o+1824+(B<<2)>>2]|0)+4>>2]|0;c[k+(r<<2)>>2]=H;r=r+1|0}while((r|0)<(A|0))}b:do if((D|0)>0){if(C){r=0;t=0;y=0;while(1){x=c[j+(y<<2)>>2]<<r|t;y=y+1|0;if((y|0)==(D|0)){I=x;break b}else{r=r+31|0;t=x}}}else{J=0;K=0;L=0}while(1){t=c[h+(L+w<<2)>>2]|0;r=0;while(1){if((t|0)<(c[k+(r<<2)>>2]|0)){M=r;N=37;break}r=r+1|0;if((r|0)>=(A|0)){N=38;break}}if((N|0)==37){N=0;c[j+(L<<2)>>2]=M;O=M}else if((N|0)==38){N=0;O=c[j+(L<<2)>>2]|0}r=O<<J|K;L=L+1|0;if((L|0)==(D|0)){I=r;break}else{J=J+n|0;K=r}}}else I=0;while(0);n=Cb(p+((c[l+256+(s<<2)>>2]|0)*56|0)|0,I,a)|0;c[G>>2]=(c[G>>2]|0)+n}if((D|0)>0){n=0;do{A=c[l+320+(s<<5)+(c[j+(n<<2)>>2]<<2)>>2]|0;if((A|0)>-1?(C=c[h+(n+w<<2)>>2]|0,(C|0)<(c[p+(A*56|0)+4>>2]|0)):0){r=Cb(p+(A*56|0)|0,C,a)|0;c[E>>2]=(c[E>>2]|0)+r}n=n+1|0}while((n|0)!=(D|0))}F=F+1|0;if((F|0)>=(c[l>>2]|0))break;else w=D+w|0}}w=l+832|0;F=_(c[w>>2]|0,c[e>>2]|0)|0;E=(c[o+(c[b+28>>2]<<2)>>2]|0)/2|0;if((c[m>>2]|0)>1){o=0;a=1;p=0;h=F;while(1){j=c[d+260+(a<<2)>>2]|0;G=c[e+(j<<2)>>2]|0;if((G&32767|0)==(G|0)){I=_(c[w>>2]|0,G)|0;G=c[l+836+(j<<2)>>2]|0;j=I-h|0;K=G-p|0;J=(j|0)/(K|0)|0;L=j>>31|1;O=_(J,K)|0;N=((j|0)>-1?j:0-j|0)-((O|0)>-1?O:0-O|0)|0;O=(E|0)>(G|0)?G:E;if((O|0)>(p|0))c[f+(p<<2)>>2]=h;j=p+1|0;if((j|0)<(O|0)){M=j;j=0;k=h;while(1){H=j+N|0;n=(H|0)<(K|0);k=k+J+(n?0:L)|0;c[f+(M<<2)>>2]=k;M=M+1|0;if((M|0)>=(O|0)){P=G;Q=G;R=I;break}else j=H-(n?0:K)|0}}else{P=G;Q=G;R=I}}else{P=o;Q=p;R=h}a=a+1|0;if((a|0)>=(c[m>>2]|0)){S=P;T=R;break}else{o=P;p=Q;h=R}}}else{S=0;T=F}F=b+36|0;if((S|0)<((c[F>>2]|0)/2|0|0))U=S;else{q=1;i=g;return q|0}do{c[f+(U<<2)>>2]=T;U=U+1|0}while((U|0)<((c[F>>2]|0)/2|0|0));q=1;i=g;return q|0}function cc(a,b,d,e,f,j,k,l,m){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;j=j|0;k=k|0;l=l|0;m=m|0;var n=0,o=0,p=0,q=0,r=0,s=0.0,t=0,u=0,v=0,w=0,x=0,y=0,z=0.0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,O=0.0,P=0,Q=0,R=0.0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0.0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0;n=i;o=c[d>>2]|0;p=d+4|0;d=c[p>>2]|0;if(!(c[d+500>>2]|0))q=16;else q=c[d+508>>2]|0;r=c[b+132+((c[d>>2]|0)*60|0)+(a<<2)>>2]|0;s=+h[8+(c[b+252+(a<<2)>>2]<<3)>>3];d=m<<2;t=i;i=i+((1*d|0)+15&-16)|0;u=i;i=i+((1*d|0)+15&-16)|0;v=i;i=i+((1*d|0)+15&-16)|0;w=i;i=i+((1*d|0)+15&-16)|0;x=i;i=i+((1*d|0)+15&-16)|0;y=e+1156|0;z=+h[((o|0)>1e3?80:8)+(c[b+312+(a<<2)>>2]<<3)>>3];a=_(d,q)|0;b=i;i=i+((1*a|0)+15&-16)|0;c[t>>2]=b;A=i;i=i+((1*a|0)+15&-16)|0;c[u>>2]=A;B=i;i=i+((1*a|0)+15&-16)|0;c[v>>2]=B;C=i;i=i+((1*a|0)+15&-16)|0;c[w>>2]=C;if((m|0)>1?(c[t+4>>2]=b+(q<<2),c[u+4>>2]=A+(q<<2),c[v+4>>2]=B+(q<<2),c[w+4>>2]=C+(q<<2),(m|0)!=2):0){C=2;do{B=c[u>>2]|0;A=c[v>>2]|0;b=c[w>>2]|0;D=_(C,q)|0;c[t+(C<<2)>>2]=(c[t>>2]|0)+(D<<2);c[u+(C<<2)>>2]=B+(D<<2);c[v+(C<<2)>>2]=A+(D<<2);c[w+(C<<2)>>2]=b+(D<<2);C=C+1|0}while((C|0)!=(m|0))}C=c[y>>2]|0;if((o|0)>0){D=c[w>>2]|0;b=(m|0)>0;A=0;do{B=o-A|0;E=(q|0)>(B|0)?B:q;od(x|0,k|0,d|0)|0;md(D|0,0,a|0)|0;if(b){B=(E|0)>0;F=r-A|0;G=0;do{H=(c[j+(G<<2)>>2]|0)+(A<<2)|0;if(!(c[x+(G<<2)>>2]|0)){if(B){I=c[v+(G<<2)>>2]|0;J=c[t+(G<<2)>>2]|0;K=c[u+(G<<2)>>2]|0;L=c[w+(G<<2)>>2]|0;M=0;do{g[I+(M<<2)>>2]=1.000000013351432e-10;g[J+(M<<2)>>2]=0.0;g[K+(M<<2)>>2]=0.0;c[L+(M<<2)>>2]=0;c[H+(M<<2)>>2]=0;M=M+1|0}while((M|0)<(E|0))}}else{M=c[v+(G<<2)>>2]|0;if(B){L=0;do{c[M+(L<<2)>>2]=c[33128+(c[H+(L<<2)>>2]<<2)>>2];L=L+1|0}while((L|0)<(E|0));L=f+(G<<2)|0;K=(c[L>>2]|0)+(A<<2)|0;J=c[w+(G<<2)>>2]|0;if(B){I=0;do{O=+N(+(+g[K+(I<<2)>>2]));c[J+(I<<2)>>2]=!(O/+g[M+(I<<2)>>2]<((I|0)>=(F|0)?z:s))&1;I=I+1|0}while((I|0)!=(E|0));if(B){I=c[L>>2]|0;J=c[t+(G<<2)>>2]|0;K=c[u+(G<<2)>>2]|0;P=0;do{Q=I+(P+A<<2)|0;O=+g[Q>>2];R=O*O;S=J+(P<<2)|0;g[S>>2]=R;g[K+(P<<2)>>2]=R;if(+g[Q>>2]<0.0)g[S>>2]=-+g[S>>2];S=M+(P<<2)|0;R=+g[S>>2];g[S>>2]=R*R;P=P+1|0}while((P|0)<(E|0));T=J;U=K}else V=21}else V=21}else V=21;if((V|0)==21){V=0;T=c[t+(G<<2)>>2]|0;U=c[u+(G<<2)>>2]|0}+dc(c[p>>2]|0,r,T,U,M,0,A,E,H)}G=G+1|0}while((G|0)!=(m|0))}G=c[y>>2]|0;if((G|0)>0){B=(E|0)>0;F=l-A|0;K=r-A|0;J=G;P=0;while(1){I=c[e+1160+(P<<2)>>2]|0;L=c[e+2184+(P<<2)>>2]|0;S=(c[j+(I<<2)>>2]|0)+(A<<2)|0;Q=(c[j+(L<<2)>>2]|0)+(A<<2)|0;W=c[t+(I<<2)>>2]|0;X=c[t+(L<<2)>>2]|0;Y=c[u+(I<<2)>>2]|0;Z=c[u+(L<<2)>>2]|0;$=c[v+(I<<2)>>2]|0;aa=c[v+(L<<2)>>2]|0;ba=c[w+(I<<2)>>2]|0;ca=c[w+(L<<2)>>2]|0;da=x+(I<<2)|0;I=x+(L<<2)|0;if((c[da>>2]|0)==0?(c[I>>2]|0)==0:0)ea=J;else{c[I>>2]=1;c[da>>2]=1;if(B){da=0;do{do if((da|0)<(F|0)){I=ba+(da<<2)|0;L=ca+(da<<2)|0;if((c[I>>2]|0)==0?(c[L>>2]|0)==0:0){do if((da|0)>=(K|0)){fa=W+(da<<2)|0;R=+g[fa>>2];ga=X+(da<<2)|0;O=+g[ga>>2];ha=+N(+O)+ +N(+R);g[Y+(da<<2)>>2]=ha;if(O+R<0.0){g[fa>>2]=-ha;ia=ga;break}else{g[fa>>2]=ha;ia=ga;break}}else{ga=X+(da<<2)|0;fa=W+(da<<2)|0;ha=+g[fa>>2]+ +g[ga>>2];g[fa>>2]=ha;g[Y+(da<<2)>>2]=+N(+ha);ia=ga}while(0);g[Z+(da<<2)>>2]=0.0;g[ia>>2]=0.0;c[L>>2]=1;c[Q+(da<<2)>>2]=0;break}ga=W+(da<<2)|0;ha=+N(+(+g[ga>>2]));g[ga>>2]=+N(+(+g[X+(da<<2)>>2]))+ha;ga=Y+(da<<2)|0;g[ga>>2]=+g[Z+(da<<2)>>2]+ +g[ga>>2];c[L>>2]=1;c[I>>2]=1;ga=S+(da<<2)|0;fa=c[ga>>2]|0;ja=Q+(da<<2)|0;ka=c[ja>>2]|0;if((((fa|0)>-1?fa:0-fa|0)|0)>(((ka|0)>-1?ka:0-ka|0)|0)){la=(fa|0)>0?fa-ka|0:ka-fa|0;c[ja>>2]=la;ma=c[ga>>2]|0;na=la}else{c[ja>>2]=(ka|0)>0?fa-ka|0:ka-fa|0;c[ga>>2]=ka;ma=ka;na=c[ja>>2]|0}if((na|0)>=(((ma|0)>-1?ma:0-ma|0)<<1|0)){c[ja>>2]=0-na;c[ga>>2]=0-(c[ga>>2]|0)}}while(0);ga=$+(da<<2)|0;ja=aa+(da<<2)|0;ha=+g[ja>>2]+ +g[ga>>2];g[ja>>2]=ha;g[ga>>2]=ha;da=da+1|0}while((da|0)<(E|0))}+dc(c[p>>2]|0,r,W,Y,$,ba,A,E,S);ea=c[y>>2]|0}P=P+1|0;if((P|0)>=(ea|0)){oa=ea;break}else J=ea}}else oa=G;A=A+q|0}while((o|0)>(A|0));pa=oa}else pa=C;if((pa|0)>0){qa=pa;ra=0}else{i=n;return}while(1){pa=k+(c[e+1160+(ra<<2)>>2]<<2)|0;C=e+2184+(ra<<2)|0;if((c[pa>>2]|0)==0?(c[k+(c[C>>2]<<2)>>2]|0)==0:0)sa=qa;else{c[pa>>2]=1;c[k+(c[C>>2]<<2)>>2]=1;sa=c[y>>2]|0}ra=ra+1|0;if((ra|0)>=(sa|0))break;else qa=sa}i=n;return}function dc(a,b,d,e,f,j,l,m,n){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;j=j|0;l=l|0;m=m|0;n=n|0;var o=0,p=0,q=0,r=0,s=0,t=0.0,u=0,v=0,w=0.0,x=0.0,y=0.0,z=0,A=0.0,B=0,C=0.0,D=0,E=0.0,F=0,G=0.0,H=0,I=0.0;o=i;p=i;i=i+((1*(m<<2)|0)+15&-16)|0;if(!(c[a+500>>2]|0))q=m;else q=(c[a+504>>2]|0)-l|0;r=(q|0)>(m|0)?m:q;a:do if((r|0)>0){if(!j){q=0;while(1){s=+g[d+(q<<2)>>2]<0.0;t=+cd(+O(+(+g[e+(q<<2)>>2]/+g[f+(q<<2)>>2])));c[n+(q<<2)>>2]=~~(s?-t:t);q=q+1|0;if((q|0)>=(r|0)){u=r;break a}}}else v=0;do{do if(!(c[j+(v<<2)>>2]|0)){q=+g[d+(v<<2)>>2]<0.0;t=+cd(+O(+(+g[e+(v<<2)>>2]/+g[f+(v<<2)>>2])));if(q){c[n+(v<<2)>>2]=~~-t;break}else{c[n+(v<<2)>>2]=~~t;break}}while(0);v=v+1|0}while((v|0)<(r|0));u=r}else u=0;while(0);if((u|0)>=(m|0)){w=0.0;i=o;return +w}r=b-l|0;if(!j){t=0.0;l=0;b=u;while(1){v=e+(b<<2)|0;q=f+(b<<2)|0;x=+g[v>>2]/+g[q>>2];if(x<.25){c[p+(l<<2)>>2]=v;y=x+t;z=l+1|0}else{s=+g[d+(b<<2)>>2]<0.0;A=+cd(+O(+x));B=~~(s?-A:A);c[n+(b<<2)>>2]=B;A=+(_(B,B)|0);g[v>>2]=A*+g[q>>2];y=t;z=l}b=b+1|0;if((b|0)==(m|0)){C=y;D=z;break}else{t=y;l=z}}}else{y=0.0;z=0;l=u;while(1){do if(!(c[j+(l<<2)>>2]|0)){u=e+(l<<2)|0;b=f+(l<<2)|0;t=+g[u>>2]/+g[b>>2];if(!(t<.25)|(l|0)<(r|0)){q=+g[d+(l<<2)>>2]<0.0;A=+cd(+O(+t));v=~~(q?-A:A);c[n+(l<<2)>>2]=v;A=+(_(v,v)|0);g[u>>2]=A*+g[b>>2];E=y;F=z;break}else{c[p+(z<<2)>>2]=u;E=t+y;F=z+1|0;break}}else{E=y;F=z}while(0);l=l+1|0;if((l|0)==(m|0)){C=E;D=F;break}else{y=E;z=F}}}if(!D){w=C;i=o;return +w}Yc(p,D,4,12);if((D|0)<=0){w=C;i=o;return +w}F=e;E=+h[a+512>>3];y=C;a=0;while(1){e=c[p+(a<<2)>>2]|0;z=e-F>>2;if(!(y>=E)){G=y;H=0;I=0.0}else{G=y+-1.0;H=~~(c[k>>2]=c[d+(z<<2)>>2]&-2147483648|1065353216,+g[k>>2]);I=+g[f+(z<<2)>>2]}c[n+(z<<2)>>2]=H;g[e>>2]=I;a=a+1|0;if((a|0)==(D|0)){w=G;break}else y=G}i=o;return +w}function ec(a,b){a=a|0;b=b|0;var d=0.0,e=0.0;d=+g[c[a>>2]>>2];e=+g[c[b>>2]>>2];return (d<e&1)-(d>e&1)|0}function fc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0.0,E=0.0,F=0;d=i;e=c[a+64>>2]|0;f=c[e+4>>2]|0;h=c[f+28>>2]|0;j=c[e+104>>2]|0;e=a+28|0;k=c[h+(c[e>>2]<<2)>>2]|0;c[a+36>>2]=k;l=f+4|0;f=c[l>>2]|0;m=f<<2;n=i;i=i+((1*m|0)+15&-16)|0;o=i;i=i+((1*m|0)+15&-16)|0;p=i;i=i+((1*m|0)+15&-16)|0;q=i;i=i+((1*m|0)+15&-16)|0;if((f|0)>0){m=b+4|0;r=b+1028|0;s=j+48|0;t=k<<1&2147483646;u=0;do{v=c[r+(c[m+(u<<2)>>2]<<2)>>2]|0;w=Ga[c[(c[34164+(c[h+800+(v<<2)>>2]<<2)>>2]|0)+20>>2]&15](a,c[(c[s>>2]|0)+(v<<2)>>2]|0)|0;c[q+(u<<2)>>2]=w;c[p+(u<<2)>>2]=(w|0)!=0&1;md(c[(c[a>>2]|0)+(u<<2)>>2]|0,0,t|0)|0;u=u+1|0;w=c[l>>2]|0}while((u|0)<(w|0));x=w}else x=f;f=b+1156|0;u=c[f>>2]|0;if((u|0)>0){t=b+1160|0;s=b+2184|0;m=0;do{r=p+(c[t+(m<<2)>>2]<<2)|0;w=c[s+(m<<2)>>2]|0;if(!((c[r>>2]|0)==0?!(c[p+(w<<2)>>2]|0):0)){c[r>>2]=1;c[p+(w<<2)>>2]=1}m=m+1|0}while((m|0)<(u|0))}if((c[b>>2]|0)>0){m=b+1092|0;s=j+52|0;t=b+4|0;w=x;x=0;while(1){if((w|0)>0){r=w;v=0;y=0;while(1){if((c[t+(y<<2)>>2]|0)==(x|0)){c[o+(v<<2)>>2]=(c[p+(y<<2)>>2]|0)!=0&1;c[n+(v<<2)>>2]=c[(c[a>>2]|0)+(y<<2)>>2];z=c[l>>2]|0;A=v+1|0}else{z=r;A=v}y=y+1|0;if((y|0)>=(z|0)){B=A;break}else{r=z;v=A}}}else B=0;v=c[m+(x<<2)>>2]|0;Ha[c[(c[34152+(c[h+1312+(v<<2)>>2]<<2)>>2]|0)+28>>2]&7](a,c[(c[s>>2]|0)+(v<<2)>>2]|0,n,o,B)|0;v=x+1|0;if((v|0)>=(c[b>>2]|0))break;w=c[l>>2]|0;x=v}C=c[f>>2]|0}else C=u;if((C|0)>0?(u=b+1160|0,f=c[a>>2]|0,x=b+2184|0,w=(k|0)/2|0,(k|0)>1):0){k=C;do{C=k;k=k+-1|0;B=c[f+(c[u+(k<<2)>>2]<<2)>>2]|0;o=c[f+(c[x+(k<<2)>>2]<<2)>>2]|0;n=0;do{s=B+(n<<2)|0;D=+g[s>>2];m=o+(n<<2)|0;E=+g[m>>2];A=E>0.0;do if(D>0.0)if(A){g[m>>2]=D-E;break}else{g[m>>2]=D;g[s>>2]=E+D;break}else if(A){g[m>>2]=E+D;break}else{g[m>>2]=D;g[s>>2]=D-E;break}while(0);n=n+1|0}while((n|0)<(w|0))}while((C|0)>1)}if((c[l>>2]|0)<=0){i=d;return 0}w=b+4|0;k=b+1028|0;b=j+48|0;x=0;do{f=c[k+(c[w+(x<<2)>>2]<<2)>>2]|0;Aa[c[(c[34164+(c[h+800+(f<<2)>>2]<<2)>>2]|0)+24>>2]&7](a,c[(c[b>>2]|0)+(f<<2)>>2]|0,c[q+(x<<2)>>2]|0,c[(c[a>>2]|0)+(x<<2)>>2]|0)|0;x=x+1|0;f=c[l>>2]|0}while((x|0)<(f|0));F=f;if((F|0)<=0){i=d;return 0}F=0;do{x=c[(c[a>>2]|0)+(F<<2)>>2]|0;gc(c[c[j+12+(c[e>>2]<<2)>>2]>>2]|0,x,x);F=F+1|0}while((F|0)<(c[l>>2]|0));i=d;return 0}function gc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0.0,v=0.0,w=0.0,x=0.0,y=0.0,z=0.0,A=0.0,B=0.0,C=0.0,D=0.0,E=0,F=0;e=c[a>>2]|0;f=e>>1;h=e>>2;e=b+(f<<2)|0;i=d+(f<<2)|0;j=i+(h<<2)|0;k=a+8|0;l=c[k>>2]|0;m=l+(h<<2)|0;n=m;o=e+-28|0;p=j;while(1){q=p;p=p+-16|0;r=o+8|0;s=n+12|0;t=n+8|0;g[p>>2]=-(+g[r>>2]*+g[s>>2])-+g[t>>2]*+g[o>>2];g[q+-12>>2]=+g[s>>2]*+g[o>>2]-+g[t>>2]*+g[r>>2];r=o+24|0;t=n+4|0;s=o+16|0;g[q+-8>>2]=-(+g[r>>2]*+g[t>>2])-+g[n>>2]*+g[s>>2];g[q+-4>>2]=+g[t>>2]*+g[s>>2]-+g[n>>2]*+g[r>>2];o=o+-32|0;if(o>>>0<b>>>0)break;else n=n+16|0}n=m;m=e+-32|0;e=j;while(1){o=m+16|0;p=n+-4|0;r=m+24|0;s=n+-8|0;g[e>>2]=+g[s>>2]*+g[r>>2]+ +g[p>>2]*+g[o>>2];g[e+4>>2]=+g[s>>2]*+g[o>>2]-+g[p>>2]*+g[r>>2];r=n+-12|0;n=n+-16|0;p=m+8|0;g[e+8>>2]=+g[n>>2]*+g[p>>2]+ +g[r>>2]*+g[m>>2];g[e+12>>2]=+g[n>>2]*+g[m>>2]-+g[r>>2]*+g[p>>2];m=m+-32|0;if(m>>>0<b>>>0)break;else e=e+16|0}Pb(c[a+4>>2]|0,l,i,f);l=c[a>>2]|0;e=c[k>>2]|0;k=d+(l>>1<<2)|0;b=e+(l<<2)|0;l=c[a+12>>2]|0;a=d;m=k;while(1){n=k+(c[l>>2]<<2)|0;p=k+(c[l+4>>2]<<2)|0;u=+g[n+4>>2];v=+g[p+4>>2];w=u-v;x=+g[n>>2];y=+g[p>>2];z=y+x;A=+g[b>>2];B=+g[b+4>>2];C=B*w+z*A;D=B*z-A*w;p=m;m=m+-16|0;w=(v+u)*.5;u=(x-y)*.5;g[a>>2]=C+w;g[p+-8>>2]=w-C;g[a+4>>2]=D+u;g[p+-4>>2]=D-u;n=k+(c[l+8>>2]<<2)|0;r=k+(c[l+12>>2]<<2)|0;u=+g[n+4>>2];D=+g[r+4>>2];C=u-D;w=+g[n>>2];y=+g[r>>2];x=y+w;v=+g[b+8>>2];A=+g[b+12>>2];z=A*C+x*v;B=A*x-v*C;C=(D+u)*.5;u=(w-y)*.5;g[a+8>>2]=z+C;g[m>>2]=C-z;g[a+12>>2]=B+u;g[p+-12>>2]=B-u;a=a+16|0;if(a>>>0>=m>>>0)break;else{b=b+16|0;l=l+16|0}}l=e+(f<<2)|0;f=d;e=j;b=j;while(1){m=l+4|0;a=f+4|0;g[e+-4>>2]=+g[m>>2]*+g[f>>2]-+g[l>>2]*+g[a>>2];g[b>>2]=-(+g[l>>2]*+g[f>>2]+ +g[m>>2]*+g[a>>2]);a=f+8|0;m=l+12|0;k=f+12|0;p=l+8|0;g[e+-8>>2]=+g[m>>2]*+g[a>>2]-+g[p>>2]*+g[k>>2];g[b+4>>2]=-(+g[p>>2]*+g[a>>2]+ +g[m>>2]*+g[k>>2]);k=f+16|0;m=l+20|0;a=f+20|0;p=l+16|0;g[e+-12>>2]=+g[m>>2]*+g[k>>2]-+g[p>>2]*+g[a>>2];e=e+-16|0;g[b+8>>2]=-(+g[p>>2]*+g[k>>2]+ +g[m>>2]*+g[a>>2]);a=f+24|0;m=l+28|0;k=f+28|0;p=l+24|0;g[e>>2]=+g[m>>2]*+g[a>>2]-+g[p>>2]*+g[k>>2];g[b+12>>2]=-(+g[p>>2]*+g[a>>2]+ +g[m>>2]*+g[k>>2]);f=f+32|0;if(f>>>0>=e>>>0)break;else{l=l+32|0;b=b+16|0}}b=d+(h<<2)|0;h=j;d=b;l=b;do{b=d;d=d+-16|0;u=+g[h+-4>>2];g[b+-4>>2]=u;g[l>>2]=-u;u=+g[h+-8>>2];g[b+-8>>2]=u;g[l+4>>2]=-u;u=+g[h+-12>>2];h=h+-16|0;g[b+-12>>2]=u;g[l+8>>2]=-u;u=+g[h>>2];g[d>>2]=u;g[l+12>>2]=-u;l=l+16|0}while(l>>>0<h>>>0);E=j;F=j;while(1){j=F;F=F+-16|0;c[F>>2]=c[E+12>>2];c[j+-12>>2]=c[E+8>>2];c[j+-8>>2]=c[E+4>>2];c[j+-4>>2]=c[E>>2];if(F>>>0<=i>>>0)break;else E=E+16|0}return}function hc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,h=0,i=0.0,j=0,k=0.0,l=0,m=0.0,n=0.0,o=0,p=0.0,q=0,r=0,s=0,t=0;d=(b|0)/4|0;e=ed(d<<2)|0;f=ed(d+b<<2)|0;h=b>>1;i=+(b|0);j=~~+cd(+Y(+i)*1.4426950408889634);c[a+4>>2]=j;c[a>>2]=b;c[a+8>>2]=f;c[a+12>>2]=e;if((b|0)<=3){k=4.0/i;l=a+16|0;g[l>>2]=k;return}m=3.141592653589793/+(b|0);n=3.141592653589793/+(b<<1|0);o=0;do{p=+(o<<2|0)*m;q=o<<1;g[f+(q<<2)>>2]=+Q(+p);r=q|1;g[f+(r<<2)>>2]=-+R(+p);p=+(r|0)*n;r=q+h|0;g[f+(r<<2)>>2]=+Q(+p);g[f+(r+1<<2)>>2]=+R(+p);o=o+1|0}while((o|0)<(d|0));d=(b|0)/8|0;o=(b|0)>7;if(!o){k=4.0/i;l=a+16|0;g[l>>2]=k;return}n=3.141592653589793/+(b|0);h=0;do{m=+(h<<2|2|0)*n;r=(h<<1)+b|0;g[f+(r<<2)>>2]=+Q(+m)*.5;g[f+(r+1<<2)>>2]=+R(+m)*-.5;h=h+1|0}while((h|0)<(d|0));h=(1<<j+-1)+-1|0;f=1<<j+-2;if(o)s=0;else{k=4.0/i;l=a+16|0;g[l>>2]=k;return}do{o=f;j=0;b=0;while(1){r=((o&s|0)==0?0:1<<b)|j;b=b+1|0;o=f>>b;if(!o){t=r;break}else j=r}j=s<<1;c[e+(j<<2)>>2]=(h&~t)+-1;c[e+((j|1)<<2)>>2]=t;s=s+1|0}while((s|0)<(d|0));k=4.0/i;l=a+16|0;g[l>>2]=k;return}function ic(a){a=a|0;var b=0;if(!a)return;b=c[a+8>>2]|0;if(b|0)fd(b);b=c[a+12>>2]|0;if(b|0)fd(b);c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+16>>2]=0;return}function jc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0.0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0.0,I=0.0,J=0.0;c[a>>2]=b;d=gd(b*3|0,4)|0;c[a+4>>2]=d;e=gd(32,4)|0;c[a+8>>2]=e;if((b|0)==1)return;a=d+(b<<2)|0;d=e+8|0;f=-1;h=0;i=b;j=0;a:while(1){k=f+1|0;if((k|0)<4)l=c[34176+(k<<2)>>2]|0;else l=j+2|0;if((l|0)==2){m=h;n=i}else{o=h;p=i;while(1){q=p;p=(p|0)/(l|0)|0;if((q|0)!=(_(p,l)|0)){f=k;h=o;i=q;j=l;continue a}q=o+1|0;c[e+(o+2<<2)>>2]=l;if((p|0)==1){r=q;s=o;t=15;break a}else o=q}}while(1){o=m+1|0;p=n;n=(n|0)/2|0;if((p|0)!=(n<<1|0)){f=k;h=m;i=p;j=l;continue a}c[e+(m+2<<2)>>2]=2;q=(m|0)==0;if(!q){if((m|0)>=1){u=1;do{v=o-u|0;c[e+(v+2<<2)>>2]=c[e+(v+1<<2)>>2];u=u+1|0}while((u|0)!=(o|0))}c[d>>2]=2}if((p&-2|0)==2){w=o;x=q;y=m;break a}else m=o}}if((t|0)==15){w=r;x=(s|0)==0;y=s}c[e>>2]=b;c[e+4>>2]=w;z=6.2831854820251465/+(b|0);if((y|0)>0&(x^1)){A=0;B=0;C=1}else return;while(1){x=c[e+(B+2<<2)>>2]|0;w=C;C=_(x,C)|0;s=(b|0)/(C|0)|0;do if((x|0)>1){r=x+-1|0;t=_(s,r)|0;if((s|0)>2){D=A;E=0;F=0}else{G=t+A|0;break}while(1){F=F+w|0;H=+(F|0)*z;I=0.0;m=D;d=2;while(1){I=I+1.0;J=H*I;g[a+(m<<2)>>2]=+Q(+J);g[a+(m+1<<2)>>2]=+R(+J);d=d+2|0;if((d|0)>=(s|0))break;else m=m+2|0}E=E+1|0;if((E|0)==(r|0))break;else D=D+s|0}G=t+A|0}else G=A;while(0);B=B+1|0;if((B|0)==(y|0))break;else A=G}return}function kc(a){a=a|0;var b=0;if(!a)return;b=c[a+4>>2]|0;if(b|0)fd(b);b=c[a+8>>2]|0;if(b|0)fd(b);c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;return}function lc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;d=b;e=d+112|0;do{c[d>>2]=0;d=d+4|0}while((d|0)<(e|0));c[b+64>>2]=a;c[b+76>>2]=0;c[b+68>>2]=0;if(!(c[a>>2]|0))return 0;a=gd(1,72)|0;c[b+104>>2]=a;g[a+4>>2]=-9999.0;d=b+4|0;b=a+12|0;e=a+40|0;a=0;while(1)if((a|0)!=7){f=gd(1,20)|0;c[b+(a<<2)>>2]=f;Ra(f);f=a+1|0;if((f|0)==15)break;else{a=f;continue}}else{c[e>>2]=d;Ra(d);a=8;continue}return 0}function mc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0;b=a+84|0;d=c[b>>2]|0;if(d|0){e=d;do{d=e;e=c[e+4>>2]|0;fd(c[d>>2]|0);fd(d)}while((e|0)!=0)}e=a+80|0;d=c[e>>2]|0;if(!d){f=a+72|0;c[f>>2]=0;c[b>>2]=0;return}g=a+68|0;h=a+76|0;c[g>>2]=hd(c[g>>2]|0,(c[h>>2]|0)+d|0)|0;c[h>>2]=(c[h>>2]|0)+(c[e>>2]|0);c[e>>2]=0;f=a+72|0;c[f>>2]=0;c[b>>2]=0;return}function nc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0;b=c[a+104>>2]|0;d=a+84|0;e=c[d>>2]|0;if(e|0){f=e;do{e=f;f=c[f+4>>2]|0;fd(c[e>>2]|0);fd(e)}while((f|0)!=0)}f=a+80|0;e=c[f>>2]|0;g=a+68|0;h=c[g>>2]|0;if(!e)i=h;else{j=a+76|0;k=hd(h,(c[j>>2]|0)+e|0)|0;c[g>>2]=k;c[j>>2]=(c[j>>2]|0)+(c[f>>2]|0);c[f>>2]=0;i=k}c[a+72>>2]=0;c[d>>2]=0;if(i|0)fd(i);if(!b){l=a;m=l+112|0;do{c[l>>2]=0;l=l+4|0}while((l|0)<(m|0));return 0}else n=0;while(1){i=b+12+(n<<2)|0;Ta(c[i>>2]|0);if((n|0)==7){n=8;continue}fd(c[i>>2]|0);n=n+1|0;if((n|0)==15)break}fd(b);l=a;m=l+112|0;do{c[l>>2]=0;l=l+4|0}while((l|0)<(m|0));return 0}function oc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;e=c[b+28>>2]|0;if(!e){f=1;return f|0}g=c[e+3656>>2]|0;h=a;i=h+112|0;do{c[h>>2]=0;h=h+4|0}while((h|0)<(i|0));h=gd(1,136)|0;c[a+104>>2]=h;c[a+4>>2]=b;i=c[e+8>>2]|0;j=i+-1|0;if((i|0)==0|(j|0)==0)k=0;else{i=j;j=0;while(1){l=j+1|0;i=i>>>1;if(!i){k=l;break}else j=l}}c[h+44>>2]=k;k=gd(1,4)|0;c[h+12>>2]=k;j=gd(1,4)|0;i=h+16|0;c[i>>2]=j;l=gd(1,20)|0;c[k>>2]=l;c[j>>2]=gd(1,20)|0;hc(l,c[e>>2]>>g);l=e+4|0;hc(c[c[i>>2]>>2]|0,c[l>>2]>>g);g=c[e>>2]|0;i=g+-1|0;if((g|0)==0|(i|0)==0)m=0;else{j=i;i=0;while(1){k=i+1|0;j=j>>>1;if(!j){m=k;break}else i=k}}c[h+4>>2]=m+-6;m=c[l>>2]|0;i=m+-1|0;if((m|0)==0|(i|0)==0)n=0;else{m=i;i=0;while(1){j=i+1|0;m=m>>>1;if(!m){n=j;break}else i=j}}c[h+8>>2]=n+-6;a:do if(!d){n=e+2848|0;if((c[n>>2]|0)==0?(i=e+24|0,c[n>>2]=gd(c[i>>2]|0,56)|0,m=c[i>>2]|0,(m|0)>0):0){j=m;m=0;while(1){k=e+1824+(m<<2)|0;o=c[k>>2]|0;if(!o){p=j;break}if(tc((c[n>>2]|0)+(m*56|0)|0,o)|0){q=23;break}wc(c[k>>2]|0);c[k>>2]=0;m=m+1|0;j=c[i>>2]|0;if((m|0)>=(j|0))break a}if((q|0)==23)p=c[i>>2]|0;if((p|0)>0){j=p;m=0;while(1){n=e+1824+(m<<2)|0;k=c[n>>2]|0;if(!k)r=j;else{wc(k);c[n>>2]=0;r=c[i>>2]|0}m=m+1|0;if((m|0)>=(r|0))break;else j=r}}xc(a);f=-1;return f|0}}else{jc(h+20|0,g);jc(h+32|0,c[l>>2]|0);j=e+2848|0;if(((c[j>>2]|0)==0?(m=e+24|0,i=gd(c[m>>2]|0,56)|0,c[j>>2]=i,(c[m>>2]|0)>0):0)?(pc(i,c[e+1824>>2]|0)|0,(c[m>>2]|0)>1):0){i=1;do{pc((c[j>>2]|0)+(i*56|0)|0,c[e+1824+(i<<2)>>2]|0)|0;i=i+1|0}while((i|0)<(c[m>>2]|0))}m=e+28|0;i=gd(c[m>>2]|0,52)|0;j=h+56|0;c[j>>2]=i;b:do if((c[m>>2]|0)>0){n=e+2868|0;k=b+8|0;o=i;s=0;while(1){t=c[e+2852+(s<<2)>>2]|0;rc(o+(s*52|0)|0,t,n,(c[e+(c[t>>2]<<2)>>2]|0)/2|0,c[k>>2]|0);t=s+1|0;if((t|0)>=(c[m>>2]|0))break b;o=c[j>>2]|0;s=t}}while(0);c[a>>2]=1}while(0);g=c[l>>2]|0;c[a+16>>2]=g;r=c[b+4>>2]|0;b=r<<2;p=ed(b)|0;q=a+8|0;c[q>>2]=p;c[a+12>>2]=ed(b)|0;if((r|0)>0?(c[p>>2]=gd(g,4)|0,(r|0)>1):0){p=1;do{b=c[q>>2]|0;c[b+(p<<2)>>2]=gd(g,4)|0;p=p+1|0}while((p|0)<(r|0))}c[a+36>>2]=0;c[a+40>>2]=0;r=(c[l>>2]|0)/2|0;c[a+48>>2]=r;c[a+20>>2]=r;r=e+16|0;l=h+48|0;c[l>>2]=gd(c[r>>2]|0,4)|0;p=e+20|0;g=h+52|0;c[g>>2]=gd(c[p>>2]|0,4)|0;if((c[r>>2]|0)>0){h=0;do{q=Ga[c[(c[34164+(c[e+800+(h<<2)>>2]<<2)>>2]|0)+8>>2]&15](a,c[e+1056+(h<<2)>>2]|0)|0;c[(c[l>>2]|0)+(h<<2)>>2]=q;h=h+1|0}while((h|0)<(c[r>>2]|0))}if((c[p>>2]|0)>0)u=0;else{f=0;return f|0}do{r=Ga[c[(c[34152+(c[e+1312+(u<<2)>>2]<<2)>>2]|0)+8>>2]&15](a,c[e+1568+(u<<2)>>2]|0)|0;c[(c[g>>2]|0)+(u<<2)>>2]=r;u=u+1|0}while((u|0)<(c[p>>2]|0));f=0;return f|0}function pc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0.0;d=a;e=d+56|0;do{c[d>>2]=0;d=d+4|0}while((d|0)<(e|0));c[a+12>>2]=b;d=b+4|0;e=c[d>>2]|0;c[a+4>>2]=e;c[a+8>>2]=e;c[a>>2]=c[b>>2];c[a+20>>2]=qc(c[b+8>>2]|0,e,0)|0;e=c[d>>2]|0;d=c[b>>2]|0;if((d|0)<=0)while(1){}f=~~+M(+(+P(+(+(e|0)),+(1.0/+(d|0)))));while(1){g=f+1|0;h=1;i=1;j=0;while(1){k=_(h,f)|0;l=_(i,g)|0;j=j+1|0;if((j|0)==(d|0)){m=k;n=l;break}else{h=k;i=l}}if((n|0)>(e|0)&(m|0)<=(e|0)){o=f;break}f=((m|0)>(e|0)?-1:1)+f|0}c[a+44>>2]=o;o=c[b+16>>2]|0;p=+(o&2097151|0);c[a+48>>2]=~~+dd(+bd((o|0)<0?-p:p,(o>>>21&1023)+-788|0));o=c[b+20>>2]|0;p=+(o&2097151|0);c[a+52>>2]=~~+dd(+bd((o|0)<0?-p:p,(o>>>21&1023)+-788|0));return 0}function qc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0;e=i;i=i+144|0;f=e;g=(d|0)!=0;h=ed((g?d:b)<<2)|0;md(f|0,0,132)|0;j=(b|0)>0;a:do if(j){k=f+4|0;l=(d|0)==0&1;m=0;n=0;b:while(1){o=c[a+(n<<2)>>2]|0;c:do if((o|0)>0){p=c[f+(o<<2)>>2]|0;if(!((o|0)>31|(p>>>o|0)==0))break b;q=m+1|0;c[h+(m<<2)>>2]=p;r=f+(o<<2)|0;d:do if(!(p&1)){s=p;t=r;u=o;while(1){c[t>>2]=s+1;v=u+-1|0;if((u|0)<=1)break d;s=c[f+(v<<2)>>2]|0;w=f+(v<<2)|0;if(s&1|0){x=w;y=v;z=7;break}else{t=w;u=v}}}else{x=r;y=o;z=7}while(0);do if((z|0)==7){z=0;if((y|0)==1){c[k>>2]=(c[k>>2]|0)+1;break}else{c[x>>2]=c[f+(y+-1<<2)>>2]<<1;break}}while(0);r=o+1|0;if((r|0)<33){u=p;t=o;s=r;while(1){r=f+(s<<2)|0;v=u;u=c[r>>2]|0;if((u>>>1|0)!=(v|0)){A=q;break c}c[r>>2]=c[f+(t<<2)>>2]<<1;r=s+1|0;if((r|0)>=33){A=q;break}else{v=s;s=r;t=v}}}else A=q}else A=m+l|0;while(0);n=n+1|0;if((n|0)>=(b|0))break a;else m=A}fd(h);B=0;i=e;return B|0}while(0);e:do if((d|0)!=1){A=1;while(1){if(c[f+(A<<2)>>2]&-1>>>(32-A|0)|0)break;A=A+1|0;if((A|0)>=33)break e}fd(h);B=0;i=e;return B|0}while(0);if(!j){B=h;i=e;return B|0}if(g){C=0;D=0}else{g=0;do{j=c[a+(g<<2)>>2]|0;f=h+(g<<2)|0;if((j|0)>0){d=c[f>>2]|0;A=0;y=0;while(1){x=d>>>A&1|y<<1;A=A+1|0;if((A|0)>=(j|0)){E=x;break}else y=x}}else E=0;g=g+1|0;c[f>>2]=E}while((g|0)!=(b|0));B=h;i=e;return B|0}while(1){g=c[a+(D<<2)>>2]|0;if((g|0)>0){E=c[h+(C<<2)>>2]|0;y=0;j=0;while(1){A=E>>>y&1|j<<1;y=y+1|0;if((y|0)>=(g|0)){F=A;break}else j=A}}else F=0;if(!g)G=C;else{c[h+(C<<2)>>2]=F;G=C+1|0}D=D+1|0;if((D|0)==(b|0)){B=h;break}else C=G}i=e;return B|0}function rc(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var h=0,i=0,j=0.0,k=0.0,l=0.0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0.0,A=0.0,B=0.0,C=0,D=0,E=0,F=0.0,G=0;h=a;i=h+48|0;do{c[h>>2]=0;h=h+4|0}while((h|0)<(i|0));h=c[d>>2]|0;c[a+36>>2]=h;d=~~(+cd(+Y(+(+(h|0)*8.0))*1.4426950408889634)+-1.0);i=a+32|0;c[i>>2]=d;j=+(f|0);k=+(e|0);l=+(1<<d+1|0);d=~~(l*(+Y(+(j*.25*.5/k))*1.4426950216293335+-5.965784072875977)-+(h|0));c[a+28>>2]=d;c[a+40>>2]=1-d+~~(l*(+Y(+((+(e|0)+.25)*j*.5/k))*1.4426950216293335+-5.965784072875977)+.5);d=e<<2;h=a+16|0;c[h>>2]=ed(d)|0;m=a+20|0;c[m>>2]=ed(d)|0;n=a+24|0;c[n>>2]=ed(d)|0;o=a+4|0;c[o>>2]=b;c[a>>2]=e;c[a+44>>2]=f;p=a+48|0;g[p>>2]=1.0;do if((f|0)>=26e3){if((f|0)<38e3){g[p>>2]=.9399999976158142;break}if((f|0)>46e3)g[p>>2]=1.274999976158142}else g[p>>2]=0.0;while(0);j=k*2.0;l=+(f|0);p=0;q=0;a:while(1){r=(q|0)>=(e|0);s=p;while(1){if((s|0)>=87){t=q;break a}u=s+1|0;v=~~+cd(j*+X(+(+(u|0)*.08664337545633316+2.7488713472395148))/l);if((v|0)<=(q|0)|r)s=u;else{w=u;x=v;y=s;break}}z=+g[34192+(y<<2)>>2];A=(+g[34192+(w<<2)>>2]-z)/+(x-q|0);s=c[h>>2]|0;B=z;r=q;while(1){g[s+(r<<2)>>2]=B+100.0;v=r+1|0;if((v|0)<(x|0)&(v|0)<(e|0)){B=B+A;r=v}else{p=w;q=v;continue a}}}if((t|0)<(e|0)){q=c[h>>2]|0;h=t;do{c[q+(h<<2)>>2]=c[q+(h+-1<<2)>>2];h=h+1|0}while((h|0)!=(e|0))}h=(e|0)>0;if(h){q=(f|0)/(e<<1|0)|0;f=b+120|0;t=c[f>>2]|0;w=c[n>>2]|0;n=b+124|0;p=b+116|0;x=b+112|0;y=1;r=0;s=-99;while(1){v=_(q,r)|0;A=+(v|0);B=+V(+(+(_(v,v)|0)*1.8499999754340024e-08))*2.240000009536743+ +V(+(A*7.399999885819852e-04))*13.100000381469727+A*9.999999747378752e-05;b:do if((t+s|0)<(r|0)){A=B-+g[x>>2];v=s;while(1){u=_(v,q)|0;z=+(u|0);if(!(+V(+(z*7.399999885819852e-04))*13.100000381469727+z*9.999999747378752e-05+ +V(+(+(_(u,u)|0)*1.8499999754340024e-08))*2.240000009536743<A)){C=v;break b}u=v+1|0;if(((c[f>>2]|0)+u|0)<(r|0))v=u;else{C=u;break}}}else C=s;while(0);c:do if((y|0)>(e|0))D=y;else{v=(c[n>>2]|0)+r|0;u=y;while(1){if((u|0)>=(v|0)?(E=_(u,q)|0,A=+(E|0),z=+V(+(A*7.399999885819852e-04))*13.100000381469727+A*9.999999747378752e-05+ +V(+(+(_(E,E)|0)*1.8499999754340024e-08))*2.240000009536743,!(z<+g[p>>2]+B)):0){D=u;break c}E=u+1|0;if((u|0)<(e|0))u=E;else{D=E;break}}}while(0);c[w+(r<<2)>>2]=(C<<16)+-65537+D;r=r+1|0;if((r|0)==(e|0))break;else{y=D;s=C}}if(h){B=l*.5;C=c[m>>2]|0;m=0;do{z=+Y(+(B*(+(m|0)+.25)/k))*1.4426950216293335+-5.965784072875977;c[C+(m<<2)>>2]=~~(+(1<<(c[i>>2]|0)+1|0)*z+.5);m=m+1|0}while((m|0)!=(e|0));F=B}else G=19}else G=19;if((G|0)==19)F=l*.5;c[a+8>>2]=sc(b+36|0,F/k,e,+g[b+24>>2],+g[b+28>>2])|0;b=ed(12)|0;c[a+12>>2]=b;c[b>>2]=ed(d)|0;c[b+4>>2]=ed(d)|0;c[b+8>>2]=ed(d)|0;if(!h)return;h=c[o>>2]|0;o=c[b>>2]|0;d=c[b+4>>2]|0;a=c[b+8>>2]|0;b=0;do{k=+Y(+((+(b|0)+.5)*l/j))*2.885390043258667+-11.931568145751953;F=k<0.0?0.0:k;k=F>=16.0?16.0:F;G=~~k;F=k-+(G|0);k=1.0-F;m=G+1|0;g[o+(b<<2)>>2]=+g[h+132+(m<<2)>>2]*F+ +g[h+132+(G<<2)>>2]*k;g[d+(b<<2)>>2]=+g[h+200+(m<<2)>>2]*F+ +g[h+200+(G<<2)>>2]*k;g[a+(b<<2)>>2]=+g[h+268+(m<<2)>>2]*F+ +g[h+268+(G<<2)>>2]*k;b=b+1|0}while((b|0)!=(e|0));return}function sc(a,b,d,e,f){a=a|0;b=+b;d=d|0;e=+e;f=+f;var h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0.0,v=0,w=0.0,x=0.0,y=0.0,z=0.0,A=0.0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0.0,N=0;h=i;i=i+32480|0;j=h+32256|0;k=h+1792|0;l=h;m=i;i=i+((1*(d<<2)|0)+15&-16)|0;n=ed(68)|0;md(k|0,0,30464)|0;o=e>0.0;p=e<0.0;q=0;do{r=q<<2;s=0;do{t=s+r|0;if((t|0)<88)u=+g[34192+(t<<2)>>2];else u=-30.0;v=t+1|0;if((v|0)<88){w=+g[34192+(v<<2)>>2];if(u>w)x=w;else x=u}else if(u>-30.0)x=-30.0;else x=u;v=t+2|0;if((v|0)<88){w=+g[34192+(v<<2)>>2];if(x>w)y=w;else y=x}else if(x>-30.0)y=-30.0;else y=x;v=t+3|0;if((v|0)<88){w=+g[34192+(v<<2)>>2];if(y>w)z=w;else z=y}else if(y>-30.0)z=-30.0;else z=y;g[j+(s<<2)>>2]=z;s=s+1|0}while((s|0)!=56);s=34544+(q*1344|0)|0;od(k+(q*1792|0)+448|0,s|0,224)|0;od(k+(q*1792|0)+672|0,34544+(q*1344|0)+224|0,224)|0;od(k+(q*1792|0)+896|0,34544+(q*1344|0)+448|0,224)|0;od(k+(q*1792|0)+1120|0,34544+(q*1344|0)+672|0,224)|0;od(k+(q*1792|0)+1344|0,34544+(q*1344|0)+896|0,224)|0;od(k+(q*1792|0)+1568|0,34544+(q*1344|0)+1120|0,224)|0;od(k+(q*1792|0)|0,s|0,224)|0;od(k+(q*1792|0)+224|0,s|0,224)|0;if(o){s=0;do{if(p){r=0;do{v=16-r|0;w=+(((v|0)>-1?v:0-v|0)|0)*f+e;A=w<0.0?0.0:w;v=k+(q*1792|0)+(s*224|0)+(r<<2)|0;g[v>>2]=+g[v>>2]+(A>0.0?0.0:A);r=r+1|0}while((r|0)!=56)}else{r=0;do{v=16-r|0;A=+(((v|0)>-1?v:0-v|0)|0)*f+e;v=k+(q*1792|0)+(s*224|0)+(r<<2)|0;g[v>>2]=+g[v>>2]+(A<0.0?0.0:A);r=r+1|0}while((r|0)!=56)}s=s+1|0}while((s|0)!=8)}else{s=0;do{if(p){r=0;do{v=16-r|0;A=+(((v|0)>-1?v:0-v|0)|0)*f+e;v=k+(q*1792|0)+(s*224|0)+(r<<2)|0;g[v>>2]=+g[v>>2]+(A>0.0?0.0:A);r=r+1|0}while((r|0)!=56)}else{r=0;do{v=16-r|0;t=k+(q*1792|0)+(s*224|0)+(r<<2)|0;g[t>>2]=+g[t>>2]+(+(((v|0)>-1?v:0-v|0)|0)*f+e);r=r+1|0}while((r|0)!=56)}s=s+1|0}while((s|0)!=8)}A=+g[a+(q<<2)>>2];s=0;do{w=+(((s|0)<2?2:s)|0)*-10.0+70.0+A;r=0;do{v=k+(q*1792|0)+(s*224|0)+(r<<2)|0;g[v>>2]=+g[v>>2]+w;r=r+1|0}while((r|0)!=56);od(l+(s*224|0)|0,j|0,224)|0;w=+(s|0)*-10.0+70.0;r=0;do{v=l+(s*224|0)+(r<<2)|0;g[v>>2]=w+ +g[v>>2];r=r+1|0}while((r|0)!=56);B=0;do{w=+g[k+(q*1792|0)+(s*224|0)+(B<<2)>>2];r=l+(s*224|0)+(B<<2)|0;if(w>+g[r>>2])g[r>>2]=w;B=B+1|0}while((B|0)!=56);s=s+1|0}while((s|0)!=8);C=1;do{s=C+-1|0;r=0;do{A=+g[l+(s*224|0)+(r<<2)>>2];v=l+(C*224|0)+(r<<2)|0;if(A<+g[v>>2])g[v>>2]=A;r=r+1|0}while((r|0)!=56);D=0;do{A=+g[l+(C*224|0)+(D<<2)>>2];r=k+(q*1792|0)+(C*224|0)+(D<<2)|0;if(A<+g[r>>2])g[r>>2]=A;D=D+1|0}while((D|0)!=56);C=C+1|0}while((C|0)!=8);q=q+1|0}while((q|0)!=17);e=b;q=(d|0)>0;C=0;do{D=ed(32)|0;c[n+(C<<2)>>2]=D;f=+(C|0);z=f*.5;l=~~+M(+(+X(+(f*.34657350182533264+4.135165354540845))/e));B=~~+Z(+(+Y(+(+(l|0)*b+1.0))*2.885390043258667+-11.931568145751953));j=~~+M(+(+Y(+(+(l+1|0)*b))*2.885390043258667+-11.931568145751953));l=(B|0)>(C|0)?C:B;B=(l|0)<0?0:l;l=(j|0)>16?16:j;j=(B|0)>(l|0);C=C+1|0;a=(C|0)<17;f=z+3.9657840728759766;p=0;do{o=D+(p<<2)|0;c[o>>2]=ed(232)|0;if(q){r=0;do{g[m+(r<<2)>>2]=999.0;r=r+1|0}while((r|0)!=(d|0))}if(!j){r=B;while(1){y=+(r|0)*.5;s=0;v=0;while(1){x=+(s|0)*.125+y;t=~~(+X(+((x+3.9032840728759766)*.6931470036506653))/e);E=~~(+X(+((x+4.028284072875977)*.6931470036506653))/e+1.0);F=(t|0)<0?0:t;t=(F|0)>(d|0)?d:F;F=(t|0)<(v|0)?t:v;t=(E|0)<0?0:E;E=(t|0)>(d|0)?d:t;if((F|0)<(E|0)&(F|0)<(d|0)){x=+g[k+(r*1792|0)+(p*224|0)+(s<<2)>>2];t=F;while(1){G=m+(t<<2)|0;if(+g[G>>2]>x)g[G>>2]=x;G=t+1|0;if((G|0)<(E|0)&(G|0)<(d|0))t=G;else{H=G;break}}}else H=F;s=s+1|0;if((s|0)==56){I=H;break}else v=H}if((I|0)<(d|0)){y=+g[k+(r*1792|0)+(p*224|0)+220>>2];v=I;do{s=m+(v<<2)|0;if(+g[s>>2]>y)g[s>>2]=y;v=v+1|0}while((v|0)!=(d|0))}if((r|0)<(l|0))r=r+1|0;else break}}if(a){r=0;v=0;while(1){y=+(r|0)*.125+z;s=~~(+X(+((y+3.9032840728759766)*.6931470036506653))/e);t=~~(+X(+((y+4.028284072875977)*.6931470036506653))/e+1.0);E=(s|0)<0?0:s;s=(E|0)>(d|0)?d:E;E=(s|0)<(v|0)?s:v;s=(t|0)<0?0:t;t=(s|0)>(d|0)?d:s;if((E|0)<(t|0)&(E|0)<(d|0)){y=+g[k+(C*1792|0)+(p*224|0)+(r<<2)>>2];s=E;while(1){G=m+(s<<2)|0;if(+g[G>>2]>y)g[G>>2]=y;G=s+1|0;if((G|0)<(t|0)&(G|0)<(d|0))s=G;else{J=G;break}}}else J=E;r=r+1|0;if((r|0)==56){K=J;break}else v=J}if((K|0)<(d|0)){y=+g[k+(C*1792|0)+(p*224|0)+220>>2];v=K;do{r=m+(v<<2)|0;if(+g[r>>2]>y)g[r>>2]=y;v=v+1|0}while((v|0)!=(d|0))}}v=D+(p<<2)|0;r=D+(p<<2)|0;s=D+(p<<2)|0;t=0;do{G=~~(+X(+((f+ +(t|0)*.125)*.6931470036506653))/e);do if((G|0)>=0)if((G|0)<(d|0)){c[(c[r>>2]|0)+(t+2<<2)>>2]=c[m+(G<<2)>>2];break}else{g[(c[s>>2]|0)+(t+2<<2)>>2]=-999.0;break}else g[(c[v>>2]|0)+(t+2<<2)>>2]=-999.0;while(0);t=t+1|0}while((t|0)!=56);t=c[o>>2]|0;do if(!(+g[t+8>>2]>-200.0))if(!(+g[t+12>>2]>-200.0))if(!(+g[t+16>>2]>-200.0))if(!(+g[t+20>>2]>-200.0))if(!(+g[t+24>>2]>-200.0))if(!(+g[t+28>>2]>-200.0))if(!(+g[t+32>>2]>-200.0))if(!(+g[t+36>>2]>-200.0))if(!(+g[t+40>>2]>-200.0))if(!(+g[t+44>>2]>-200.0))if(!(+g[t+48>>2]>-200.0))if(!(+g[t+52>>2]>-200.0))if(!(+g[t+56>>2]>-200.0))if(+g[t+60>>2]>-200.0)L=13.0;else{if(+g[t+64>>2]>-200.0){L=14.0;break}if(+g[t+68>>2]>-200.0){L=15.0;break}L=16.0}else L=12.0;else L=11.0;else L=10.0;else L=9.0;else L=8.0;else L=7.0;else L=6.0;else L=5.0;else L=4.0;else L=3.0;else L=2.0;else L=1.0;else L=0.0;while(0);g[t>>2]=L;v=c[o>>2]|0;s=55;while(1){if(+g[v+(s+2<<2)>>2]>-200.0){N=s;break}r=s+-1|0;if((r|0)>17)s=r;else{N=r;break}}g[v+4>>2]=+(N|0);p=p+1|0}while((p|0)!=8)}while((C|0)!=17);i=h;return n|0}function tc(b,d){b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0;e=i;f=b;g=f+56|0;do{c[f>>2]=0;f=f+4|0}while((f|0)<(g|0));h=d+4|0;j=c[h>>2]|0;if((j|0)>0){k=c[d+8>>2]|0;l=0;m=0;while(1){n=((c[k+(l<<2)>>2]|0)>0&1)+m|0;l=l+1|0;if((l|0)>=(j|0)){o=n;break}else m=n}}else o=0;c[b+4>>2]=j;m=b+8|0;c[m>>2]=o;c[b>>2]=c[d>>2];if((o|0)<=0){p=0;i=e;return p|0}l=d+8|0;k=qc(c[l>>2]|0,j,o)|0;j=o<<2;n=i;i=i+((1*j|0)+15&-16)|0;if(!k){q=c[b+16>>2]|0;if(q|0)fd(q);q=c[b+20>>2]|0;if(q|0)fd(q);q=c[b+24>>2]|0;if(q|0)fd(q);q=c[b+28>>2]|0;if(q|0)fd(q);q=c[b+32>>2]|0;if(q|0)fd(q);f=b;g=f+56|0;do{c[f>>2]=0;f=f+4|0}while((f|0)<(g|0));p=-1;i=e;return p|0}else r=0;do{f=k+(r<<2)|0;g=qd(c[f>>2]|0)|0;q=g>>>4&252645135|g<<4&-252645136;g=q>>>2&858993459|q<<2&-858993460;c[f>>2]=g>>>1&1431655765|g<<1&-1431655766;c[n+(r<<2)>>2]=f;r=r+1|0}while((r|0)!=(o|0));Yc(n,o,4,13);r=i;i=i+((1*j|0)+15&-16)|0;f=ed(j)|0;g=b+20|0;c[g>>2]=f;q=k;s=0;do{c[r+((c[n+(s<<2)>>2]|0)-q>>2<<2)>>2]=s;s=s+1|0}while((s|0)!=(o|0));t=0;do{c[f+(c[r+(t<<2)>>2]<<2)>>2]=c[k+(t<<2)>>2];t=t+1|0}while((t|0)!=(o|0));fd(k);c[b+16>>2]=vc(d,o,r)|0;o=ed(j)|0;c[b+24>>2]=o;j=c[h>>2]|0;d=(j|0)>0;if(d){k=c[l>>2]|0;t=0;f=0;while(1){if((c[k+(t<<2)>>2]|0)>0){c[o+(c[r+(f<<2)>>2]<<2)>>2]=t;u=f+1|0}else u=f;t=t+1|0;if((t|0)>=(j|0)){v=u;break}else f=u}u=b+28|0;c[u>>2]=ed(v)|0;if(d){d=j;j=0;v=0;while(1){f=c[(c[l>>2]|0)+(j<<2)>>2]|0;if((f|0)>0){a[(c[u>>2]|0)+(c[r+(v<<2)>>2]|0)>>0]=f;w=c[h>>2]|0;x=v+1|0}else{w=d;x=v}j=j+1|0;if((j|0)>=(w|0)){y=u;z=x;break}else{d=w;v=x}}}else{y=u;z=0}}else{u=b+28|0;c[u>>2]=ed(0)|0;y=u;z=0}u=c[m>>2]|0;if(!u)A=-4;else{m=u;u=0;while(1){m=m>>>1;if(!m){B=u;break}else u=u+1|0}A=B+-3|0}B=b+36|0;u=(A|0)<5?5:A;A=(u|0)>8?8:u;c[B>>2]=A;u=1<<A;m=gd(u,4)|0;x=b+32|0;c[x>>2]=m;v=b+40|0;c[v>>2]=0;a:do if((z|0)>0){b=c[y>>2]|0;w=0;d=A;j=0;while(1){h=b+j|0;r=a[h>>0]|0;l=r<<24>>24;if((w|0)<(l|0)){c[v>>2]=l;C=a[h>>0]|0}else C=r;r=C<<24>>24;if((d|0)>=(r|0)?(l=qd(c[(c[g>>2]|0)+(j<<2)>>2]|0)|0,f=l>>>4&252645135|l<<4&-252645136,l=f>>>2&858993459|f<<2&-858993460,f=l>>>1&1431655765|l<<1&-1431655766,(d-r|0)!=31):0){l=j+1|0;t=r;r=0;do{c[m+((f|r<<t)<<2)>>2]=l;r=r+1|0;o=c[B>>2]|0;t=a[h>>0]|0}while((r|0)<(1<<o-t|0));D=o}else D=d;t=j+1|0;if((t|0)==(z|0)){E=D;break a}w=c[v>>2]|0;d=D;j=t}}else E=A;while(0);D=-2<<31-E;if((A|0)==31){p=0;i=e;return p|0}A=c[x>>2]|0;v=E;E=0;m=0;C=0;while(1){y=m<<32-v;j=qd(y|0)|0;d=j>>>4&252645135|j<<4&-252645136;j=d>>>2&858993459|d<<2&-858993460;d=j>>>1&1431655765|j<<1&-1431655766;if(!(c[A+(d<<2)>>2]|0)){j=C;while(1){w=j+1|0;if((w|0)>=(z|0)){F=j;break}if((c[(c[g>>2]|0)+(w<<2)>>2]|0)>>>0>y>>>0){F=j;break}else j=w}b:do if((z|0)>(E|0)){j=c[g>>2]|0;w=E;while(1){if(y>>>0<(c[j+(w<<2)>>2]&D)>>>0){G=w;break b}b=w+1|0;if((z|0)>(b|0))w=b;else{G=b;break}}}else G=E;while(0);y=z-G|0;c[(c[x>>2]|0)+(d<<2)>>2]=(F>>>0>32767?32767:F)<<15|(y>>>0>32767?32767:y)|-2147483648;H=G;I=F}else{H=E;I=C}y=m+1|0;if((y|0)>=(u|0)){p=0;break}v=c[B>>2]|0;E=H;m=y;C=I}i=e;return p|0}function uc(a,b){a=a|0;b=b|0;var d=0;d=c[c[a>>2]>>2]|0;a=c[c[b>>2]>>2]|0;return (d>>>0>a>>>0&1)-(d>>>0<a>>>0&1)|0}function vc(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,h=0,i=0.0,j=0.0,k=0.0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0.0,w=0,x=0,y=0.0,z=0,A=0,B=0.0,C=0;e=c[a+12>>2]|0;if((e+-1|0)>>>0>=2){f=0;return f|0}h=c[a+16>>2]|0;i=+(h&2097151|0);j=+bd((h|0)<0?-i:i,(h>>>21&1023)+-788|0);h=c[a+20>>2]|0;i=+(h&2097151|0);k=+bd((h|0)<0?-i:i,(h>>>21&1023)+-788|0);h=c[a>>2]|0;l=gd(_(h,b)|0,4)|0;switch(e|0){case 1:{e=c[a+4>>2]|0;if((h|0)<=0)while(1){}b=~~+M(+(+P(+(+(e|0)),+(1.0/+(h|0)))));while(1){m=b+1|0;n=1;o=1;p=0;while(1){q=_(n,b)|0;r=_(o,m)|0;p=p+1|0;if((p|0)==(h|0)){s=q;t=r;break}else{n=q;o=r}}if((t|0)>(e|0)&(s|0)<=(e|0)){u=b;break}b=((s|0)>(e|0)?-1:1)+b|0}if((e|0)<=0){f=l;return f|0}b=(d|0)==0;s=a+8|0;t=a+32|0;i=k;v=j;o=a+28|0;n=0;p=0;while(1){if(b){m=c[t>>2]|0;r=_(h,n)|0;if(!(c[o>>2]|0)){q=1;w=0;do{g[l+(r+w<<2)>>2]=v+ +N(+(+(c[m+((((p|0)/(q|0)|0|0)%(u|0)|0)<<2)>>2]|0)))*i;q=_(q,u)|0;w=w+1|0}while((w|0)<(h|0));x=21}else{w=1;q=0;y=0.0;do{y=y+v+ +N(+(+(c[m+((((p|0)/(w|0)|0|0)%(u|0)|0)<<2)>>2]|0)))*i;g[l+(r+q<<2)>>2]=y;w=_(w,u)|0;q=q+1|0}while((q|0)<(h|0));x=21}}else if(!(c[(c[s>>2]|0)+(p<<2)>>2]|0))z=n;else{q=c[t>>2]|0;w=(c[o>>2]|0)==0;r=_(c[d+(n<<2)>>2]|0,h)|0;m=1;A=0;y=0.0;while(1){B=y+v+ +N(+(+(c[q+((((p|0)/(m|0)|0|0)%(u|0)|0)<<2)>>2]|0)))*i;g[l+(r+A<<2)>>2]=B;m=_(m,u)|0;A=A+1|0;if((A|0)>=(h|0)){x=21;break}else y=w?y:B}}if((x|0)==21){x=0;z=n+1|0}p=p+1|0;if((p|0)>=(e|0)){f=l;break}else n=z}return f|0}case 2:{z=c[a+4>>2]|0;if((z|0)<=0){f=l;return f|0}n=(d|0)!=0;e=a+8|0;p=a+32|0;i=k;k=j;x=a+28|0;a=(h|0)>0;u=0;o=0;while(1){if(n?(c[(c[e>>2]|0)+(o<<2)>>2]|0)==0:0)C=u;else{if(a){t=c[p>>2]|0;s=(c[x>>2]|0)==0;if(n){b=_(h,o)|0;w=_(c[d+(u<<2)>>2]|0,h)|0;if(s){A=0;do{g[l+(w+A<<2)>>2]=k+ +N(+(+(c[t+(b+A<<2)>>2]|0)))*i;A=A+1|0}while((A|0)<(h|0))}else{A=0;j=0.0;do{j=j+k+ +N(+(+(c[t+(b+A<<2)>>2]|0)))*i;g[l+(w+A<<2)>>2]=j;A=A+1|0}while((A|0)<(h|0))}}else{A=_(h,o)|0;w=_(h,u)|0;if(s){b=0;do{g[l+(w+b<<2)>>2]=k+ +N(+(+(c[t+(A+b<<2)>>2]|0)))*i;b=b+1|0}while((b|0)<(h|0))}else{b=0;j=0.0;do{j=j+k+ +N(+(+(c[t+(A+b<<2)>>2]|0)))*i;g[l+(w+b<<2)>>2]=j;b=b+1|0}while((b|0)<(h|0))}}}C=u+1|0}o=o+1|0;if((o|0)>=(z|0)){f=l;break}else u=C}return f|0}default:{f=l;return f|0}}return 0}function wc(a){a=a|0;var b=0;if(!(c[a+36>>2]|0))return;b=c[a+32>>2]|0;if(b|0)fd(b);b=c[a+8>>2]|0;if(b|0)fd(b);fd(a);return}function xc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;if(!a)return;b=c[a+4>>2]|0;d=(b|0)!=0;if(d)e=c[b+28>>2]|0;else e=0;f=c[a+104>>2]|0;g=(f|0)!=0;if(g){h=c[f>>2]|0;if(h|0){yc(h);fd(c[f>>2]|0)}h=f+12|0;i=c[h>>2]|0;if(i|0){ic(c[i>>2]|0);fd(c[c[h>>2]>>2]|0);fd(c[h>>2]|0)}h=f+16|0;i=c[h>>2]|0;if(i|0){ic(c[i>>2]|0);fd(c[c[h>>2]>>2]|0);fd(c[h>>2]|0)}h=f+48|0;i=c[h>>2]|0;if(i|0){if((e|0)!=0?(j=e+16|0,(c[j>>2]|0)>0):0){k=e+800|0;Ba[c[(c[34164+(c[k>>2]<<2)>>2]|0)+16>>2]&7](c[i>>2]|0);if((c[j>>2]|0)>1){l=1;do{Ba[c[(c[34164+(c[k+(l<<2)>>2]<<2)>>2]|0)+16>>2]&7](c[(c[h>>2]|0)+(l<<2)>>2]|0);l=l+1|0}while((l|0)<(c[j>>2]|0))}m=c[h>>2]|0}else m=i;fd(m)}m=f+52|0;i=c[m>>2]|0;if(i|0){if((e|0)!=0?(h=e+20|0,(c[h>>2]|0)>0):0){j=e+1312|0;Ba[c[(c[34152+(c[j>>2]<<2)>>2]|0)+16>>2]&7](c[i>>2]|0);if((c[h>>2]|0)>1){l=1;do{Ba[c[(c[34152+(c[j+(l<<2)>>2]<<2)>>2]|0)+16>>2]&7](c[(c[m>>2]|0)+(l<<2)>>2]|0);l=l+1|0}while((l|0)<(c[h>>2]|0))}n=c[m>>2]|0}else n=i;fd(n)}n=f+56|0;i=c[n>>2]|0;if(i|0){if((e|0)!=0?(m=e+28|0,(c[m>>2]|0)>0):0){zc(i);if((c[m>>2]|0)>1){e=1;do{zc((c[n>>2]|0)+(e*52|0)|0);e=e+1|0}while((e|0)<(c[m>>2]|0))}o=c[n>>2]|0}else o=i;fd(o)}o=c[f+60>>2]|0;if(o|0)Ac(o);Bc(f+80|0);kc(f+20|0);kc(f+32|0)}o=a+8|0;i=c[o>>2]|0;if(i|0){if(d?(d=b+4|0,b=c[d>>2]|0,(b|0)>0):0){n=i;m=b;b=0;while(1){e=c[n+(b<<2)>>2]|0;if(!e)p=m;else{fd(e);p=c[d>>2]|0}e=b+1|0;if((e|0)>=(p|0))break;n=c[o>>2]|0;m=p;b=e}q=c[o>>2]|0}else q=i;fd(q);q=c[a+12>>2]|0;if(q|0)fd(q)}if(g){g=c[f+64>>2]|0;if(g|0)fd(g);g=c[f+68>>2]|0;if(g|0)fd(g);g=c[f+72>>2]|0;if(g|0)fd(g);fd(f)}f=a;a=f+112|0;do{c[f>>2]=0;f=f+4|0}while((f|0)<(a|0));return}function yc(a){a=a|0;ic(a+16|0);fd(c[a+48>>2]|0);fd(c[a+64>>2]|0);fd(c[a+80>>2]|0);fd(c[a+96>>2]|0);fd(c[a+112>>2]|0);fd(c[a+128>>2]|0);fd(c[a+144>>2]|0);fd(c[a+36>>2]|0);fd(c[a+152>>2]|0);fd(c[a+160>>2]|0);md(a|0,0,180)|0;return}function zc(a){a=a|0;var b=0,d=0,e=0,f=0;if(!a)return;b=c[a+16>>2]|0;if(b|0)fd(b);b=c[a+20>>2]|0;if(b|0)fd(b);b=c[a+24>>2]|0;if(b|0)fd(b);b=a+8|0;d=c[b>>2]|0;if(d|0){e=d;d=0;while(1){fd(c[c[e+(d<<2)>>2]>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+4>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+8>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+12>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+16>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+20>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+24>>2]|0);fd(c[(c[(c[b>>2]|0)+(d<<2)>>2]|0)+28>>2]|0);fd(c[(c[b>>2]|0)+(d<<2)>>2]|0);f=d+1|0;if((f|0)==17)break;e=c[b>>2]|0;d=f}fd(c[b>>2]|0)}b=a+12|0;d=c[b>>2]|0;if(d|0){fd(c[d>>2]|0);fd(c[(c[b>>2]|0)+4>>2]|0);fd(c[(c[b>>2]|0)+8>>2]|0);fd(c[b>>2]|0)}b=a;a=b+52|0;do{c[b>>2]=0;b=b+4|0}while((b|0)<(a|0));return}function Ac(a){a=a|0;if(!a)return;fd(a);return}function Bc(a){a=a|0;var b=0;b=a;a=b+48|0;do{c[b>>2]=0;b=b+4|0}while((b|0)<(a|0));return}function Cc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;if(oc(a,b,0)|0){xc(a);d=1;return d|0}b=c[a+4>>2]|0;e=c[a+104>>2]|0;if((b|0)==0|(e|0)==0){d=0;return d|0}f=c[b+28>>2]|0;if(!f){d=0;return d|0}b=c[f+3656>>2]|0;g=c[f+4>>2]>>b+1;c[a+48>>2]=g;c[a+20>>2]=g>>b;c[a+24>>2]=-1;b=a+56|0;c[b>>2]=-1;c[b+4>>2]=-1;c[b+8>>2]=-1;c[b+12>>2]=-1;c[a+32>>2]=0;a=e+128|0;c[a>>2]=-1;c[a+4>>2]=-1;d=0;return d|0} function Dc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,_=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0;d=c[a+4>>2]|0;e=c[d+28>>2]|0;f=c[a+104>>2]|0;h=c[e+3656>>2]|0;if(!b){i=-131;return i|0}j=a+20|0;k=c[j>>2]|0;l=a+24|0;m=c[l>>2]|0;if(!((k|0)<=(m|0)|(m|0)==-1)){i=-131;return i|0}n=a+40|0;o=c[n>>2]|0;p=a+36|0;c[p>>2]=o;q=c[b+28>>2]|0;c[n>>2]=q;c[a+44>>2]=-1;r=a+64|0;s=r;t=c[s>>2]|0;u=c[s+4>>2]|0;if(!((t|0)==-1&(u|0)==-1)){s=pd(t|0,u|0,1,0)|0;u=C;t=b+56|0;v=c[t>>2]|0;w=c[t+4>>2]|0;if((s|0)==(v|0)&(u|0)==(w|0)){x=s;y=u}else{z=v;A=w;B=6}}else{w=b+56|0;z=c[w>>2]|0;A=c[w+4>>2]|0;B=6}if((B|0)==6){B=a+56|0;c[B>>2]=-1;c[B+4>>2]=-1;B=f+128|0;c[B>>2]=-1;c[B+4>>2]=-1;x=z;y=A}A=r;c[A>>2]=x;c[A+4>>2]=y;if(!(c[b>>2]|0)){D=k;E=m}else{k=h+1|0;y=c[e+(q<<2)>>2]>>k;A=c[e>>2]>>k;x=c[e+4>>2]>>k;k=c[b+88>>2]|0;r=a+72|0;z=r;B=pd(c[z>>2]|0,c[z+4>>2]|0,k|0,((k|0)<0)<<31>>31|0)|0;k=r;c[k>>2]=B;c[k+4>>2]=C;k=c[b+92>>2]|0;B=a+80|0;r=B;z=pd(c[r>>2]|0,c[r+4>>2]|0,k|0,((k|0)<0)<<31>>31|0)|0;k=B;c[k>>2]=z;c[k+4>>2]=C;k=c[b+96>>2]|0;z=a+88|0;B=z;r=pd(c[B>>2]|0,c[B+4>>2]|0,k|0,((k|0)<0)<<31>>31|0)|0;k=z;c[k>>2]=r;c[k+4>>2]=C;k=c[b+100>>2]|0;r=a+96|0;z=r;B=pd(c[z>>2]|0,c[z+4>>2]|0,k|0,((k|0)<0)<<31>>31|0)|0;k=r;c[k>>2]=B;c[k+4>>2]=C;k=a+48|0;B=c[k>>2]|0;r=(B|0)==0;z=r?x:0;w=r?0:x;r=d+4|0;if((c[r>>2]|0)>0){d=f+4|0;v=a+8|0;u=(x|0)/2|0;s=(A|0)/2|0;t=0-s|0;F=(A|0)>0;G=u+s|0;s=A+-1|0;H=(y|0)>0;I=f+8|0;J=(x|0)>0;K=x+-1|0;L=(A|0)/-2|0;M=o;o=q;q=0;while(1){N=(o|0)!=0;a:do if(!M){O=Ec((c[d>>2]|0)-h|0)|0;P=c[(c[v>>2]|0)+(q<<2)>>2]|0;Q=P+(z<<2)|0;R=c[(c[b>>2]|0)+(q<<2)>>2]|0;if(!N){if(F)S=0;else{T=P;U=R;break}while(1){V=Q+(S<<2)|0;g[V>>2]=+g[O+(S<<2)>>2]*+g[R+(S<<2)>>2]+ +g[O+(s-S<<2)>>2]*+g[V>>2];S=S+1|0;if((S|0)==(A|0)){T=P;U=R;break a}}}V=R+(u<<2)+(t<<2)|0;if(F){W=0;do{X=Q+(W<<2)|0;g[X>>2]=+g[O+(W<<2)>>2]*+g[V+(W<<2)>>2]+ +g[O+(s-W<<2)>>2]*+g[X>>2];W=W+1|0}while((W|0)!=(A|0));Y=A}else Y=0;if((Y|0)<(G|0)){W=Y;do{c[Q+(W<<2)>>2]=c[V+(W<<2)>>2];W=W+1|0}while((W|0)<(G|0));T=P;U=R}else{T=P;U=R}}else if(N){W=Ec((c[I>>2]|0)-h|0)|0;V=c[(c[v>>2]|0)+(q<<2)>>2]|0;Q=V+(z<<2)|0;O=c[(c[b>>2]|0)+(q<<2)>>2]|0;if(J)Z=0;else{T=V;U=O;break}do{X=Q+(Z<<2)|0;g[X>>2]=+g[W+(Z<<2)>>2]*+g[O+(Z<<2)>>2]+ +g[W+(K-Z<<2)>>2]*+g[X>>2];Z=Z+1|0}while((Z|0)!=(x|0));T=V;U=O}else{O=Ec((c[d>>2]|0)-h|0)|0;V=c[(c[v>>2]|0)+(q<<2)>>2]|0;W=V+(z<<2)+(u<<2)+(L<<2)|0;Q=c[(c[b>>2]|0)+(q<<2)>>2]|0;if(F)_=0;else{T=V;U=Q;break}do{R=W+(_<<2)|0;g[R>>2]=+g[O+(_<<2)>>2]*+g[Q+(_<<2)>>2]+ +g[O+(s-_<<2)>>2]*+g[R>>2];_=_+1|0}while((_|0)!=(A|0));T=V;U=Q}while(0);N=T+(w<<2)|0;Q=U+(y<<2)|0;if(H){V=0;do{c[N+(V<<2)>>2]=c[Q+(V<<2)>>2];V=V+1|0}while((V|0)!=(y|0))}V=q+1|0;if((V|0)>=(c[r>>2]|0))break;M=c[p>>2]|0;o=c[n>>2]|0;q=V}$=c[k>>2]|0;aa=c[l>>2]|0}else{$=B;aa=m}c[k>>2]=($|0)==0?x:0;if((aa|0)==-1){c[l>>2]=w;ba=w;ca=w}else{c[l>>2]=z;ba=z;ca=(((c[e+(c[n>>2]<<2)>>2]|0)/4|0)+((c[e+(c[p>>2]<<2)>>2]|0)/4|0)>>h)+z|0}c[j>>2]=ca;D=ca;E=ba}ba=f+128|0;f=ba;ca=c[f>>2]|0;z=c[f+4>>2]|0;if((ca|0)==-1&(z|0)==-1){da=0;ea=0}else{f=((c[e+(c[n>>2]<<2)>>2]|0)/4|0)+((c[e+(c[p>>2]<<2)>>2]|0)/4|0)|0;w=pd(f|0,((f|0)<0)<<31>>31|0,ca|0,z|0)|0;da=w;ea=C}w=ba;c[w>>2]=da;c[w+4>>2]=ea;w=a+56|0;ba=w;z=c[ba>>2]|0;ca=c[ba+4>>2]|0;do if((z|0)==-1&(ca|0)==-1){ba=b+48|0;f=c[ba>>2]|0;aa=c[ba+4>>2]|0;if(!((f|0)==-1&(aa|0)==-1)?(ba=w,c[ba>>2]=f,c[ba+4>>2]=aa,(ea|0)>(aa|0)|(ea|0)==(aa|0)&da>>>0>f>>>0):0){ba=ld(da|0,ea|0,f|0,aa|0)|0;aa=(ba|0)<0?0:ba;if(!(c[b+44>>2]|0)){ba=E+(aa>>h)|0;c[l>>2]=(ba|0)>(D|0)?D:ba;break}else{ba=D-E<<h;c[j>>2]=D-(((aa|0)>(ba|0)?ba:aa)>>h);break}}}else{aa=((c[e+(c[n>>2]<<2)>>2]|0)/4|0)+((c[e+(c[p>>2]<<2)>>2]|0)/4|0)|0;ba=pd(aa|0,((aa|0)<0)<<31>>31|0,z|0,ca|0)|0;aa=C;f=w;c[f>>2]=ba;c[f+4>>2]=aa;f=b+48|0;x=c[f>>2]|0;$=c[f+4>>2]|0;if(!((x|0)==-1&($|0)==-1|(ba|0)==(x|0)&(aa|0)==($|0))){if(((aa|0)>($|0)|(aa|0)==($|0)&ba>>>0>x>>>0?(f=ld(ba|0,aa|0,x|0,$|0)|0,f|0):0)?c[b+44>>2]|0:0){aa=D-E<<h;ba=(f|0)>(aa|0)?aa:f;c[j>>2]=D-(((ba|0)<0?0:ba)>>h)}ba=w;c[ba>>2]=x;c[ba+4>>2]=$}}while(0);if(!(c[b+44>>2]|0)){i=0;return i|0}c[a+32>>2]=1;i=0;return i|0}function Ec(a){a=a|0;return c[456+(a<<2)>>2]|0}function Fc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0;d=c[a+24>>2]|0;if((d|0)<=-1){e=0;return e|0}f=c[a+20>>2]|0;if((f|0)<=(d|0)){e=0;return e|0}if(b|0){g=c[(c[a+4>>2]|0)+4>>2]|0;if((g|0)>0){h=a+8|0;i=a+12|0;j=0;do{c[(c[i>>2]|0)+(j<<2)>>2]=(c[(c[h>>2]|0)+(j<<2)>>2]|0)+(d<<2);j=j+1|0}while((j|0)<(g|0));k=i}else k=a+12|0;c[b>>2]=c[k>>2]}e=f-d|0;return e|0}function Gc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;d=a+24|0;e=c[d>>2]|0;if(b|0?(e+b|0)>(c[a+20>>2]|0):0){f=-131;return f|0}c[d>>2]=e+b;f=0;return f|0}function Hc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0;d=(a|0)!=0;if(d?(e=c[a+64>>2]|0,(e|0)!=0):0){f=c[e+104>>2]|0;g=c[e+4>>2]|0;if(!g){h=f;i=1;j=0;k=0;l=0}else{h=f;i=1;j=1;k=c[g+28>>2]|0;l=g}}else{h=0;i=0;j=0;k=0;l=0}g=d?a+4|0:0;if(!(d&((k|0)!=0&(j&(i&(h|0)!=0))))){m=-136;return m|0}mc(a);Ua(g,c[b>>2]|0,c[b+4>>2]|0);if(Xa(g,1)|0){m=-135;return m|0}i=Xa(g,c[h+44>>2]|0)|0;if((i|0)==-1){m=-136;return m|0}c[a+40>>2]=i;h=k+32+(i<<2)|0;i=c[h>>2]|0;if(!i){m=-136;return m|0}j=c[i>>2]|0;i=a+28|0;c[i>>2]=j;do if(j){c[a+24>>2]=Xa(g,1)|0;d=Xa(g,1)|0;c[a+32>>2]=d;if((d|0)==-1){m=-136;return m|0}else{n=c[i>>2]|0;break}}else{c[a+24>>2]=0;c[a+32>>2]=0;n=0}while(0);i=b+16|0;g=c[i+4>>2]|0;j=a+48|0;c[j>>2]=c[i>>2];c[j+4>>2]=g;g=b+24|0;j=c[g+4>>2]|0;i=a+56|0;c[i>>2]=c[g>>2];c[i+4>>2]=j;c[a+44>>2]=c[b+12>>2];b=a+36|0;c[b>>2]=c[k+(n<<2)>>2];n=l+4|0;c[a>>2]=eb(a,c[n>>2]<<2)|0;if((c[n>>2]|0)>0){l=0;do{j=eb(a,c[b>>2]<<2)|0;c[(c[a>>2]|0)+(l<<2)>>2]=j;l=l+1|0}while((l|0)<(c[n>>2]|0))}n=c[(c[h>>2]|0)+12>>2]|0;m=Ga[c[(c[34172+(c[k+288+(n<<2)>>2]<<2)>>2]|0)+16>>2]&15](a,c[k+544+(n<<2)>>2]|0)|0;return m|0}function Ic(a){a=a|0;if(a|0)fd(a);return}function Jc(a){a=a|0;c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;return}function Kc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0;if(!a)return;b=c[a>>2]|0;if(b|0){d=a+8|0;e=c[d>>2]|0;if((e|0)>0){f=e;e=b;g=0;while(1){h=c[e+(g<<2)>>2]|0;if(!h)i=f;else{fd(h);i=c[d>>2]|0}h=g+1|0;if((h|0)>=(i|0))break;f=i;e=c[a>>2]|0;g=h}j=c[a>>2]|0}else j=b;fd(j)}j=c[a+4>>2]|0;if(j|0)fd(j);j=c[a+12>>2]|0;if(j|0)fd(j);c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;return}function Lc(a){a=a|0;c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+16>>2]=0;c[a+20>>2]=0;c[a+24>>2]=0;c[a+28>>2]=gd(1,3664)|0;return}function Mc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0;b=c[a+28>>2]|0;if(!b){c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+16>>2]=0;c[a+20>>2]=0;c[a+24>>2]=0;c[a+28>>2]=0;return}d=b+8|0;e=c[d>>2]|0;if((e|0)>0){f=e;e=0;while(1){g=c[b+32+(e<<2)>>2]|0;if(!g)h=f;else{fd(g);h=c[d>>2]|0}e=e+1|0;if((e|0)>=(h|0))break;else f=h}}h=b+12|0;f=c[h>>2]|0;if((f|0)>0){e=f;f=0;while(1){d=c[b+544+(f<<2)>>2]|0;if(!d)i=e;else{Ba[c[(c[34172+(c[b+288+(f<<2)>>2]<<2)>>2]|0)+8>>2]&7](d);i=c[h>>2]|0}f=f+1|0;if((f|0)>=(i|0))break;else e=i}}i=b+16|0;e=c[i>>2]|0;if((e|0)>0){f=e;e=0;while(1){h=c[b+1056+(e<<2)>>2]|0;if(!h)j=f;else{Ba[c[(c[34164+(c[b+800+(e<<2)>>2]<<2)>>2]|0)+12>>2]&7](h);j=c[i>>2]|0}e=e+1|0;if((e|0)>=(j|0))break;else f=j}}j=b+20|0;f=c[j>>2]|0;if((f|0)>0){e=f;f=0;while(1){i=c[b+1568+(f<<2)>>2]|0;if(!i)k=e;else{Ba[c[(c[34152+(c[b+1312+(f<<2)>>2]<<2)>>2]|0)+12>>2]&7](i);k=c[j>>2]|0}f=f+1|0;if((f|0)>=(k|0))break;else e=k}}k=b+24|0;e=b+2848|0;if((c[k>>2]|0)>0){f=0;do{j=c[b+1824+(f<<2)>>2]|0;if(j|0)wc(j);j=c[e>>2]|0;if(j|0)Nc(j+(f*56|0)|0);f=f+1|0}while((f|0)<(c[k>>2]|0))}k=c[e>>2]|0;if(k|0)fd(k);k=b+28|0;if((c[k>>2]|0)>0){e=0;do{Ic(c[b+2852+(e<<2)>>2]|0);e=e+1|0}while((e|0)<(c[k>>2]|0))}fd(b);c[a>>2]=0;c[a+4>>2]=0;c[a+8>>2]=0;c[a+12>>2]=0;c[a+16>>2]=0;c[a+20>>2]=0;c[a+24>>2]=0;c[a+28>>2]=0;return}function Nc(a){a=a|0;var b=0;b=c[a+16>>2]|0;if(b|0)fd(b);b=c[a+20>>2]|0;if(b|0)fd(b);b=c[a+24>>2]|0;if(b|0)fd(b);b=c[a+28>>2]|0;if(b|0)fd(b);b=c[a+32>>2]|0;if(b|0)fd(b);b=a;a=b+56|0;do{c[b>>2]=0;b=b+4|0}while((b|0)<(a|0));return}function Oc(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0;f=i;i=i+32|0;g=f;h=f+20|0;if(!e){j=-133;i=f;return j|0}Ua(g,c[e>>2]|0,c[e+4>>2]|0);k=Xa(g,8)|0;a[h>>0]=0;a[h+1>>0]=0;a[h+2>>0]=0;a[h+3>>0]=0;a[h+4>>0]=0;a[h>>0]=Xa(g,8)|0;a[h+1>>0]=Xa(g,8)|0;a[h+2>>0]=Xa(g,8)|0;a[h+3>>0]=Xa(g,8)|0;a[h+4>>0]=Xa(g,8)|0;a[h+5>>0]=Xa(g,8)|0;a:do if(!(Xc(h,57392,6)|0))switch(k|0){case 1:{if(!(c[e+8>>2]|0)){l=-133;break a}m=b+8|0;if(c[m>>2]|0){l=-133;break a}n=c[b+28>>2]|0;if(!n){l=-129;break a}o=Xa(g,32)|0;c[b>>2]=o;if(o|0){l=-134;break a}o=b+4|0;c[o>>2]=Xa(g,8)|0;c[m>>2]=Xa(g,32)|0;c[b+12>>2]=Xa(g,32)|0;c[b+16>>2]=Xa(g,32)|0;c[b+20>>2]=Xa(g,32)|0;c[n>>2]=1<<(Xa(g,4)|0);p=1<<(Xa(g,4)|0);c[n+4>>2]=p;if((((c[m>>2]|0)>=1?(c[o>>2]|0)>=1:0)?(o=c[n>>2]|0,!((p|0)>8192|((o|0)<64|(p|0)<(o|0)))):0)?(Xa(g,1)|0)==1:0){l=0;break a}Mc(b);l=-133;break a;break}case 3:{if(!(c[b+8>>2]|0)){l=-133;break a}o=Xa(g,32)|0;b:do if((o|0)>=0?(p=g+16|0,(o|0)<=((c[p>>2]|0)+-8|0)):0){n=gd(o+1|0,1)|0;c[d+12>>2]=n;if(o|0){m=n;n=o;while(1){n=n+-1|0;a[m>>0]=Xa(g,8)|0;if(!n)break;else m=m+1|0}}m=Xa(g,32)|0;if((m|0)>=0?(n=c[p>>2]|0,(m|0)<=(n-(Ya(g)|0)>>2|0)):0){n=d+8|0;c[n>>2]=m;q=m+1|0;c[d>>2]=gd(q,4)|0;r=d+4|0;c[r>>2]=gd(q,4)|0;if((m|0)>0){m=0;do{q=Xa(g,32)|0;if((q|0)<0){s=d;break b}t=c[p>>2]|0;if((q|0)>(t-(Ya(g)|0)|0)){s=d;break b}c[(c[r>>2]|0)+(m<<2)>>2]=q;t=gd(q+1|0,1)|0;c[(c[d>>2]|0)+(m<<2)>>2]=t;if(q|0){t=c[(c[d>>2]|0)+(m<<2)>>2]|0;u=q;while(1){u=u+-1|0;a[t>>0]=Xa(g,8)|0;if(!u)break;else t=t+1|0}}m=m+1|0}while((m|0)<(c[n>>2]|0))}if((Xa(g,1)|0)==1){l=0;break a}else s=d}else v=28}else v=28;while(0);if((v|0)==28){if(!d){l=-133;break a}s=d}o=c[s>>2]|0;if(o|0){n=d+8|0;m=c[n>>2]|0;if((m|0)>0){r=o;p=m;m=0;while(1){t=c[r+(m<<2)>>2]|0;if(!t)w=p;else{fd(t);w=c[n>>2]|0}t=m+1|0;if((t|0)>=(w|0))break;r=c[s>>2]|0;p=w;m=t}x=c[d>>2]|0}else x=o;fd(x)}m=c[d+4>>2]|0;if(m|0)fd(m);m=c[d+12>>2]|0;if(m|0)fd(m);c[d>>2]=0;c[d+4>>2]=0;c[d+8>>2]=0;c[d+12>>2]=0;l=-133;break a;break}case 5:{if(!(c[b+8>>2]|0)){l=-133;break a}if(!(c[d+12>>2]|0)){l=-133;break a}m=c[b+28>>2]|0;if(!m){l=-129;break a}p=Xa(g,8)|0;r=m+24|0;c[r>>2]=p+1;c:do if((p|0)>=0){n=0;do{t=Pc(g)|0;c[m+1824+(n<<2)>>2]=t;n=n+1|0;if(!t)break c}while((n|0)<(c[r>>2]|0));n=Xa(g,6)|0;if((n|0)>=0){t=0;while(1){if(Xa(g,16)|0)break c;if((t|0)<(n|0))t=t+1|0;else break}t=Xa(g,6)|0;n=m+16|0;c[n>>2]=t+1;if((t|0)>=0){t=0;do{u=Xa(g,16)|0;c[m+800+(t<<2)>>2]=u;if(u>>>0>1)break c;q=Ga[c[(c[34164+(u<<2)>>2]|0)+4>>2]&15](b,g)|0;c[m+1056+(t<<2)>>2]=q;t=t+1|0;if(!q)break c}while((t|0)<(c[n>>2]|0));n=Xa(g,6)|0;t=m+20|0;c[t>>2]=n+1;if((n|0)>=0){n=0;do{q=Xa(g,16)|0;c[m+1312+(n<<2)>>2]=q;if(q>>>0>2)break c;u=Ga[c[(c[34152+(q<<2)>>2]|0)+4>>2]&15](b,g)|0;c[m+1568+(n<<2)>>2]=u;n=n+1|0;if(!u)break c}while((n|0)<(c[t>>2]|0));t=Xa(g,6)|0;n=m+12|0;c[n>>2]=t+1;if((t|0)>=0){t=0;do{u=Xa(g,16)|0;c[m+288+(t<<2)>>2]=u;if(u|0)break c;u=Ga[c[(c[8543]|0)+4>>2]&15](b,g)|0;c[m+544+(t<<2)>>2]=u;t=t+1|0;if(!u)break c}while((t|0)<(c[n>>2]|0));t=Xa(g,6)|0;u=m+8|0;c[u>>2]=t+1;if((t|0)>=0){t=0;do{q=m+32+(t<<2)|0;c[q>>2]=gd(1,16)|0;y=Xa(g,1)|0;c[c[q>>2]>>2]=y;y=Xa(g,16)|0;c[(c[q>>2]|0)+4>>2]=y;y=Xa(g,16)|0;c[(c[q>>2]|0)+8>>2]=y;y=Xa(g,8)|0;z=c[q>>2]|0;c[z+12>>2]=y;if((c[z+4>>2]|0)>0)break c;if((c[z+8>>2]|0)>0)break c;t=t+1|0;if((y|0)<0?1:(y|0)>=(c[n>>2]|0))break c}while((t|0)<(c[u>>2]|0));if((Xa(g,1)|0)==1){l=0;break a}}}}}}}while(0);Mc(b);l=-133;break a;break}default:{l=-133;break a}}else l=-132;while(0);j=l;i=f;return j|0}function Pc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0;b=gd(1,40)|0;c[b+36>>2]=1;a:do if(((Xa(a,24)|0)==5653314?(c[b>>2]=Xa(a,16)|0,d=Xa(a,24)|0,e=b+4|0,c[e>>2]=d,(d|0)!=-1):0)?(d=nb(c[b>>2]|0)|0,((nb(c[e>>2]|0)|0)+d|0)<=24):0){b:do switch(Xa(a,1)|0){case 0:{d=(Xa(a,1)|0)!=0;if(((_(d?1:5,c[e>>2]|0)|0)+7>>3|0)>((c[a+16>>2]|0)-(Ya(a)|0)|0))break a;f=c[e>>2]|0;g=b+8|0;c[g>>2]=ed(f<<2)|0;h=(f|0)>0;if(!d){if(h)i=0;else break b;while(1){d=Xa(a,5)|0;if((d|0)==-1)break a;c[(c[g>>2]|0)+(i<<2)>>2]=d+1;i=i+1|0;if((i|0)>=(c[e>>2]|0))break b}}if(h){d=0;do{if(!(Xa(a,1)|0))c[(c[g>>2]|0)+(d<<2)>>2]=0;else{f=Xa(a,5)|0;if((f|0)==-1)break a;c[(c[g>>2]|0)+(d<<2)>>2]=f+1}d=d+1|0}while((d|0)<(c[e>>2]|0))}break}case 1:{d=(Xa(a,5)|0)+1|0;if(!d)break a;g=c[e>>2]|0;h=b+8|0;c[h>>2]=ed(g<<2)|0;if((g|0)>0){f=g;g=0;j=d;while(1){d=Xa(a,nb(f-g|0)|0)|0;if((j|0)>32|(d|0)==-1)break a;k=c[e>>2]|0;if((d|0)>(k-g|0))break a;if((d|0)>0){if((d+-1>>j+-1|0)>1)break a;l=c[h>>2]|0;m=g;n=0;while(1){c[l+(m<<2)>>2]=j;n=n+1|0;if((n|0)==(d|0))break;else m=m+1|0}o=c[e>>2]|0;p=d+g|0}else{o=k;p=g}if((o|0)>(p|0)){f=o;g=p;j=j+1|0}else break}}break}default:break a}while(0);j=Xa(a,4)|0;g=b+12|0;c[g>>2]=j;switch(j|0){case 2:case 1:break;case 0:{q=b;return q|0}default:break a}c[b+16>>2]=Xa(a,32)|0;c[b+20>>2]=Xa(a,32)|0;j=b+24|0;c[j>>2]=(Xa(a,4)|0)+1;f=Xa(a,1)|0;c[b+28>>2]=f;if((f|0)!=-1){switch(c[g>>2]|0){case 1:{if(!(c[b>>2]|0))r=0;else r=Qc(b)|0;break}case 2:{r=_(c[b>>2]|0,c[e>>2]|0)|0;break}default:r=0}g=(_(c[j>>2]|0,r)|0)+7>>3;f=c[a+16>>2]|0;if((g|0)<=(f-(Ya(a)|0)|0)){f=ed(r<<2)|0;g=b+32|0;c[g>>2]=f;if((r|0)>0){h=0;do{m=Xa(a,c[j>>2]|0)|0;n=c[g>>2]|0;c[n+(h<<2)>>2]=m;h=h+1|0}while((h|0)!=(r|0));s=n}else s=f;if(!r){q=b;return q|0}if((c[s+(r+-1<<2)>>2]|0)!=-1){q=b;return q|0}}}}while(0);wc(b);q=0;return q|0}function Qc(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0;b=c[a+4>>2]|0;d=c[a>>2]|0;if((d|0)<=0)while(1){}a=~~+M(+(+P(+(+(b|0)),+(1.0/+(d|0)))));while(1){e=a+1|0;f=1;g=1;h=0;while(1){i=_(f,a)|0;j=_(g,e)|0;h=h+1|0;if((h|0)>=(d|0)){k=i;l=j;break}else{f=i;g=j}}if((k|0)<=(b|0)&(l|0)>(b|0)){m=a;break}a=((k|0)>(b|0)?-1:1)+a|0}return m|0}function Rc(){Lc(57628);Jc(57660);return}function Sc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0;d=i;i=i+32|0;e=d;Vc(e,a,b);if(!(c[14406]|0))c[e+8>>2]=1;if(Oc(57628,57660,e)|0){f=0;i=d;return f|0}e=(c[14406]|0)+1|0;c[14406]=e;if((e|0)<3){f=1;i=d;return f|0}Cc(57400,57628)|0;lc(57400,57512)|0;wa(c[14408]|0,c[14409]|0);f=1;i=d;return f|0}function Tc(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;d=i;i=i+48|0;e=d;f=d+32|0;Vc(e,a,b);if(Hc(57512,e)|0){g=0;i=d;return g|0}Dc(57400,57512)|0;e=Fc(57400,f)|0;va(c[f>>2]|0,c[14408]|0,e|0);Gc(57400,e)|0;g=1;i=d;return g|0}function Uc(){if(!(c[14406]|0))return;Mc(57628);xc(57400);nc(57512)|0;Kc(57660);return}function Vc(a,b,d){a=a|0;b=b|0;d=d|0;c[a>>2]=b;c[a+4>>2]=d;d=a+8|0;c[d>>2]=0;c[d+4>>2]=0;c[d+8>>2]=0;c[d+12>>2]=0;c[d+16>>2]=0;c[d+20>>2]=0;return}function Wc(){var a=0;if(!0)a=57676;else a=c[(la()|0)+64>>2]|0;return a|0}function Xc(b,c,d){b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;a:do if(!d)e=0;else{f=d;g=b;h=c;while(1){i=a[g>>0]|0;j=a[h>>0]|0;if(i<<24>>24!=j<<24>>24){k=i;l=j;break}f=f+-1|0;if(!f){e=0;break a}else{g=g+1|0;h=h+1|0}}e=(k&255)-(l&255)|0}while(0);return e|0}function Yc(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0;f=i;i=i+208|0;g=f+8|0;h=f;j=_(d,b)|0;b=h;c[b>>2]=1;c[b+4>>2]=0;if(j|0){b=0-d|0;c[g+4>>2]=d;c[g>>2]=d;k=d;l=d;m=2;while(1){n=l+d+k|0;c[g+(m<<2)>>2]=n;if(n>>>0<j>>>0){o=k;k=n;m=m+1|0;l=o}else break}l=a+j+b|0;j=h+4|0;if(l>>>0>a>>>0){m=l;k=1;o=a;n=1;while(1){do if((k&3|0)==3){Zc(o,d,e,n,g);p=c[j>>2]|0;q=p<<30|(c[h>>2]|0)>>>2;c[h>>2]=q;c[j>>2]=p>>>2;r=q;s=n+2|0}else{q=n+-1|0;if((c[g+(q<<2)>>2]|0)>>>0<(m-o|0)>>>0)Zc(o,d,e,n,g);else $c(o,d,e,h,n,0,g);if((n|0)==1){p=c[h>>2]|0;c[j>>2]=p>>>31|c[j>>2]<<1;t=p<<1;c[h>>2]=t;r=t;s=0;break}if(q>>>0>31){t=c[h>>2]|0;c[j>>2]=t;c[h>>2]=0;u=n+-33|0;v=t;w=0}else{u=q;v=c[j>>2]|0;w=c[h>>2]|0}c[j>>2]=w>>>(32-u|0)|v<<u;q=w<<u;c[h>>2]=q;r=q;s=1}while(0);k=r|1;c[h>>2]=k;q=o+d|0;if(q>>>0>=l>>>0){x=q;y=s;break}else{o=q;n=s}}}else{x=a;y=1}$c(x,d,e,h,y,0,g);a=h+4|0;s=c[h>>2]|0;n=c[a>>2]|0;o=(n|0)==0;if(!((y|0)==1&(s|0)==1&o)){l=o;o=s;s=n;n=x;x=y;while(1){if((x|0)<2){y=o+-1|0;do if(y){if(!(y&1)){k=y;r=0;while(1){u=r+1|0;k=k>>>1;if(k&1|0){z=u;break}else r=u}}else{if(l)A=32;else{if(!(s&1)){B=s;C=0}else{D=0;E=o;F=s;G=0;break}while(1){r=C+1|0;B=B>>>1;if(B&1|0){A=r;break}else C=r}}z=A+32|0}if(z>>>0>31){H=z;I=28}else{D=z;E=o;F=s;G=z}}else{H=32;I=28}while(0);if((I|0)==28){I=0;c[h>>2]=s;c[j>>2]=0;D=H+-32|0;E=s;F=0;G=H}c[h>>2]=F<<32-D|E>>>D;c[j>>2]=F>>>D;J=n+b|0;K=G+x|0}else{y=o>>>30;r=x+-2|0;c[h>>2]=(o<<1&2147483646|y<<31)^3;c[j>>2]=(y|s<<2)>>>1;$c(n+(0-(c[g+(r<<2)>>2]|0))+b|0,d,e,h,x+-1|0,1,g);y=c[h>>2]|0;c[j>>2]=y>>>31|c[j>>2]<<1;c[h>>2]=y<<1|1;y=n+b|0;$c(y,d,e,h,r,1,g);J=y;K=r}o=c[h>>2]|0;s=c[a>>2]|0;l=(s|0)==0;if((K|0)==1&(o|0)==1&l)break;else{n=J;x=K}}}}i=f;return}function Zc(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;g=i;i=i+240|0;h=g;c[h>>2]=a;a:do if((e|0)>1){j=0-b|0;k=e;l=a;m=a;n=1;while(1){o=l+j|0;p=k+-2|0;q=o+(0-(c[f+(p<<2)>>2]|0))|0;if((Ga[d&15](m,q)|0)>-1?(Ga[d&15](m,o)|0)>-1:0){r=n;break a}s=n+1|0;t=h+(n<<2)|0;if((Ga[d&15](q,o)|0)>-1){c[t>>2]=q;u=q;v=k+-1|0}else{c[t>>2]=o;u=o;v=p}if((v|0)<=1){r=s;break a}k=v;l=u;m=c[h>>2]|0;n=s}}else r=1;while(0);_c(b,h,r);i=g;return}function _c(a,b,d){a=a|0;b=b|0;d=d|0;var e=0,f=0,g=0,h=0,j=0,k=0,l=0,m=0;e=i;i=i+256|0;f=e;a:do if((d|0)>=2?(g=b+(d<<2)|0,c[g>>2]=f,a|0):0){h=a;j=f;while(1){k=h>>>0>256?256:h;od(j|0,c[b>>2]|0,k|0)|0;l=0;do{m=b+(l<<2)|0;l=l+1|0;od(c[m>>2]|0,c[b+(l<<2)>>2]|0,k|0)|0;c[m>>2]=(c[m>>2]|0)+k}while((l|0)!=(d|0));if((h|0)==(k|0))break a;h=h-k|0;j=c[g>>2]|0}}while(0);i=e;return}function $c(a,b,d,e,f,g,h){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0;j=i;i=i+240|0;k=j;l=c[e>>2]|0;m=c[e+4>>2]|0;c[k>>2]=a;e=0-b|0;a:do if((m|0)!=0|(l|0)!=1?(n=a+(0-(c[h+(f<<2)>>2]|0))|0,(Ga[d&15](n,a)|0)>=1):0){o=a;p=f;q=(g|0)==0;r=n;n=1;s=l;t=m;while(1){if(q&(p|0)>1){u=o+e|0;v=c[h+(p+-2<<2)>>2]|0;if((Ga[d&15](u,r)|0)>-1){w=o;x=p;y=n;z=19;break a}if((Ga[d&15](u+(0-v)|0,r)|0)>-1){w=o;x=p;y=n;z=19;break a}}v=n+1|0;c[k+(n<<2)>>2]=r;u=s+-1|0;do if(u){if(!(u&1)){A=u;B=0;while(1){C=B+1|0;A=A>>>1;if(A&1|0){D=C;break}else B=C}}else{if(!t)E=32;else{if(!(t&1)){F=t;G=0}else{H=0;I=s;J=t;K=0;break}while(1){B=G+1|0;F=F>>>1;if(F&1|0){E=B;break}else G=B}}D=E+32|0}if(D>>>0>31){L=D;z=15}else{H=D;I=s;J=t;K=D}}else{L=32;z=15}while(0);if((z|0)==15){z=0;H=L+-32|0;I=t;J=0;K=L}s=J<<32-H|I>>>H;t=J>>>H;u=K+p|0;if(!((t|0)!=0|(s|0)!=1)){w=r;x=u;y=v;z=19;break a}B=r+(0-(c[h+(u<<2)>>2]|0))|0;if((Ga[d&15](B,c[k>>2]|0)|0)<1){M=r;N=u;O=0;P=v;z=18;break}else{A=r;p=u;q=1;r=B;n=v;o=A}}}else{M=a;N=f;O=g;P=1;z=18}while(0);if((z|0)==18?(O|0)==0:0){w=M;x=N;y=P;z=19}if((z|0)==19){_c(b,k,y);Zc(w,b,d,x,h)}i=j;return}function ad(a,b){a=+a;b=b|0;var d=0.0,e=0,f=0,g=0,i=0.0;if((b|0)>1023){d=a*8988465674311579538646525.0e283;e=b+-1023|0;if((e|0)>1023){f=b+-2046|0;g=(f|0)>1023?1023:f;i=d*8988465674311579538646525.0e283}else{g=e;i=d}}else if((b|0)<-1022){d=a*2.2250738585072014e-308;e=b+1022|0;if((e|0)<-1022){f=b+2044|0;g=(f|0)<-1022?-1022:f;i=d*2.2250738585072014e-308}else{g=e;i=d}}else{g=b;i=a}b=nd(g+1023|0,0,52)|0;g=C;c[k>>2]=b;c[k+4>>2]=g;return +(i*+h[k>>3])}function bd(a,b){a=+a;b=b|0;return +(+ad(a,b))}function cd(a){a=+a;var b=0,d=0,e=0.0,f=0.0;h[k>>3]=a;b=c[k+4>>2]|0;d=b&2146435072;if(!(d>>>0>1126170624|(d|0)==1126170624&0>0)){d=(b|0)<0;e=d?a+-4503599627370496.0+4503599627370496.0:a+4503599627370496.0+-4503599627370496.0;if(e==0.0)f=d?-0.0:0.0;else f=e}else f=a;return +f}function dd(a){a=+a;var b=0,d=0,e=0.0,f=0.0;b=(g[k>>2]=a,c[k>>2]|0);if((b&2130706432)>>>0<=1249902592){d=(b|0)<0;e=d?a+-8388608.0+8388608.0:a+8388608.0+-8388608.0;if(e==0.0)f=d?-0.0:0.0;else f=e}else f=a;return +f}function ed(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,_=0,$=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ha=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,pa=0,qa=0,sa=0,va=0,wa=0,xa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Fa=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0,Na=0,Oa=0,Pa=0,Qa=0;do if(a>>>0<245){b=a>>>0<11?16:a+11&-8;d=b>>>3;e=c[14420]|0;f=e>>>d;if(f&3|0){g=(f&1^1)+d|0;h=57720+(g<<1<<2)|0;i=h+8|0;j=c[i>>2]|0;k=j+8|0;l=c[k>>2]|0;do if((h|0)!=(l|0)){if(l>>>0<(c[14424]|0)>>>0)ra();m=l+12|0;if((c[m>>2]|0)==(j|0)){c[m>>2]=h;c[i>>2]=l;break}else ra()}else c[14420]=e&~(1<<g);while(0);l=g<<3;c[j+4>>2]=l|3;i=j+l+4|0;c[i>>2]=c[i>>2]|1;n=k;return n|0}i=c[14422]|0;if(b>>>0>i>>>0){if(f|0){l=2<<d;h=f<<d&(l|0-l);l=(h&0-h)+-1|0;h=l>>>12&16;m=l>>>h;l=m>>>5&8;o=m>>>l;m=o>>>2&4;p=o>>>m;o=p>>>1&2;q=p>>>o;p=q>>>1&1;r=(l|h|m|o|p)+(q>>>p)|0;p=57720+(r<<1<<2)|0;q=p+8|0;o=c[q>>2]|0;m=o+8|0;h=c[m>>2]|0;do if((p|0)!=(h|0)){if(h>>>0<(c[14424]|0)>>>0)ra();l=h+12|0;if((c[l>>2]|0)==(o|0)){c[l>>2]=p;c[q>>2]=h;s=c[14422]|0;break}else ra()}else{c[14420]=e&~(1<<r);s=i}while(0);i=(r<<3)-b|0;c[o+4>>2]=b|3;e=o+b|0;c[e+4>>2]=i|1;c[e+i>>2]=i;if(s|0){h=c[14425]|0;q=s>>>3;p=57720+(q<<1<<2)|0;d=c[14420]|0;f=1<<q;if(d&f){q=p+8|0;k=c[q>>2]|0;if(k>>>0<(c[14424]|0)>>>0)ra();else{t=q;u=k}}else{c[14420]=d|f;t=p+8|0;u=p}c[t>>2]=h;c[u+12>>2]=h;c[h+8>>2]=u;c[h+12>>2]=p}c[14422]=i;c[14425]=e;n=m;return n|0}e=c[14421]|0;if(e){i=(e&0-e)+-1|0;e=i>>>12&16;p=i>>>e;i=p>>>5&8;h=p>>>i;p=h>>>2&4;f=h>>>p;h=f>>>1&2;d=f>>>h;f=d>>>1&1;k=c[57984+((i|e|p|h|f)+(d>>>f)<<2)>>2]|0;f=(c[k+4>>2]&-8)-b|0;d=k;h=k;while(1){k=c[d+16>>2]|0;if(!k){p=c[d+20>>2]|0;if(!p){v=f;w=h;break}else x=p}else x=k;k=(c[x+4>>2]&-8)-b|0;p=k>>>0<f>>>0;f=p?k:f;d=x;h=p?x:h}h=c[14424]|0;if(w>>>0<h>>>0)ra();d=w+b|0;if(w>>>0>=d>>>0)ra();f=c[w+24>>2]|0;m=c[w+12>>2]|0;do if((m|0)==(w|0)){o=w+20|0;r=c[o>>2]|0;if(!r){p=w+16|0;k=c[p>>2]|0;if(!k){y=0;break}else{z=k;A=p}}else{z=r;A=o}while(1){o=z+20|0;r=c[o>>2]|0;if(r|0){z=r;A=o;continue}o=z+16|0;r=c[o>>2]|0;if(!r){B=z;C=A;break}else{z=r;A=o}}if(C>>>0<h>>>0)ra();else{c[C>>2]=0;y=B;break}}else{o=c[w+8>>2]|0;if(o>>>0<h>>>0)ra();r=o+12|0;if((c[r>>2]|0)!=(w|0))ra();p=m+8|0;if((c[p>>2]|0)==(w|0)){c[r>>2]=m;c[p>>2]=o;y=m;break}else ra()}while(0);do if(f|0){m=c[w+28>>2]|0;h=57984+(m<<2)|0;if((w|0)==(c[h>>2]|0)){c[h>>2]=y;if(!y){c[14421]=c[14421]&~(1<<m);break}}else{if(f>>>0<(c[14424]|0)>>>0)ra();m=f+16|0;if((c[m>>2]|0)==(w|0))c[m>>2]=y;else c[f+20>>2]=y;if(!y)break}m=c[14424]|0;if(y>>>0<m>>>0)ra();c[y+24>>2]=f;h=c[w+16>>2]|0;do if(h|0)if(h>>>0<m>>>0)ra();else{c[y+16>>2]=h;c[h+24>>2]=y;break}while(0);h=c[w+20>>2]|0;if(h|0)if(h>>>0<(c[14424]|0)>>>0)ra();else{c[y+20>>2]=h;c[h+24>>2]=y;break}}while(0);if(v>>>0<16){f=v+b|0;c[w+4>>2]=f|3;h=w+f+4|0;c[h>>2]=c[h>>2]|1}else{c[w+4>>2]=b|3;c[d+4>>2]=v|1;c[d+v>>2]=v;h=c[14422]|0;if(h|0){f=c[14425]|0;m=h>>>3;h=57720+(m<<1<<2)|0;o=c[14420]|0;p=1<<m;if(o&p){m=h+8|0;r=c[m>>2]|0;if(r>>>0<(c[14424]|0)>>>0)ra();else{D=m;E=r}}else{c[14420]=o|p;D=h+8|0;E=h}c[D>>2]=f;c[E+12>>2]=f;c[f+8>>2]=E;c[f+12>>2]=h}c[14422]=v;c[14425]=d}n=w+8|0;return n|0}else F=b}else F=b}else if(a>>>0<=4294967231){h=a+11|0;f=h&-8;p=c[14421]|0;if(p){o=0-f|0;r=h>>>8;if(r)if(f>>>0>16777215)G=31;else{h=(r+1048320|0)>>>16&8;m=r<<h;r=(m+520192|0)>>>16&4;k=m<<r;m=(k+245760|0)>>>16&2;e=14-(r|h|m)+(k<<m>>>15)|0;G=f>>>(e+7|0)&1|e<<1}else G=0;e=c[57984+(G<<2)>>2]|0;a:do if(!e){H=o;I=0;J=0;K=86}else{m=o;k=0;h=f<<((G|0)==31?0:25-(G>>>1)|0);r=e;i=0;while(1){q=c[r+4>>2]&-8;j=q-f|0;if(j>>>0<m>>>0)if((q|0)==(f|0)){L=j;M=r;N=r;K=90;break a}else{O=j;P=r}else{O=m;P=i}j=c[r+20>>2]|0;r=c[r+16+(h>>>31<<2)>>2]|0;q=(j|0)==0|(j|0)==(r|0)?k:j;j=(r|0)==0;if(j){H=O;I=q;J=P;K=86;break}else{m=O;k=q;h=h<<(j&1^1);i=P}}}while(0);if((K|0)==86){if((I|0)==0&(J|0)==0){e=2<<G;o=p&(e|0-e);if(!o){F=f;break}e=(o&0-o)+-1|0;o=e>>>12&16;b=e>>>o;e=b>>>5&8;d=b>>>e;b=d>>>2&4;i=d>>>b;d=i>>>1&2;h=i>>>d;i=h>>>1&1;Q=c[57984+((e|o|b|d|i)+(h>>>i)<<2)>>2]|0}else Q=I;if(!Q){R=H;S=J}else{L=H;M=Q;N=J;K=90}}if((K|0)==90)while(1){K=0;i=(c[M+4>>2]&-8)-f|0;h=i>>>0<L>>>0;d=h?i:L;i=h?M:N;h=c[M+16>>2]|0;if(h|0){L=d;M=h;N=i;K=90;continue}M=c[M+20>>2]|0;if(!M){R=d;S=i;break}else{L=d;N=i;K=90}}if((S|0)!=0?R>>>0<((c[14422]|0)-f|0)>>>0:0){p=c[14424]|0;if(S>>>0<p>>>0)ra();i=S+f|0;if(S>>>0>=i>>>0)ra();d=c[S+24>>2]|0;h=c[S+12>>2]|0;do if((h|0)==(S|0)){b=S+20|0;o=c[b>>2]|0;if(!o){e=S+16|0;k=c[e>>2]|0;if(!k){T=0;break}else{U=k;V=e}}else{U=o;V=b}while(1){b=U+20|0;o=c[b>>2]|0;if(o|0){U=o;V=b;continue}b=U+16|0;o=c[b>>2]|0;if(!o){W=U;X=V;break}else{U=o;V=b}}if(X>>>0<p>>>0)ra();else{c[X>>2]=0;T=W;break}}else{b=c[S+8>>2]|0;if(b>>>0<p>>>0)ra();o=b+12|0;if((c[o>>2]|0)!=(S|0))ra();e=h+8|0;if((c[e>>2]|0)==(S|0)){c[o>>2]=h;c[e>>2]=b;T=h;break}else ra()}while(0);do if(d|0){h=c[S+28>>2]|0;p=57984+(h<<2)|0;if((S|0)==(c[p>>2]|0)){c[p>>2]=T;if(!T){c[14421]=c[14421]&~(1<<h);break}}else{if(d>>>0<(c[14424]|0)>>>0)ra();h=d+16|0;if((c[h>>2]|0)==(S|0))c[h>>2]=T;else c[d+20>>2]=T;if(!T)break}h=c[14424]|0;if(T>>>0<h>>>0)ra();c[T+24>>2]=d;p=c[S+16>>2]|0;do if(p|0)if(p>>>0<h>>>0)ra();else{c[T+16>>2]=p;c[p+24>>2]=T;break}while(0);p=c[S+20>>2]|0;if(p|0)if(p>>>0<(c[14424]|0)>>>0)ra();else{c[T+20>>2]=p;c[p+24>>2]=T;break}}while(0);do if(R>>>0>=16){c[S+4>>2]=f|3;c[i+4>>2]=R|1;c[i+R>>2]=R;d=R>>>3;if(R>>>0<256){p=57720+(d<<1<<2)|0;h=c[14420]|0;b=1<<d;if(h&b){d=p+8|0;e=c[d>>2]|0;if(e>>>0<(c[14424]|0)>>>0)ra();else{Y=d;Z=e}}else{c[14420]=h|b;Y=p+8|0;Z=p}c[Y>>2]=i;c[Z+12>>2]=i;c[i+8>>2]=Z;c[i+12>>2]=p;break}p=R>>>8;if(p)if(R>>>0>16777215)_=31;else{b=(p+1048320|0)>>>16&8;h=p<<b;p=(h+520192|0)>>>16&4;e=h<<p;h=(e+245760|0)>>>16&2;d=14-(p|b|h)+(e<<h>>>15)|0;_=R>>>(d+7|0)&1|d<<1}else _=0;d=57984+(_<<2)|0;c[i+28>>2]=_;h=i+16|0;c[h+4>>2]=0;c[h>>2]=0;h=c[14421]|0;e=1<<_;if(!(h&e)){c[14421]=h|e;c[d>>2]=i;c[i+24>>2]=d;c[i+12>>2]=i;c[i+8>>2]=i;break}e=R<<((_|0)==31?0:25-(_>>>1)|0);h=c[d>>2]|0;while(1){if((c[h+4>>2]&-8|0)==(R|0)){$=h;K=148;break}d=h+16+(e>>>31<<2)|0;b=c[d>>2]|0;if(!b){aa=d;ba=h;K=145;break}else{e=e<<1;h=b}}if((K|0)==145)if(aa>>>0<(c[14424]|0)>>>0)ra();else{c[aa>>2]=i;c[i+24>>2]=ba;c[i+12>>2]=i;c[i+8>>2]=i;break}else if((K|0)==148){h=$+8|0;e=c[h>>2]|0;b=c[14424]|0;if(e>>>0>=b>>>0&$>>>0>=b>>>0){c[e+12>>2]=i;c[h>>2]=i;c[i+8>>2]=e;c[i+12>>2]=$;c[i+24>>2]=0;break}else ra()}}else{e=R+f|0;c[S+4>>2]=e|3;h=S+e+4|0;c[h>>2]=c[h>>2]|1}while(0);n=S+8|0;return n|0}else F=f}else F=f}else F=-1;while(0);S=c[14422]|0;if(S>>>0>=F>>>0){R=S-F|0;$=c[14425]|0;if(R>>>0>15){ba=$+F|0;c[14425]=ba;c[14422]=R;c[ba+4>>2]=R|1;c[ba+R>>2]=R;c[$+4>>2]=F|3}else{c[14422]=0;c[14425]=0;c[$+4>>2]=S|3;R=$+S+4|0;c[R>>2]=c[R>>2]|1}n=$+8|0;return n|0}$=c[14423]|0;if($>>>0>F>>>0){R=$-F|0;c[14423]=R;$=c[14426]|0;S=$+F|0;c[14426]=S;c[S+4>>2]=R|1;c[$+4>>2]=F|3;n=$+8|0;return n|0}do if(!(c[14538]|0)){$=oa(30)|0;if(!($+-1&$)){c[14540]=$;c[14539]=$;c[14541]=-1;c[14542]=-1;c[14543]=0;c[14531]=0;c[14538]=(ua(0)|0)&-16^1431655768;break}else ra()}while(0);$=F+48|0;R=c[14540]|0;S=F+47|0;ba=R+S|0;aa=0-R|0;R=ba&aa;if(R>>>0<=F>>>0){n=0;return n|0}_=c[14530]|0;if(_|0?(Z=c[14528]|0,Y=Z+R|0,Y>>>0<=Z>>>0|Y>>>0>_>>>0):0){n=0;return n|0}b:do if(!(c[14531]&4)){_=c[14426]|0;c:do if(_){Y=58128;while(1){Z=c[Y>>2]|0;if(Z>>>0<=_>>>0?(T=Y+4|0,(Z+(c[T>>2]|0)|0)>>>0>_>>>0):0){ca=Y;da=T;break}Y=c[Y+8>>2]|0;if(!Y){K=173;break c}}Y=ba-(c[14423]|0)&aa;if(Y>>>0<2147483647){T=ta(Y|0)|0;if((T|0)==((c[ca>>2]|0)+(c[da>>2]|0)|0)){if((T|0)!=(-1|0)){ea=T;fa=Y;K=193;break b}}else{ga=T;ha=Y;K=183}}}else K=173;while(0);do if((K|0)==173?(_=ta(0)|0,(_|0)!=(-1|0)):0){f=_;Y=c[14539]|0;T=Y+-1|0;if(!(T&f))ia=R;else ia=R-f+(T+f&0-Y)|0;Y=c[14528]|0;f=Y+ia|0;if(ia>>>0>F>>>0&ia>>>0<2147483647){T=c[14530]|0;if(T|0?f>>>0<=Y>>>0|f>>>0>T>>>0:0)break;T=ta(ia|0)|0;if((T|0)==(_|0)){ea=_;fa=ia;K=193;break b}else{ga=T;ha=ia;K=183}}}while(0);d:do if((K|0)==183){T=0-ha|0;do if($>>>0>ha>>>0&(ha>>>0<2147483647&(ga|0)!=(-1|0))?(_=c[14540]|0,f=S-ha+_&0-_,f>>>0<2147483647):0)if((ta(f|0)|0)==(-1|0)){ta(T|0)|0;break d}else{ja=f+ha|0;break}else ja=ha;while(0);if((ga|0)!=(-1|0)){ea=ga;fa=ja;K=193;break b}}while(0);c[14531]=c[14531]|4;K=190}else K=190;while(0);if((((K|0)==190?R>>>0<2147483647:0)?(ja=ta(R|0)|0,R=ta(0)|0,ja>>>0<R>>>0&((ja|0)!=(-1|0)&(R|0)!=(-1|0))):0)?(ga=R-ja|0,ga>>>0>(F+40|0)>>>0):0){ea=ja;fa=ga;K=193}if((K|0)==193){ga=(c[14528]|0)+fa|0;c[14528]=ga;if(ga>>>0>(c[14529]|0)>>>0)c[14529]=ga;ga=c[14426]|0;do if(ga){ja=58128;do{R=c[ja>>2]|0;ha=ja+4|0;S=c[ha>>2]|0;if((ea|0)==(R+S|0)){ka=R;la=ha;ma=S;na=ja;K=203;break}ja=c[ja+8>>2]|0}while((ja|0)!=0);if(((K|0)==203?(c[na+12>>2]&8|0)==0:0)?ga>>>0<ea>>>0&ga>>>0>=ka>>>0:0){c[la>>2]=ma+fa;ja=ga+8|0;S=(ja&7|0)==0?0:0-ja&7;ja=ga+S|0;ha=fa-S+(c[14423]|0)|0;c[14426]=ja;c[14423]=ha;c[ja+4>>2]=ha|1;c[ja+ha+4>>2]=40;c[14427]=c[14542];break}ha=c[14424]|0;if(ea>>>0<ha>>>0){c[14424]=ea;pa=ea}else pa=ha;ha=ea+fa|0;ja=58128;while(1){if((c[ja>>2]|0)==(ha|0)){qa=ja;sa=ja;K=211;break}ja=c[ja+8>>2]|0;if(!ja){va=58128;break}}if((K|0)==211)if(!(c[sa+12>>2]&8)){c[qa>>2]=ea;ja=sa+4|0;c[ja>>2]=(c[ja>>2]|0)+fa;ja=ea+8|0;S=ea+((ja&7|0)==0?0:0-ja&7)|0;ja=ha+8|0;R=ha+((ja&7|0)==0?0:0-ja&7)|0;ja=S+F|0;$=R-S-F|0;c[S+4>>2]=F|3;do if((R|0)!=(ga|0)){if((R|0)==(c[14425]|0)){ia=(c[14422]|0)+$|0;c[14422]=ia;c[14425]=ja;c[ja+4>>2]=ia|1;c[ja+ia>>2]=ia;break}ia=c[R+4>>2]|0;if((ia&3|0)==1){da=ia&-8;ca=ia>>>3;e:do if(ia>>>0>=256){aa=c[R+24>>2]|0;ba=c[R+12>>2]|0;do if((ba|0)==(R|0)){T=R+16|0;f=T+4|0;_=c[f>>2]|0;if(!_){Y=c[T>>2]|0;if(!Y){wa=0;break}else{xa=Y;ya=T}}else{xa=_;ya=f}while(1){f=xa+20|0;_=c[f>>2]|0;if(_|0){xa=_;ya=f;continue}f=xa+16|0;_=c[f>>2]|0;if(!_){za=xa;Aa=ya;break}else{xa=_;ya=f}}if(Aa>>>0<pa>>>0)ra();else{c[Aa>>2]=0;wa=za;break}}else{f=c[R+8>>2]|0;if(f>>>0<pa>>>0)ra();_=f+12|0;if((c[_>>2]|0)!=(R|0))ra();T=ba+8|0;if((c[T>>2]|0)==(R|0)){c[_>>2]=ba;c[T>>2]=f;wa=ba;break}else ra()}while(0);if(!aa)break;ba=c[R+28>>2]|0;f=57984+(ba<<2)|0;do if((R|0)!=(c[f>>2]|0)){if(aa>>>0<(c[14424]|0)>>>0)ra();T=aa+16|0;if((c[T>>2]|0)==(R|0))c[T>>2]=wa;else c[aa+20>>2]=wa;if(!wa)break e}else{c[f>>2]=wa;if(wa|0)break;c[14421]=c[14421]&~(1<<ba);break e}while(0);ba=c[14424]|0;if(wa>>>0<ba>>>0)ra();c[wa+24>>2]=aa;f=R+16|0;T=c[f>>2]|0;do if(T|0)if(T>>>0<ba>>>0)ra();else{c[wa+16>>2]=T;c[T+24>>2]=wa;break}while(0);T=c[f+4>>2]|0;if(!T)break;if(T>>>0<(c[14424]|0)>>>0)ra();else{c[wa+20>>2]=T;c[T+24>>2]=wa;break}}else{T=c[R+8>>2]|0;ba=c[R+12>>2]|0;aa=57720+(ca<<1<<2)|0;do if((T|0)!=(aa|0)){if(T>>>0<pa>>>0)ra();if((c[T+12>>2]|0)==(R|0))break;ra()}while(0);if((ba|0)==(T|0)){c[14420]=c[14420]&~(1<<ca);break}do if((ba|0)==(aa|0))Ba=ba+8|0;else{if(ba>>>0<pa>>>0)ra();f=ba+8|0;if((c[f>>2]|0)==(R|0)){Ba=f;break}ra()}while(0);c[T+12>>2]=ba;c[Ba>>2]=T}while(0);Ca=R+da|0;Da=da+$|0}else{Ca=R;Da=$}ca=Ca+4|0;c[ca>>2]=c[ca>>2]&-2;c[ja+4>>2]=Da|1;c[ja+Da>>2]=Da;ca=Da>>>3;if(Da>>>0<256){ia=57720+(ca<<1<<2)|0;aa=c[14420]|0;f=1<<ca;do if(!(aa&f)){c[14420]=aa|f;Ea=ia+8|0;Fa=ia}else{ca=ia+8|0;_=c[ca>>2]|0;if(_>>>0>=(c[14424]|0)>>>0){Ea=ca;Fa=_;break}ra()}while(0);c[Ea>>2]=ja;c[Fa+12>>2]=ja;c[ja+8>>2]=Fa;c[ja+12>>2]=ia;break}f=Da>>>8;do if(!f)Ga=0;else{if(Da>>>0>16777215){Ga=31;break}aa=(f+1048320|0)>>>16&8;da=f<<aa;_=(da+520192|0)>>>16&4;ca=da<<_;da=(ca+245760|0)>>>16&2;Y=14-(_|aa|da)+(ca<<da>>>15)|0;Ga=Da>>>(Y+7|0)&1|Y<<1}while(0);f=57984+(Ga<<2)|0;c[ja+28>>2]=Ga;ia=ja+16|0;c[ia+4>>2]=0;c[ia>>2]=0;ia=c[14421]|0;Y=1<<Ga;if(!(ia&Y)){c[14421]=ia|Y;c[f>>2]=ja;c[ja+24>>2]=f;c[ja+12>>2]=ja;c[ja+8>>2]=ja;break}Y=Da<<((Ga|0)==31?0:25-(Ga>>>1)|0);ia=c[f>>2]|0;while(1){if((c[ia+4>>2]&-8|0)==(Da|0)){Ha=ia;K=281;break}f=ia+16+(Y>>>31<<2)|0;da=c[f>>2]|0;if(!da){Ia=f;Ja=ia;K=278;break}else{Y=Y<<1;ia=da}}if((K|0)==278)if(Ia>>>0<(c[14424]|0)>>>0)ra();else{c[Ia>>2]=ja;c[ja+24>>2]=Ja;c[ja+12>>2]=ja;c[ja+8>>2]=ja;break}else if((K|0)==281){ia=Ha+8|0;Y=c[ia>>2]|0;da=c[14424]|0;if(Y>>>0>=da>>>0&Ha>>>0>=da>>>0){c[Y+12>>2]=ja;c[ia>>2]=ja;c[ja+8>>2]=Y;c[ja+12>>2]=Ha;c[ja+24>>2]=0;break}else ra()}}else{Y=(c[14423]|0)+$|0;c[14423]=Y;c[14426]=ja;c[ja+4>>2]=Y|1}while(0);n=S+8|0;return n|0}else va=58128;while(1){ja=c[va>>2]|0;if(ja>>>0<=ga>>>0?($=ja+(c[va+4>>2]|0)|0,$>>>0>ga>>>0):0){Ka=$;break}va=c[va+8>>2]|0}S=Ka+-47|0;$=S+8|0;ja=S+(($&7|0)==0?0:0-$&7)|0;$=ga+16|0;S=ja>>>0<$>>>0?ga:ja;ja=S+8|0;R=ea+8|0;ha=(R&7|0)==0?0:0-R&7;R=ea+ha|0;Y=fa+-40-ha|0;c[14426]=R;c[14423]=Y;c[R+4>>2]=Y|1;c[R+Y+4>>2]=40;c[14427]=c[14542];Y=S+4|0;c[Y>>2]=27;c[ja>>2]=c[14532];c[ja+4>>2]=c[14533];c[ja+8>>2]=c[14534];c[ja+12>>2]=c[14535];c[14532]=ea;c[14533]=fa;c[14535]=0;c[14534]=ja;ja=S+24|0;do{ja=ja+4|0;c[ja>>2]=7}while((ja+4|0)>>>0<Ka>>>0);if((S|0)!=(ga|0)){ja=S-ga|0;c[Y>>2]=c[Y>>2]&-2;c[ga+4>>2]=ja|1;c[S>>2]=ja;R=ja>>>3;if(ja>>>0<256){ha=57720+(R<<1<<2)|0;ia=c[14420]|0;da=1<<R;if(ia&da){R=ha+8|0;f=c[R>>2]|0;if(f>>>0<(c[14424]|0)>>>0)ra();else{La=R;Ma=f}}else{c[14420]=ia|da;La=ha+8|0;Ma=ha}c[La>>2]=ga;c[Ma+12>>2]=ga;c[ga+8>>2]=Ma;c[ga+12>>2]=ha;break}ha=ja>>>8;if(ha)if(ja>>>0>16777215)Na=31;else{da=(ha+1048320|0)>>>16&8;ia=ha<<da;ha=(ia+520192|0)>>>16&4;f=ia<<ha;ia=(f+245760|0)>>>16&2;R=14-(ha|da|ia)+(f<<ia>>>15)|0;Na=ja>>>(R+7|0)&1|R<<1}else Na=0;R=57984+(Na<<2)|0;c[ga+28>>2]=Na;c[ga+20>>2]=0;c[$>>2]=0;ia=c[14421]|0;f=1<<Na;if(!(ia&f)){c[14421]=ia|f;c[R>>2]=ga;c[ga+24>>2]=R;c[ga+12>>2]=ga;c[ga+8>>2]=ga;break}f=ja<<((Na|0)==31?0:25-(Na>>>1)|0);ia=c[R>>2]|0;while(1){if((c[ia+4>>2]&-8|0)==(ja|0)){Oa=ia;K=307;break}R=ia+16+(f>>>31<<2)|0;da=c[R>>2]|0;if(!da){Pa=R;Qa=ia;K=304;break}else{f=f<<1;ia=da}}if((K|0)==304)if(Pa>>>0<(c[14424]|0)>>>0)ra();else{c[Pa>>2]=ga;c[ga+24>>2]=Qa;c[ga+12>>2]=ga;c[ga+8>>2]=ga;break}else if((K|0)==307){ia=Oa+8|0;f=c[ia>>2]|0;ja=c[14424]|0;if(f>>>0>=ja>>>0&Oa>>>0>=ja>>>0){c[f+12>>2]=ga;c[ia>>2]=ga;c[ga+8>>2]=f;c[ga+12>>2]=Oa;c[ga+24>>2]=0;break}else ra()}}}else{f=c[14424]|0;if((f|0)==0|ea>>>0<f>>>0)c[14424]=ea;c[14532]=ea;c[14533]=fa;c[14535]=0;c[14429]=c[14538];c[14428]=-1;f=0;do{ia=57720+(f<<1<<2)|0;c[ia+12>>2]=ia;c[ia+8>>2]=ia;f=f+1|0}while((f|0)!=32);f=ea+8|0;ia=(f&7|0)==0?0:0-f&7;f=ea+ia|0;ja=fa+-40-ia|0;c[14426]=f;c[14423]=ja;c[f+4>>2]=ja|1;c[f+ja+4>>2]=40;c[14427]=c[14542]}while(0);fa=c[14423]|0;if(fa>>>0>F>>>0){ea=fa-F|0;c[14423]=ea;fa=c[14426]|0;ga=fa+F|0;c[14426]=ga;c[ga+4>>2]=ea|1;c[fa+4>>2]=F|3;n=fa+8|0;return n|0}}c[(Wc()|0)>>2]=12;n=0;return n|0}function fd(a){a=a|0;var b=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0,K=0,L=0;if(!a)return;b=a+-8|0;d=c[14424]|0;if(b>>>0<d>>>0)ra();e=c[a+-4>>2]|0;a=e&3;if((a|0)==1)ra();f=e&-8;g=b+f|0;do if(!(e&1)){h=c[b>>2]|0;if(!a)return;i=b+(0-h)|0;j=h+f|0;if(i>>>0<d>>>0)ra();if((i|0)==(c[14425]|0)){k=g+4|0;l=c[k>>2]|0;if((l&3|0)!=3){m=i;n=j;break}c[14422]=j;c[k>>2]=l&-2;c[i+4>>2]=j|1;c[i+j>>2]=j;return}l=h>>>3;if(h>>>0<256){h=c[i+8>>2]|0;k=c[i+12>>2]|0;o=57720+(l<<1<<2)|0;if((h|0)!=(o|0)){if(h>>>0<d>>>0)ra();if((c[h+12>>2]|0)!=(i|0))ra()}if((k|0)==(h|0)){c[14420]=c[14420]&~(1<<l);m=i;n=j;break}if((k|0)!=(o|0)){if(k>>>0<d>>>0)ra();o=k+8|0;if((c[o>>2]|0)==(i|0))p=o;else ra()}else p=k+8|0;c[h+12>>2]=k;c[p>>2]=h;m=i;n=j;break}h=c[i+24>>2]|0;k=c[i+12>>2]|0;do if((k|0)==(i|0)){o=i+16|0;l=o+4|0;q=c[l>>2]|0;if(!q){r=c[o>>2]|0;if(!r){s=0;break}else{t=r;u=o}}else{t=q;u=l}while(1){l=t+20|0;q=c[l>>2]|0;if(q|0){t=q;u=l;continue}l=t+16|0;q=c[l>>2]|0;if(!q){v=t;w=u;break}else{t=q;u=l}}if(w>>>0<d>>>0)ra();else{c[w>>2]=0;s=v;break}}else{l=c[i+8>>2]|0;if(l>>>0<d>>>0)ra();q=l+12|0;if((c[q>>2]|0)!=(i|0))ra();o=k+8|0;if((c[o>>2]|0)==(i|0)){c[q>>2]=k;c[o>>2]=l;s=k;break}else ra()}while(0);if(h){k=c[i+28>>2]|0;l=57984+(k<<2)|0;if((i|0)==(c[l>>2]|0)){c[l>>2]=s;if(!s){c[14421]=c[14421]&~(1<<k);m=i;n=j;break}}else{if(h>>>0<(c[14424]|0)>>>0)ra();k=h+16|0;if((c[k>>2]|0)==(i|0))c[k>>2]=s;else c[h+20>>2]=s;if(!s){m=i;n=j;break}}k=c[14424]|0;if(s>>>0<k>>>0)ra();c[s+24>>2]=h;l=i+16|0;o=c[l>>2]|0;do if(o|0)if(o>>>0<k>>>0)ra();else{c[s+16>>2]=o;c[o+24>>2]=s;break}while(0);o=c[l+4>>2]|0;if(o)if(o>>>0<(c[14424]|0)>>>0)ra();else{c[s+20>>2]=o;c[o+24>>2]=s;m=i;n=j;break}else{m=i;n=j}}else{m=i;n=j}}else{m=b;n=f}while(0);if(m>>>0>=g>>>0)ra();f=g+4|0;b=c[f>>2]|0;if(!(b&1))ra();if(!(b&2)){if((g|0)==(c[14426]|0)){s=(c[14423]|0)+n|0;c[14423]=s;c[14426]=m;c[m+4>>2]=s|1;if((m|0)!=(c[14425]|0))return;c[14425]=0;c[14422]=0;return}if((g|0)==(c[14425]|0)){s=(c[14422]|0)+n|0;c[14422]=s;c[14425]=m;c[m+4>>2]=s|1;c[m+s>>2]=s;return}s=(b&-8)+n|0;d=b>>>3;do if(b>>>0>=256){v=c[g+24>>2]|0;w=c[g+12>>2]|0;do if((w|0)==(g|0)){u=g+16|0;t=u+4|0;p=c[t>>2]|0;if(!p){a=c[u>>2]|0;if(!a){x=0;break}else{y=a;z=u}}else{y=p;z=t}while(1){t=y+20|0;p=c[t>>2]|0;if(p|0){y=p;z=t;continue}t=y+16|0;p=c[t>>2]|0;if(!p){A=y;B=z;break}else{y=p;z=t}}if(B>>>0<(c[14424]|0)>>>0)ra();else{c[B>>2]=0;x=A;break}}else{t=c[g+8>>2]|0;if(t>>>0<(c[14424]|0)>>>0)ra();p=t+12|0;if((c[p>>2]|0)!=(g|0))ra();u=w+8|0;if((c[u>>2]|0)==(g|0)){c[p>>2]=w;c[u>>2]=t;x=w;break}else ra()}while(0);if(v|0){w=c[g+28>>2]|0;j=57984+(w<<2)|0;if((g|0)==(c[j>>2]|0)){c[j>>2]=x;if(!x){c[14421]=c[14421]&~(1<<w);break}}else{if(v>>>0<(c[14424]|0)>>>0)ra();w=v+16|0;if((c[w>>2]|0)==(g|0))c[w>>2]=x;else c[v+20>>2]=x;if(!x)break}w=c[14424]|0;if(x>>>0<w>>>0)ra();c[x+24>>2]=v;j=g+16|0;i=c[j>>2]|0;do if(i|0)if(i>>>0<w>>>0)ra();else{c[x+16>>2]=i;c[i+24>>2]=x;break}while(0);i=c[j+4>>2]|0;if(i|0)if(i>>>0<(c[14424]|0)>>>0)ra();else{c[x+20>>2]=i;c[i+24>>2]=x;break}}}else{i=c[g+8>>2]|0;w=c[g+12>>2]|0;v=57720+(d<<1<<2)|0;if((i|0)!=(v|0)){if(i>>>0<(c[14424]|0)>>>0)ra();if((c[i+12>>2]|0)!=(g|0))ra()}if((w|0)==(i|0)){c[14420]=c[14420]&~(1<<d);break}if((w|0)!=(v|0)){if(w>>>0<(c[14424]|0)>>>0)ra();v=w+8|0;if((c[v>>2]|0)==(g|0))C=v;else ra()}else C=w+8|0;c[i+12>>2]=w;c[C>>2]=i}while(0);c[m+4>>2]=s|1;c[m+s>>2]=s;if((m|0)==(c[14425]|0)){c[14422]=s;return}else D=s}else{c[f>>2]=b&-2;c[m+4>>2]=n|1;c[m+n>>2]=n;D=n}n=D>>>3;if(D>>>0<256){b=57720+(n<<1<<2)|0;f=c[14420]|0;s=1<<n;if(f&s){n=b+8|0;C=c[n>>2]|0;if(C>>>0<(c[14424]|0)>>>0)ra();else{E=n;F=C}}else{c[14420]=f|s;E=b+8|0;F=b}c[E>>2]=m;c[F+12>>2]=m;c[m+8>>2]=F;c[m+12>>2]=b;return}b=D>>>8;if(b)if(D>>>0>16777215)G=31;else{F=(b+1048320|0)>>>16&8;E=b<<F;b=(E+520192|0)>>>16&4;s=E<<b;E=(s+245760|0)>>>16&2;f=14-(b|F|E)+(s<<E>>>15)|0;G=D>>>(f+7|0)&1|f<<1}else G=0;f=57984+(G<<2)|0;c[m+28>>2]=G;c[m+20>>2]=0;c[m+16>>2]=0;E=c[14421]|0;s=1<<G;do if(E&s){F=D<<((G|0)==31?0:25-(G>>>1)|0);b=c[f>>2]|0;while(1){if((c[b+4>>2]&-8|0)==(D|0)){H=b;I=130;break}C=b+16+(F>>>31<<2)|0;n=c[C>>2]|0;if(!n){J=C;K=b;I=127;break}else{F=F<<1;b=n}}if((I|0)==127)if(J>>>0<(c[14424]|0)>>>0)ra();else{c[J>>2]=m;c[m+24>>2]=K;c[m+12>>2]=m;c[m+8>>2]=m;break}else if((I|0)==130){b=H+8|0;F=c[b>>2]|0;j=c[14424]|0;if(F>>>0>=j>>>0&H>>>0>=j>>>0){c[F+12>>2]=m;c[b>>2]=m;c[m+8>>2]=F;c[m+12>>2]=H;c[m+24>>2]=0;break}else ra()}}else{c[14421]=E|s;c[f>>2]=m;c[m+24>>2]=f;c[m+12>>2]=m;c[m+8>>2]=m}while(0);m=(c[14428]|0)+-1|0;c[14428]=m;if(!m)L=58136;else return;while(1){m=c[L>>2]|0;if(!m)break;else L=m+8|0}c[14428]=-1;return}function gd(a,b){a=a|0;b=b|0;var d=0,e=0;if(a){d=_(b,a)|0;if((b|a)>>>0>65535)e=((d>>>0)/(a>>>0)|0|0)==(b|0)?d:-1;else e=d}else e=0;d=ed(e)|0;if(!d)return d|0;if(!(c[d+-4>>2]&3))return d|0;md(d|0,0,e|0)|0;return d|0}function hd(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0;if(!a){d=ed(b)|0;return d|0}if(b>>>0>4294967231){c[(Wc()|0)>>2]=12;d=0;return d|0}e=id(a+-8|0,b>>>0<11?16:b+11&-8)|0;if(e|0){d=e+8|0;return d|0}e=ed(b)|0;if(!e){d=0;return d|0}f=c[a+-4>>2]|0;g=(f&-8)-((f&3|0)==0?8:4)|0;od(e|0,a|0,(g>>>0<b>>>0?g:b)|0)|0;fd(a);d=e;return d|0}function id(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0;d=a+4|0;e=c[d>>2]|0;f=e&-8;g=a+f|0;h=c[14424]|0;i=e&3;if(!((i|0)!=1&a>>>0>=h>>>0&a>>>0<g>>>0))ra();j=c[g+4>>2]|0;if(!(j&1))ra();if(!i){if(b>>>0<256){k=0;return k|0}if(f>>>0>=(b+4|0)>>>0?(f-b|0)>>>0<=c[14540]<<1>>>0:0){k=a;return k|0}k=0;return k|0}if(f>>>0>=b>>>0){i=f-b|0;if(i>>>0<=15){k=a;return k|0}l=a+b|0;c[d>>2]=e&1|b|2;c[l+4>>2]=i|3;m=l+i+4|0;c[m>>2]=c[m>>2]|1;jd(l,i);k=a;return k|0}if((g|0)==(c[14426]|0)){i=(c[14423]|0)+f|0;if(i>>>0<=b>>>0){k=0;return k|0}l=i-b|0;i=a+b|0;c[d>>2]=e&1|b|2;c[i+4>>2]=l|1;c[14426]=i;c[14423]=l;k=a;return k|0}if((g|0)==(c[14425]|0)){l=(c[14422]|0)+f|0;if(l>>>0<b>>>0){k=0;return k|0}i=l-b|0;if(i>>>0>15){m=a+b|0;n=m+i|0;c[d>>2]=e&1|b|2;c[m+4>>2]=i|1;c[n>>2]=i;o=n+4|0;c[o>>2]=c[o>>2]&-2;p=m;q=i}else{c[d>>2]=e&1|l|2;i=a+l+4|0;c[i>>2]=c[i>>2]|1;p=0;q=0}c[14422]=q;c[14425]=p;k=a;return k|0}if(j&2|0){k=0;return k|0}p=(j&-8)+f|0;if(p>>>0<b>>>0){k=0;return k|0}f=p-b|0;q=j>>>3;do if(j>>>0>=256){i=c[g+24>>2]|0;l=c[g+12>>2]|0;do if((l|0)==(g|0)){m=g+16|0;o=m+4|0;n=c[o>>2]|0;if(!n){r=c[m>>2]|0;if(!r){s=0;break}else{t=r;u=m}}else{t=n;u=o}while(1){o=t+20|0;n=c[o>>2]|0;if(n|0){t=n;u=o;continue}o=t+16|0;n=c[o>>2]|0;if(!n){v=t;w=u;break}else{t=n;u=o}}if(w>>>0<h>>>0)ra();else{c[w>>2]=0;s=v;break}}else{o=c[g+8>>2]|0;if(o>>>0<h>>>0)ra();n=o+12|0;if((c[n>>2]|0)!=(g|0))ra();m=l+8|0;if((c[m>>2]|0)==(g|0)){c[n>>2]=l;c[m>>2]=o;s=l;break}else ra()}while(0);if(i|0){l=c[g+28>>2]|0;o=57984+(l<<2)|0;if((g|0)==(c[o>>2]|0)){c[o>>2]=s;if(!s){c[14421]=c[14421]&~(1<<l);break}}else{if(i>>>0<(c[14424]|0)>>>0)ra();l=i+16|0;if((c[l>>2]|0)==(g|0))c[l>>2]=s;else c[i+20>>2]=s;if(!s)break}l=c[14424]|0;if(s>>>0<l>>>0)ra();c[s+24>>2]=i;o=g+16|0;m=c[o>>2]|0;do if(m|0)if(m>>>0<l>>>0)ra();else{c[s+16>>2]=m;c[m+24>>2]=s;break}while(0);m=c[o+4>>2]|0;if(m|0)if(m>>>0<(c[14424]|0)>>>0)ra();else{c[s+20>>2]=m;c[m+24>>2]=s;break}}}else{m=c[g+8>>2]|0;l=c[g+12>>2]|0;i=57720+(q<<1<<2)|0;if((m|0)!=(i|0)){if(m>>>0<h>>>0)ra();if((c[m+12>>2]|0)!=(g|0))ra()}if((l|0)==(m|0)){c[14420]=c[14420]&~(1<<q);break}if((l|0)!=(i|0)){if(l>>>0<h>>>0)ra();i=l+8|0;if((c[i>>2]|0)==(g|0))x=i;else ra()}else x=l+8|0;c[m+12>>2]=l;c[x>>2]=m}while(0);if(f>>>0<16){c[d>>2]=p|e&1|2;x=a+p+4|0;c[x>>2]=c[x>>2]|1;k=a;return k|0}else{x=a+b|0;c[d>>2]=e&1|b|2;c[x+4>>2]=f|3;b=x+f+4|0;c[b>>2]=c[b>>2]|1;jd(x,f);k=a;return k|0}return 0}function jd(a,b){a=a|0;b=b|0;var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,F=0,G=0,H=0,I=0,J=0;d=a+b|0;e=c[a+4>>2]|0;do if(!(e&1)){f=c[a>>2]|0;if(!(e&3))return;g=a+(0-f)|0;h=f+b|0;i=c[14424]|0;if(g>>>0<i>>>0)ra();if((g|0)==(c[14425]|0)){j=d+4|0;k=c[j>>2]|0;if((k&3|0)!=3){l=g;m=h;break}c[14422]=h;c[j>>2]=k&-2;c[g+4>>2]=h|1;c[g+h>>2]=h;return}k=f>>>3;if(f>>>0<256){f=c[g+8>>2]|0;j=c[g+12>>2]|0;n=57720+(k<<1<<2)|0;if((f|0)!=(n|0)){if(f>>>0<i>>>0)ra();if((c[f+12>>2]|0)!=(g|0))ra()}if((j|0)==(f|0)){c[14420]=c[14420]&~(1<<k);l=g;m=h;break}if((j|0)!=(n|0)){if(j>>>0<i>>>0)ra();n=j+8|0;if((c[n>>2]|0)==(g|0))o=n;else ra()}else o=j+8|0;c[f+12>>2]=j;c[o>>2]=f;l=g;m=h;break}f=c[g+24>>2]|0;j=c[g+12>>2]|0;do if((j|0)==(g|0)){n=g+16|0;k=n+4|0;p=c[k>>2]|0;if(!p){q=c[n>>2]|0;if(!q){r=0;break}else{s=q;t=n}}else{s=p;t=k}while(1){k=s+20|0;p=c[k>>2]|0;if(p|0){s=p;t=k;continue}k=s+16|0;p=c[k>>2]|0;if(!p){u=s;v=t;break}else{s=p;t=k}}if(v>>>0<i>>>0)ra();else{c[v>>2]=0;r=u;break}}else{k=c[g+8>>2]|0;if(k>>>0<i>>>0)ra();p=k+12|0;if((c[p>>2]|0)!=(g|0))ra();n=j+8|0;if((c[n>>2]|0)==(g|0)){c[p>>2]=j;c[n>>2]=k;r=j;break}else ra()}while(0);if(f){j=c[g+28>>2]|0;i=57984+(j<<2)|0;if((g|0)==(c[i>>2]|0)){c[i>>2]=r;if(!r){c[14421]=c[14421]&~(1<<j);l=g;m=h;break}}else{if(f>>>0<(c[14424]|0)>>>0)ra();j=f+16|0;if((c[j>>2]|0)==(g|0))c[j>>2]=r;else c[f+20>>2]=r;if(!r){l=g;m=h;break}}j=c[14424]|0;if(r>>>0<j>>>0)ra();c[r+24>>2]=f;i=g+16|0;k=c[i>>2]|0;do if(k|0)if(k>>>0<j>>>0)ra();else{c[r+16>>2]=k;c[k+24>>2]=r;break}while(0);k=c[i+4>>2]|0;if(k)if(k>>>0<(c[14424]|0)>>>0)ra();else{c[r+20>>2]=k;c[k+24>>2]=r;l=g;m=h;break}else{l=g;m=h}}else{l=g;m=h}}else{l=a;m=b}while(0);b=c[14424]|0;if(d>>>0<b>>>0)ra();a=d+4|0;r=c[a>>2]|0;if(!(r&2)){if((d|0)==(c[14426]|0)){u=(c[14423]|0)+m|0;c[14423]=u;c[14426]=l;c[l+4>>2]=u|1;if((l|0)!=(c[14425]|0))return;c[14425]=0;c[14422]=0;return}if((d|0)==(c[14425]|0)){u=(c[14422]|0)+m|0;c[14422]=u;c[14425]=l;c[l+4>>2]=u|1;c[l+u>>2]=u;return}u=(r&-8)+m|0;v=r>>>3;do if(r>>>0>=256){t=c[d+24>>2]|0;s=c[d+12>>2]|0;do if((s|0)==(d|0)){o=d+16|0;e=o+4|0;k=c[e>>2]|0;if(!k){j=c[o>>2]|0;if(!j){w=0;break}else{x=j;y=o}}else{x=k;y=e}while(1){e=x+20|0;k=c[e>>2]|0;if(k|0){x=k;y=e;continue}e=x+16|0;k=c[e>>2]|0;if(!k){z=x;A=y;break}else{x=k;y=e}}if(A>>>0<b>>>0)ra();else{c[A>>2]=0;w=z;break}}else{e=c[d+8>>2]|0;if(e>>>0<b>>>0)ra();k=e+12|0;if((c[k>>2]|0)!=(d|0))ra();o=s+8|0;if((c[o>>2]|0)==(d|0)){c[k>>2]=s;c[o>>2]=e;w=s;break}else ra()}while(0);if(t|0){s=c[d+28>>2]|0;h=57984+(s<<2)|0;if((d|0)==(c[h>>2]|0)){c[h>>2]=w;if(!w){c[14421]=c[14421]&~(1<<s);break}}else{if(t>>>0<(c[14424]|0)>>>0)ra();s=t+16|0;if((c[s>>2]|0)==(d|0))c[s>>2]=w;else c[t+20>>2]=w;if(!w)break}s=c[14424]|0;if(w>>>0<s>>>0)ra();c[w+24>>2]=t;h=d+16|0;g=c[h>>2]|0;do if(g|0)if(g>>>0<s>>>0)ra();else{c[w+16>>2]=g;c[g+24>>2]=w;break}while(0);g=c[h+4>>2]|0;if(g|0)if(g>>>0<(c[14424]|0)>>>0)ra();else{c[w+20>>2]=g;c[g+24>>2]=w;break}}}else{g=c[d+8>>2]|0;s=c[d+12>>2]|0;t=57720+(v<<1<<2)|0;if((g|0)!=(t|0)){if(g>>>0<b>>>0)ra();if((c[g+12>>2]|0)!=(d|0))ra()}if((s|0)==(g|0)){c[14420]=c[14420]&~(1<<v);break}if((s|0)!=(t|0)){if(s>>>0<b>>>0)ra();t=s+8|0;if((c[t>>2]|0)==(d|0))B=t;else ra()}else B=s+8|0;c[g+12>>2]=s;c[B>>2]=g}while(0);c[l+4>>2]=u|1;c[l+u>>2]=u;if((l|0)==(c[14425]|0)){c[14422]=u;return}else C=u}else{c[a>>2]=r&-2;c[l+4>>2]=m|1;c[l+m>>2]=m;C=m}m=C>>>3;if(C>>>0<256){r=57720+(m<<1<<2)|0;a=c[14420]|0;u=1<<m;if(a&u){m=r+8|0;B=c[m>>2]|0;if(B>>>0<(c[14424]|0)>>>0)ra();else{D=m;E=B}}else{c[14420]=a|u;D=r+8|0;E=r}c[D>>2]=l;c[E+12>>2]=l;c[l+8>>2]=E;c[l+12>>2]=r;return}r=C>>>8;if(r)if(C>>>0>16777215)F=31;else{E=(r+1048320|0)>>>16&8;D=r<<E;r=(D+520192|0)>>>16&4;u=D<<r;D=(u+245760|0)>>>16&2;a=14-(r|E|D)+(u<<D>>>15)|0;F=C>>>(a+7|0)&1|a<<1}else F=0;a=57984+(F<<2)|0;c[l+28>>2]=F;c[l+20>>2]=0;c[l+16>>2]=0;D=c[14421]|0;u=1<<F;if(!(D&u)){c[14421]=D|u;c[a>>2]=l;c[l+24>>2]=a;c[l+12>>2]=l;c[l+8>>2]=l;return}u=C<<((F|0)==31?0:25-(F>>>1)|0);F=c[a>>2]|0;while(1){if((c[F+4>>2]&-8|0)==(C|0)){G=F;H=127;break}a=F+16+(u>>>31<<2)|0;D=c[a>>2]|0;if(!D){I=a;J=F;H=124;break}else{u=u<<1;F=D}}if((H|0)==124){if(I>>>0<(c[14424]|0)>>>0)ra();c[I>>2]=l;c[l+24>>2]=J;c[l+12>>2]=l;c[l+8>>2]=l;return}else if((H|0)==127){H=G+8|0;J=c[H>>2]|0;I=c[14424]|0;if(!(J>>>0>=I>>>0&G>>>0>=I>>>0))ra();c[J+12>>2]=l;c[H>>2]=l;c[l+8>>2]=J;c[l+12>>2]=G;c[l+24>>2]=0;return}}function kd(){}function ld(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0;e=b-d>>>0;e=b-d-(c>>>0>a>>>0|0)>>>0;return (C=e,a-c>>>0|0)|0}function md(b,d,e){b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0;f=b+e|0;if((e|0)>=20){d=d&255;g=b&3;h=d|d<<8|d<<16|d<<24;i=f&~3;if(g){g=b+4-g|0;while((b|0)<(g|0)){a[b>>0]=d;b=b+1|0}}while((b|0)<(i|0)){c[b>>2]=h;b=b+4|0}}while((b|0)<(f|0)){a[b>>0]=d;b=b+1|0}return b-e|0}function nd(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){C=b<<c|(a&(1<<c)-1<<32-c)>>>32-c;return a<<c}C=a<<c-32;return 0}function od(b,d,e){b=b|0;d=d|0;e=e|0;var f=0;if((e|0)>=4096)return ma(b|0,d|0,e|0)|0;f=b|0;if((b&3)==(d&3)){while(b&3){if(!e)return f|0;a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}while((e|0)>=4){c[b>>2]=c[d>>2];b=b+4|0;d=d+4|0;e=e-4|0}}while((e|0)>0){a[b>>0]=a[d>>0]|0;b=b+1|0;d=d+1|0;e=e-1|0}return f|0}function pd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0;e=a+c>>>0;return (C=b+d+(e>>>0<a>>>0|0)>>>0,e|0)|0}function qd(a){a=a|0;return (a&255)<<24|(a>>8&255)<<16|(a>>16&255)<<8|a>>>24|0}function rd(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){C=b>>>c;return a>>>c|(b&(1<<c)-1)<<32-c}C=0;return b>>>c-32|0}function sd(a,b,c){a=a|0;b=b|0;c=c|0;if((c|0)<32){C=b>>c;return a>>>c|(b&(1<<c)-1)<<32-c}C=(b|0)<0?-1:0;return b>>c-32|0}function td(b){b=b|0;var c=0;c=a[m+(b&255)>>0]|0;if((c|0)<8)return c|0;c=a[m+(b>>8&255)>>0]|0;if((c|0)<8)return c+8|0;c=a[m+(b>>16&255)>>0]|0;if((c|0)<8)return c+16|0;return (a[m+(b>>>24)>>0]|0)+24|0}function ud(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0;c=a&65535;d=b&65535;e=_(d,c)|0;f=a>>>16;a=(e>>>16)+(_(d,f)|0)|0;d=b>>>16;b=_(d,c)|0;return (C=(a>>>16)+(_(d,f)|0)+(((a&65535)+b|0)>>>16)|0,a+b<<16|e&65535|0)|0}function vd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0;e=b>>31|((b|0)<0?-1:0)<<1;f=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;g=d>>31|((d|0)<0?-1:0)<<1;h=((d|0)<0?-1:0)>>31|((d|0)<0?-1:0)<<1;i=ld(e^a|0,f^b|0,e|0,f|0)|0;b=C;a=g^e;e=h^f;return ld((Ad(i,b,ld(g^c|0,h^d|0,g|0,h|0)|0,C,0)|0)^a|0,C^e|0,a|0,e|0)|0}function wd(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0,h=0,j=0,k=0,l=0,m=0;f=i;i=i+16|0;g=f|0;h=b>>31|((b|0)<0?-1:0)<<1;j=((b|0)<0?-1:0)>>31|((b|0)<0?-1:0)<<1;k=e>>31|((e|0)<0?-1:0)<<1;l=((e|0)<0?-1:0)>>31|((e|0)<0?-1:0)<<1;m=ld(h^a|0,j^b|0,h|0,j|0)|0;b=C;Ad(m,b,ld(k^d|0,l^e|0,k|0,l|0)|0,C,g)|0;l=ld(c[g>>2]^h|0,c[g+4>>2]^j|0,h|0,j|0)|0;j=C;i=f;return (C=j,l)|0}function xd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=a;a=c;c=ud(e,a)|0;f=C;return (C=(_(b,a)|0)+(_(d,e)|0)+f|f&0,c|0|0)|0}function yd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;return Ad(a,b,c,d,0)|0}function zd(a,b,d,e){a=a|0;b=b|0;d=d|0;e=e|0;var f=0,g=0;f=i;i=i+16|0;g=f|0;Ad(a,b,d,e,g)|0;i=f;return (C=c[g+4>>2]|0,c[g>>2]|0)|0}function Ad(a,b,d,e,f){a=a|0;b=b|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,D=0,E=0,F=0,G=0,H=0;g=a;h=b;i=h;j=d;k=e;l=k;if(!i){m=(f|0)!=0;if(!l){if(m){c[f>>2]=(g>>>0)%(j>>>0);c[f+4>>2]=0}n=0;o=(g>>>0)/(j>>>0)>>>0;return (C=n,o)|0}else{if(!m){n=0;o=0;return (C=n,o)|0}c[f>>2]=a|0;c[f+4>>2]=b&0;n=0;o=0;return (C=n,o)|0}}m=(l|0)==0;do if(j){if(!m){p=(aa(l|0)|0)-(aa(i|0)|0)|0;if(p>>>0<=31){q=p+1|0;r=31-p|0;s=p-31>>31;t=q;u=g>>>(q>>>0)&s|i<<r;v=i>>>(q>>>0)&s;w=0;x=g<<r;break}if(!f){n=0;o=0;return (C=n,o)|0}c[f>>2]=a|0;c[f+4>>2]=h|b&0;n=0;o=0;return (C=n,o)|0}r=j-1|0;if(r&j|0){s=(aa(j|0)|0)+33-(aa(i|0)|0)|0;q=64-s|0;p=32-s|0;y=p>>31;z=s-32|0;A=z>>31;t=s;u=p-1>>31&i>>>(z>>>0)|(i<<p|g>>>(s>>>0))&A;v=A&i>>>(s>>>0);w=g<<q&y;x=(i<<q|g>>>(z>>>0))&y|g<<p&s-33>>31;break}if(f|0){c[f>>2]=r&g;c[f+4>>2]=0}if((j|0)==1){n=h|b&0;o=a|0|0;return (C=n,o)|0}else{r=td(j|0)|0;n=i>>>(r>>>0)|0;o=i<<32-r|g>>>(r>>>0)|0;return (C=n,o)|0}}else{if(m){if(f|0){c[f>>2]=(i>>>0)%(j>>>0);c[f+4>>2]=0}n=0;o=(i>>>0)/(j>>>0)>>>0;return (C=n,o)|0}if(!g){if(f|0){c[f>>2]=0;c[f+4>>2]=(i>>>0)%(l>>>0)}n=0;o=(i>>>0)/(l>>>0)>>>0;return (C=n,o)|0}r=l-1|0;if(!(r&l)){if(f|0){c[f>>2]=a|0;c[f+4>>2]=r&i|b&0}n=0;o=i>>>((td(l|0)|0)>>>0);return (C=n,o)|0}r=(aa(l|0)|0)-(aa(i|0)|0)|0;if(r>>>0<=30){s=r+1|0;p=31-r|0;t=s;u=i<<p|g>>>(s>>>0);v=i>>>(s>>>0);w=0;x=g<<p;break}if(!f){n=0;o=0;return (C=n,o)|0}c[f>>2]=a|0;c[f+4>>2]=h|b&0;n=0;o=0;return (C=n,o)|0}while(0);if(!t){B=x;D=w;E=v;F=u;G=0;H=0}else{b=d|0|0;d=k|e&0;e=pd(b|0,d|0,-1,-1)|0;k=C;h=x;x=w;w=v;v=u;u=t;t=0;do{a=h;h=x>>>31|h<<1;x=t|x<<1;g=v<<1|a>>>31|0;a=v>>>31|w<<1|0;ld(e|0,k|0,g|0,a|0)|0;i=C;l=i>>31|((i|0)<0?-1:0)<<1;t=l&1;v=ld(g|0,a|0,l&b|0,(((i|0)<0?-1:0)>>31|((i|0)<0?-1:0)<<1)&d|0)|0;w=C;u=u-1|0}while((u|0)!=0);B=h;D=x;E=w;F=v;G=0;H=t}t=D;D=0;if(f|0){c[f>>2]=F;c[f+4>>2]=E}n=(t|0)>>>31|(B|D)<<1|(D<<1|t>>>31)&0|G;o=(t<<1|0>>>31)&-2|H;return (C=n,o)|0}function Bd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;return Aa[a&7](b|0,c|0,d|0,e|0)|0}function Cd(a,b){a=a|0;b=b|0;Ba[a&7](b|0)}function Dd(a,b,c){a=a|0;b=b|0;c=c|0;Ca[a&3](b|0,c|0)}function Ed(a,b){a=a|0;b=b|0;return Da[a&1](b|0)|0}function Fd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;Ea[a&1](b|0,c|0,d|0)}function Gd(a,b,c,d,e,f,g,h,i){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;return Fa[a&3](b|0,c|0,d|0,e|0,f|0,g|0,h|0,i|0)|0}function Hd(a,b,c){a=a|0;b=b|0;c=c|0;return Ga[a&15](b|0,c|0)|0}function Id(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;return Ha[a&7](b|0,c|0,d|0,e|0,f|0)|0}function Jd(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;ba(0);return 0}function Kd(a){a=a|0;ba(1)}function Ld(a,b){a=a|0;b=b|0;ba(2)}function Md(a){a=a|0;ba(3);return 0}function Nd(a,b,c){a=a|0;b=b|0;c=c|0;ba(4)}function Od(a,b,c,d,e,f,g,h){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;ba(5);return 0}function Pd(a,b){a=a|0;b=b|0;ba(6);return 0}function Qd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;ba(7);return 0} // EMSCRIPTEN_END_FUNCS var Aa=[Jd,hb,pb,wb,Eb,Jd,Jd,Jd];var Ba=[Kd,bb,cb,kb,lb,tb,ub,Lb];var Ca=[Ld,Za,yb,Ld];var Da=[Md,Mb];var Ea=[Nd,Jb];var Fa=[Od,Ab,Gb,Od];var Ga=[Pd,_a,ab,db,ib,jb,mb,rb,sb,Kb,fc,$a,ec,uc,Pd,Pd];var Ha=[Qd,vb,zb,Db,Fb,Hb,Qd,Qd];return{_i64Subtract:ld,_free:fd,_ogv_audio_decoder_destroy:Uc,_ogv_audio_decoder_init:Rc,_i64Add:pd,_memset:md,_ogv_audio_decoder_process_header:Sc,_malloc:ed,_memcpy:od,_ogv_audio_decoder_process_audio:Tc,_llvm_bswap_i32:qd,_bitshift64Shl:nd,runPostSets:kd,stackAlloc:Ia,stackSave:Ja,stackRestore:Ka,establishStackSpace:La,setThrew:Ma,setTempRet0:Pa,getTempRet0:Qa,dynCall_iiiii:Bd,dynCall_vi:Cd,dynCall_vii:Dd,dynCall_ii:Ed,dynCall_viii:Fd,dynCall_iiiiiiiii:Gd,dynCall_iii:Hd,dynCall_iiiiii:Id}}) // EMSCRIPTEN_END_ASM (Module.asmGlobalArg,Module.asmLibraryArg,buffer);var _i64Subtract=Module["_i64Subtract"]=asm["_i64Subtract"];var _free=Module["_free"]=asm["_free"];var runPostSets=Module["runPostSets"]=asm["runPostSets"];var _ogv_audio_decoder_destroy=Module["_ogv_audio_decoder_destroy"]=asm["_ogv_audio_decoder_destroy"];var _ogv_audio_decoder_init=Module["_ogv_audio_decoder_init"]=asm["_ogv_audio_decoder_init"];var _i64Add=Module["_i64Add"]=asm["_i64Add"];var _memset=Module["_memset"]=asm["_memset"];var _ogv_audio_decoder_process_header=Module["_ogv_audio_decoder_process_header"]=asm["_ogv_audio_decoder_process_header"];var _malloc=Module["_malloc"]=asm["_malloc"];var _memcpy=Module["_memcpy"]=asm["_memcpy"];var _ogv_audio_decoder_process_audio=Module["_ogv_audio_decoder_process_audio"]=asm["_ogv_audio_decoder_process_audio"];var _llvm_bswap_i32=Module["_llvm_bswap_i32"]=asm["_llvm_bswap_i32"];var _bitshift64Shl=Module["_bitshift64Shl"]=asm["_bitshift64Shl"];var dynCall_iiiii=Module["dynCall_iiiii"]=asm["dynCall_iiiii"];var dynCall_vi=Module["dynCall_vi"]=asm["dynCall_vi"];var dynCall_vii=Module["dynCall_vii"]=asm["dynCall_vii"];var dynCall_ii=Module["dynCall_ii"]=asm["dynCall_ii"];var dynCall_viii=Module["dynCall_viii"]=asm["dynCall_viii"];var dynCall_iiiiiiiii=Module["dynCall_iiiiiiiii"]=asm["dynCall_iiiiiiiii"];var dynCall_iii=Module["dynCall_iii"]=asm["dynCall_iii"];var dynCall_iiiiii=Module["dynCall_iiiiii"]=asm["dynCall_iiiiii"];Runtime.stackAlloc=asm["stackAlloc"];Runtime.stackSave=asm["stackSave"];Runtime.stackRestore=asm["stackRestore"];Runtime.establishStackSpace=asm["establishStackSpace"];Runtime.setTempRet0=asm["setTempRet0"];Runtime.getTempRet0=asm["getTempRet0"];function ExitStatus(status){this.name="ExitStatus";this.message="Program terminated with exit("+status+")";this.status=status}ExitStatus.prototype=new Error;ExitStatus.prototype.constructor=ExitStatus;var initialStackTop;var preloadStartTime=null;var calledMain=false;dependenciesFulfilled=function runCaller(){if(!Module["calledRun"])run();if(!Module["calledRun"])dependenciesFulfilled=runCaller};Module["callMain"]=Module.callMain=function callMain(args){args=args||[];ensureInitRuntime();var argc=args.length+1;function pad(){for(var i=0;i<4-1;i++){argv.push(0)}}var argv=[allocate(intArrayFromString(Module["thisProgram"]),"i8",ALLOC_NORMAL)];pad();for(var i=0;i<argc-1;i=i+1){argv.push(allocate(intArrayFromString(args[i]),"i8",ALLOC_NORMAL));pad()}argv.push(0);argv=allocate(argv,"i32",ALLOC_NORMAL);try{var ret=Module["_main"](argc,argv,0);exit(ret,true)}catch(e){if(e instanceof ExitStatus){return}else if(e=="SimulateInfiniteLoop"){Module["noExitRuntime"]=true;return}else{if(e&&typeof e==="object"&&e.stack)Module.printErr("exception thrown: "+[e,e.stack]);throw e}}finally{calledMain=true}};function run(args){args=args||Module["arguments"];if(preloadStartTime===null)preloadStartTime=Date.now();if(runDependencies>0){return}preRun();if(runDependencies>0)return;if(Module["calledRun"])return;function doRun(){if(Module["calledRun"])return;Module["calledRun"]=true;if(ABORT)return;ensureInitRuntime();preMain();if(Module["onRuntimeInitialized"])Module["onRuntimeInitialized"]();if(Module["_main"]&&shouldRunNow)Module["callMain"](args);postRun()}if(Module["setStatus"]){Module["setStatus"]("Running...");setTimeout((function(){setTimeout((function(){Module["setStatus"]("")}),1);doRun()}),1)}else{doRun()}}Module["run"]=Module.run=run;function exit(status,implicit){if(implicit&&Module["noExitRuntime"]){return}if(Module["noExitRuntime"]){}else{ABORT=true;EXITSTATUS=status;STACKTOP=initialStackTop;exitRuntime();if(Module["onExit"])Module["onExit"](status)}if(ENVIRONMENT_IS_NODE){process["exit"](status)}else if(ENVIRONMENT_IS_SHELL&&typeof quit==="function"){quit(status)}throw new ExitStatus(status)}Module["exit"]=Module.exit=exit;var abortDecorators=[];function abort(what){if(what!==undefined){Module.print(what);Module.printErr(what);what=JSON.stringify(what)}else{what=""}ABORT=true;EXITSTATUS=1;var extra="\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.";var output="abort("+what+") at "+stackTrace()+extra;if(abortDecorators){abortDecorators.forEach((function(decorator){output=decorator(output,what)}))}throw output}Module["abort"]=Module.abort=abort;if(Module["preInit"]){if(typeof Module["preInit"]=="function")Module["preInit"]=[Module["preInit"]];while(Module["preInit"].length>0){Module["preInit"].pop()()}}var shouldRunNow=false;if(Module["noInitialRun"]){shouldRunNow=false}Module["noExitRuntime"]=true;run();var inputBuffer,inputBufferSize;function reallocInputBuffer(size){if(inputBuffer&&inputBufferSize>=size){return inputBuffer}if(inputBuffer){Module._free(inputBuffer)}inputBufferSize=size;inputBuffer=Module._malloc(inputBufferSize);return inputBuffer}var getTimestamp;if(typeof performance==="undefined"||typeof performance.now==="undefined"){getTimestamp=Date.now}else{getTimestamp=performance.now.bind(performance)}function time(func){var start=getTimestamp(),ret;ret=func();Module.cpuTime+=getTimestamp()-start;return ret}Module.loadedMetadata=!!options.audioFormat;Module.audioFormat=options.audioFormat||null;Module.audioBuffer=null;Module.cpuTime=0;Object.defineProperty(Module,"processing",{get:function getProcessing(){return false}});Module.init=(function(callback){time((function(){Module._ogv_audio_decoder_init()}));callback()});Module.processHeader=(function(data,callback){var ret=time((function(){var len=data.byteLength;var buffer=reallocInputBuffer(len);Module.HEAPU8.set(new Uint8Array(data),buffer);return Module._ogv_audio_decoder_process_header(buffer,len)}));callback(ret)});Module.processAudio=(function(data,callback){var ret=time((function(){var len=data.byteLength;var buffer=reallocInputBuffer(len);Module.HEAPU8.set(new Uint8Array(data),buffer);return Module._ogv_audio_decoder_process_audio(buffer,len)}));callback(ret)});Module.close=(function(){}) return Module; };
"use asm";var a=new global.Int8Array(buffer);var b=new global.Int16Array(buffer);var c=new global.Int32Array(buffer);var d=new global.Uint8Array(buffer);var e=new global.Uint16Array(buffer);var f=new global.Uint32Array(buffer);var g=new global.Float32Array(buffer);var h=new global.Float64Array(buffer);var i=env.STACKTOP|0;var j=env.STACK_MAX|0;var k=env.tempDoublePtr|0;var l=env.ABORT|0;var m=env.cttz_i8|0;var n=0;var o=0;var p=0;var q=0;var r=global.NaN,s=global.Infinity;var t=0,u=0,v=0,w=0,x=0.0,y=0,z=0,A=0,B=0.0;var C=0;var D=0;var E=0;var F=0;var G=0;var H=0;var I=0;var J=0;var K=0;var L=0;var M=global.Math.floor;var N=global.Math.abs;var O=global.Math.sqrt;var P=global.Math.pow;var Q=global.Math.cos;var R=global.Math.sin;var S=global.Math.tan;var T=global.Math.acos;var U=global.Math.asin;var V=global.Math.atan;var W=global.Math.atan2;var X=global.Math.exp;var Y=global.Math.log;var Z=global.Math.ceil;var _=global.Math.imul;var $=global.Math.min;var aa=global.Math.clz32;var ba=env.abort;var ca=env.assert;var da=env.invoke_iiiii;var ea=env.invoke_vi;var fa=env.invoke_vii;var ga=env.invoke_ii;var ha=env.invoke_viii;var ia=env.invoke_iiiiiiiii;var ja=env.invoke_iii;var ka=env.invoke_iiiiii;var la=env._pthread_self;var ma=env._emscripten_memcpy_big;var na=env._llvm_pow_f64;var oa=env._sysconf;var pa=env._llvm_sqrt_f64;var qa=env._llvm_fabs_f32;var ra=env._abort;var sa=env.___setErrNo;var ta=env._sbrk;var ua=env._time;var va=env._ogvjs_callback_audio;var wa=env._ogvjs_callback_init_audio;var xa=env._exit;var ya=env.__exit;var za=0.0;
storage_v1_api.py
# coding: utf-8 """ Kubernetes No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: v1.12.4 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import sys import os import re # python 2 and python 3 compatibility library from six import iteritems from ..api_client import ApiClient class StorageV1Api(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. Ref: https://github.com/swagger-api/swagger-codegen """ def __init__(self, api_client=None): if api_client is None: api_client = ApiClient() self.api_client = api_client def create_storage_class(self, body, **kwargs): """ create a StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_storage_class(body, async_req=True) >>> result = thread.get() :param async_req bool :param V1StorageClass body: (required) :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.create_storage_class_with_http_info(body, **kwargs) else: (data) = self.create_storage_class_with_http_info(body, **kwargs) return data def create_storage_class_with_http_info(self, body, **kwargs): """ create a StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.create_storage_class_with_http_info(body, async_req=True) >>> result = thread.get() :param async_req bool :param V1StorageClass body: (required) :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ all_params = ['body', 'include_uninitialized', 'pretty', 'dry_run'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method create_storage_class" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `create_storage_class`") collection_formats = {} path_params = {} query_params = [] if 'include_uninitialized' in params: query_params.append(('includeUninitialized', params['include_uninitialized'])) if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses', 'POST', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StorageClass', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_collection_storage_class(self, **kwargs): """ delete collection of StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_storage_class(async_req=True) >>> result = thread.get() :param async_req bool :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_collection_storage_class_with_http_info(**kwargs) else: (data) = self.delete_collection_storage_class_with_http_info(**kwargs) return data def delete_collection_storage_class_with_http_info(self, **kwargs): """ delete collection of StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_collection_storage_class_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1Status If the method is called asynchronously, returns the request thread. """ all_params = ['include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_collection_storage_class" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'include_uninitialized' in params: query_params.append(('includeUninitialized', params['include_uninitialized'])) if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if '_continue' in params: query_params.append(('continue', params['_continue'])) if 'field_selector' in params: query_params.append(('fieldSelector', params['field_selector'])) if 'label_selector' in params: query_params.append(('labelSelector', params['label_selector'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'resource_version' in params: query_params.append(('resourceVersion', params['resource_version'])) if 'timeout_seconds' in params: query_params.append(('timeoutSeconds', params['timeout_seconds'])) if 'watch' in params: query_params.append(('watch', params['watch'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def delete_storage_class(self, name, body, **kwargs): """ delete a StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_storage_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param V1DeleteOptions body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :return: V1Status If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.delete_storage_class_with_http_info(name, body, **kwargs) else: (data) = self.delete_storage_class_with_http_info(name, body, **kwargs) return data def delete_storage_class_with_http_info(self, name, body, **kwargs): """ delete a StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.delete_storage_class_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param V1DeleteOptions body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :param int grace_period_seconds: The duration in seconds before the object should be deleted. Value must be non-negative integer. The value zero indicates delete immediately. If this value is nil, the default grace period for the specified type will be used. Defaults to a per object value if not specified. zero means delete immediately. :param bool orphan_dependents: Deprecated: please use the PropagationPolicy, this field will be deprecated in 1.7. Should the dependent objects be orphaned. If true/false, the \"orphan\" finalizer will be added to/removed from the object's finalizers list. Either this field or PropagationPolicy may be set, but not both. :param str propagation_policy: Whether and how garbage collection will be performed. Either this field or OrphanDependents may be set, but not both. The default policy is decided by the existing finalizer set in the metadata.finalizers and the resource-specific default policy. Acceptable values are: 'Orphan' - orphan the dependents; 'Background' - allow the garbage collector to delete the dependents in the background; 'Foreground' - a cascading policy that deletes all dependents in the foreground. :return: V1Status If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'body', 'pretty', 'dry_run', 'grace_period_seconds', 'orphan_dependents', 'propagation_policy'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method delete_storage_class" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `delete_storage_class`") # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `delete_storage_class`") collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) if 'grace_period_seconds' in params: query_params.append(('gracePeriodSeconds', params['grace_period_seconds'])) if 'orphan_dependents' in params: query_params.append(('orphanDependents', params['orphan_dependents'])) if 'propagation_policy' in params: query_params.append(('propagationPolicy', params['propagation_policy'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses/{name}', 'DELETE', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1Status', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def get_api_resources(self, **kwargs): """ get available resources This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources(async_req=True) >>> result = thread.get() :param async_req bool :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.get_api_resources_with_http_info(**kwargs) else: (data) = self.get_api_resources_with_http_info(**kwargs) return data def get_api_resources_with_http_info(self, **kwargs): """ get available resources This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.get_api_resources_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :return: V1APIResourceList If the method is called asynchronously, returns the request thread. """ all_params = [] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method get_api_resources" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1APIResourceList', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def list_storage_class(self, **kwargs): """ list or watch objects of kind StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_storage_class(async_req=True) >>> result = thread.get() :param async_req bool :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1StorageClassList If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'):
else: (data) = self.list_storage_class_with_http_info(**kwargs) return data def list_storage_class_with_http_info(self, **kwargs): """ list or watch objects of kind StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.list_storage_class_with_http_info(async_req=True) >>> result = thread.get() :param async_req bool :param bool include_uninitialized: If true, partially initialized resources are included in the response. :param str pretty: If 'true', then the output is pretty printed. :param str _continue: The continue option should be set when retrieving more results from the server. Since this value is server defined, clients may only use the continue value from a previous query result with identical query parameters (except for the value of continue) and the server may reject a continue value it does not recognize. If the specified continue value is no longer valid whether due to expiration (generally five to fifteen minutes) or a configuration change on the server, the server will respond with a 410 ResourceExpired error together with a continue token. If the client needs a consistent list, it must restart their list without the continue field. Otherwise, the client may send another list request with the token received with the 410 error, the server will respond with a list starting from the next key, but from the latest snapshot, which is inconsistent from the previous list results - objects that are created, modified, or deleted after the first list request will be included in the response, as long as their keys are after the \"next key\". This field is not supported when watch is true. Clients may start a watch from the last resourceVersion value returned by the server and not miss any modifications. :param str field_selector: A selector to restrict the list of returned objects by their fields. Defaults to everything. :param str label_selector: A selector to restrict the list of returned objects by their labels. Defaults to everything. :param int limit: limit is a maximum number of responses to return for a list call. If more items exist, the server will set the `continue` field on the list metadata to a value that can be used with the same initial query to retrieve the next set of results. Setting a limit may return fewer than the requested amount of items (up to zero items) in the event all requested objects are filtered out and clients should only use the presence of the continue field to determine whether more results are available. Servers may choose not to support the limit argument and will return all of the available results. If limit is specified and the continue field is empty, clients may assume that no more results are available. This field is not supported if watch is true. The server guarantees that the objects returned when using continue will be identical to issuing a single list call without a limit - that is, no objects created, modified, or deleted after the first request is issued will be included in any subsequent continued requests. This is sometimes referred to as a consistent snapshot, and ensures that a client that is using limit to receive smaller chunks of a very large result can ensure they see all possible objects. If objects are updated during a chunked list the version of the object that was present at the time the first list result was calculated is returned. :param str resource_version: When specified with a watch call, shows changes that occur after that particular version of a resource. Defaults to changes from the beginning of history. When specified for list: - if unset, then the result is returned from remote storage based on quorum-read flag; - if it's 0, then we simply return what we currently have in cache, no guarantee; - if set to non zero, then the result is at least as fresh as given rv. :param int timeout_seconds: Timeout for the list/watch call. This limits the duration of the call, regardless of any activity or inactivity. :param bool watch: Watch for changes to the described resources and return them as a stream of add, update, and remove notifications. Specify resourceVersion. :return: V1StorageClassList If the method is called asynchronously, returns the request thread. """ all_params = ['include_uninitialized', 'pretty', '_continue', 'field_selector', 'label_selector', 'limit', 'resource_version', 'timeout_seconds', 'watch'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method list_storage_class" % key ) params[key] = val del params['kwargs'] collection_formats = {} path_params = {} query_params = [] if 'include_uninitialized' in params: query_params.append(('includeUninitialized', params['include_uninitialized'])) if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if '_continue' in params: query_params.append(('continue', params['_continue'])) if 'field_selector' in params: query_params.append(('fieldSelector', params['field_selector'])) if 'label_selector' in params: query_params.append(('labelSelector', params['label_selector'])) if 'limit' in params: query_params.append(('limit', params['limit'])) if 'resource_version' in params: query_params.append(('resourceVersion', params['resource_version'])) if 'timeout_seconds' in params: query_params.append(('timeoutSeconds', params['timeout_seconds'])) if 'watch' in params: query_params.append(('watch', params['watch'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf', 'application/json;stream=watch', 'application/vnd.kubernetes.protobuf;stream=watch']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StorageClassList', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def patch_storage_class(self, name, body, **kwargs): """ partially update the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_storage_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.patch_storage_class_with_http_info(name, body, **kwargs) else: (data) = self.patch_storage_class_with_http_info(name, body, **kwargs) return data def patch_storage_class_with_http_info(self, name, body, **kwargs): """ partially update the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_storage_class_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param object body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'body', 'pretty', 'dry_run'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method patch_storage_class" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `patch_storage_class`") # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `patch_storage_class`") collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['application/json-patch+json', 'application/merge-patch+json', 'application/strategic-merge-patch+json']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses/{name}', 'PATCH', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StorageClass', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def read_storage_class(self, name, **kwargs): """ read the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_storage_class(name, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. :param bool export: Should this value be exported. Export strips fields that a user can not specify. :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.read_storage_class_with_http_info(name, **kwargs) else: (data) = self.read_storage_class_with_http_info(name, **kwargs) return data def read_storage_class_with_http_info(self, name, **kwargs): """ read the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.read_storage_class_with_http_info(name, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param str pretty: If 'true', then the output is pretty printed. :param bool exact: Should the export be exact. Exact export maintains cluster-specific fields like 'Namespace'. :param bool export: Should this value be exported. Export strips fields that a user can not specify. :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'pretty', 'exact', 'export'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method read_storage_class" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `read_storage_class`") collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'exact' in params: query_params.append(('exact', params['exact'])) if 'export' in params: query_params.append(('export', params['export'])) header_params = {} form_params = [] local_var_files = {} body_params = None # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses/{name}', 'GET', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StorageClass', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats) def replace_storage_class(self, name, body, **kwargs): """ replace the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_storage_class(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param V1StorageClass body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ kwargs['_return_http_data_only'] = True if kwargs.get('async_req'): return self.replace_storage_class_with_http_info(name, body, **kwargs) else: (data) = self.replace_storage_class_with_http_info(name, body, **kwargs) return data def replace_storage_class_with_http_info(self, name, body, **kwargs): """ replace the specified StorageClass This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.replace_storage_class_with_http_info(name, body, async_req=True) >>> result = thread.get() :param async_req bool :param str name: name of the StorageClass (required) :param V1StorageClass body: (required) :param str pretty: If 'true', then the output is pretty printed. :param str dry_run: When present, indicates that modifications should not be persisted. An invalid or unrecognized dryRun directive will result in an error response and no further processing of the request. Valid values are: - All: all dry run stages will be processed :return: V1StorageClass If the method is called asynchronously, returns the request thread. """ all_params = ['name', 'body', 'pretty', 'dry_run'] all_params.append('async_req') all_params.append('_return_http_data_only') all_params.append('_preload_content') all_params.append('_request_timeout') params = locals() for key, val in iteritems(params['kwargs']): if key not in all_params: raise TypeError( "Got an unexpected keyword argument '%s'" " to method replace_storage_class" % key ) params[key] = val del params['kwargs'] # verify the required parameter 'name' is set if ('name' not in params) or (params['name'] is None): raise ValueError("Missing the required parameter `name` when calling `replace_storage_class`") # verify the required parameter 'body' is set if ('body' not in params) or (params['body'] is None): raise ValueError("Missing the required parameter `body` when calling `replace_storage_class`") collection_formats = {} path_params = {} if 'name' in params: path_params['name'] = params['name'] query_params = [] if 'pretty' in params: query_params.append(('pretty', params['pretty'])) if 'dry_run' in params: query_params.append(('dryRun', params['dry_run'])) header_params = {} form_params = [] local_var_files = {} body_params = None if 'body' in params: body_params = params['body'] # HTTP header `Accept` header_params['Accept'] = self.api_client.\ select_header_accept(['application/json', 'application/yaml', 'application/vnd.kubernetes.protobuf']) # HTTP header `Content-Type` header_params['Content-Type'] = self.api_client.\ select_header_content_type(['*/*']) # Authentication setting auth_settings = ['BearerToken'] return self.api_client.call_api('/apis/storage.k8s.io/v1/storageclasses/{name}', 'PUT', path_params, query_params, header_params, body=body_params, post_params=form_params, files=local_var_files, response_type='V1StorageClass', auth_settings=auth_settings, async_req=params.get('async_req'), _return_http_data_only=params.get('_return_http_data_only'), _preload_content=params.get('_preload_content', True), _request_timeout=params.get('_request_timeout'), collection_formats=collection_formats)
return self.list_storage_class_with_http_info(**kwargs)
customers.component.ts
import { Component } from '@angular/core'; import { CustomersClient, CustomerListModel } from '../northwind-traders-api'; @Component({ selector: 'app-customers', templateUrl: './customers.component.html' }) export class CustomersComponent { customers: CustomerListModel[];
constructor(client: CustomersClient) { client.getAll().subscribe(result => { this.customers = result; }, error => console.error(error)); } }
meilisearch.rs
use std::cmp::Ordering; use std::collections::{HashMap, HashSet}; use std::hash::{Hash, Hasher}; use std::time::Instant; use indexmap::IndexMap; use log::error; use meilisearch_core::{Filter, MainReader}; use meilisearch_core::facets::FacetFilter; use meilisearch_core::criterion::*; use meilisearch_core::settings::RankingRule; use meilisearch_core::{Highlight, Index, RankedMap}; use meilisearch_schema::{FieldId, Schema}; use serde::{Deserialize, Serialize}; use serde_json::Value; use siphasher::sip::SipHasher; use slice_group_by::GroupBy; use crate::error::{Error, ResponseError}; pub trait IndexSearchExt { fn new_search(&self, query: Option<String>) -> SearchBuilder; } impl IndexSearchExt for Index { fn new_search(&self, query: Option<String>) -> SearchBuilder { SearchBuilder { index: self, query, offset: 0, limit: 20, attributes_to_crop: None, attributes_to_retrieve: None, attributes_to_highlight: None, filters: None, matches: false, facet_filters: None, facets: None, reverse: None, sort_strategy: None, } } } pub struct SearchBuilder<'a> { index: &'a Index, query: Option<String>, offset: usize, limit: usize, attributes_to_crop: Option<HashMap<String, usize>>, attributes_to_retrieve: Option<HashSet<String>>, attributes_to_highlight: Option<HashSet<String>>, filters: Option<String>, matches: bool, facet_filters: Option<FacetFilter>, facets: Option<Vec<(FieldId, String)>>, reverse: Option<bool>, sort_strategy: Option<String>, } impl<'a> SearchBuilder<'a> { pub fn offset(&mut self, value: usize) -> &SearchBuilder { self.offset = value; self } pub fn limit(&mut self, value: usize) -> &SearchBuilder { self.limit = value; self } pub fn reverse(&mut self, value: bool) -> &SearchBuilder { self.reverse = Some(value); self } pub fn sort_strategy(&mut self, value: String) -> &SearchBuilder { self.sort_strategy = Some(value); self } pub fn attributes_to_crop(&mut self, value: HashMap<String, usize>) -> &SearchBuilder { self.attributes_to_crop = Some(value); self } pub fn attributes_to_retrieve(&mut self, value: HashSet<String>) -> &SearchBuilder { self.attributes_to_retrieve = Some(value); self } pub fn add_retrievable_field(&mut self, value: String) -> &SearchBuilder { let attributes_to_retrieve = self.attributes_to_retrieve.get_or_insert(HashSet::new()); attributes_to_retrieve.insert(value); self } pub fn attributes_to_highlight(&mut self, value: HashSet<String>) -> &SearchBuilder { self.attributes_to_highlight = Some(value); self } pub fn add_facet_filters(&mut self, filters: FacetFilter) -> &SearchBuilder { self.facet_filters = Some(filters); self } pub fn filters(&mut self, value: String) -> &SearchBuilder { self.filters = Some(value); self } pub fn get_matches(&mut self) -> &SearchBuilder { self.matches = true; self } pub fn add_facets(&mut self, facets: Vec<(FieldId, String)>) -> &SearchBuilder { self.facets = Some(facets); self } pub fn search(self, reader: &MainReader) -> Result<SearchResult, ResponseError> { let schema = self .index .main .schema(reader)? .ok_or(Error::internal("missing schema"))?; let ranked_map = self.index.main.ranked_map(reader)?.unwrap_or_default(); // Change criteria let mut query_builder = match self.get_criteria(reader, &ranked_map, &schema, self.sort_strategy.clone())? { Some(criteria) => self.index.query_builder_with_criteria(criteria), None => self.index.query_builder(), }; if let Some(filter_expression) = &self.filters { let filter = Filter::parse(filter_expression, &schema)?; let index = &self.index; query_builder.with_filter(move |id| { let reader = &reader; let filter = &filter; match filter.test(reader, index, id) { Ok(res) => res, Err(e) => { log::warn!("unexpected error during filtering: {}", e); false } } }); } if let Some(field) = self.index.main.distinct_attribute(reader)? { let index = &self.index; query_builder.with_distinct(1, move |id| { match index.document_attribute_bytes(reader, id, field) { Ok(Some(bytes)) => { let mut s = SipHasher::new(); bytes.hash(&mut s); Some(s.finish()) } _ => None, } }); } if let Some(reverse) = self.reverse { query_builder.with_reverse(reverse); } query_builder.set_facet_filter(self.facet_filters); query_builder.set_facets(self.facets); let start = Instant::now(); let result = query_builder.query(reader, self.query.as_deref(), self.offset..(self.offset + self.limit)); let search_result = result.map_err(Error::search_documents)?; let time_ms = start.elapsed().as_millis() as usize; let mut all_attributes: HashSet<&str> = HashSet::new(); let mut all_formatted: HashSet<&str> = HashSet::new(); match &self.attributes_to_retrieve { Some(to_retrieve) => { all_attributes.extend(to_retrieve.iter().map(String::as_str)); if let Some(to_highlight) = &self.attributes_to_highlight { all_formatted.extend(to_highlight.iter().map(String::as_str)); } if let Some(to_crop) = &self.attributes_to_crop { all_formatted.extend(to_crop.keys().map(String::as_str)); } all_attributes.extend(&all_formatted); }, None => { all_attributes.extend(schema.displayed_names()); // If we specified at least one attribute to highlight or crop then // all available attributes will be returned in the _formatted field. if self.attributes_to_highlight.is_some() || self.attributes_to_crop.is_some() { all_formatted.extend(all_attributes.iter().cloned()); } }, } let mut hits = Vec::with_capacity(self.limit); for doc in search_result.documents { let mut document: IndexMap<String, Value> = self .index .document(reader, Some(&all_attributes), doc.id) .map_err(|e| Error::retrieve_document(doc.id.0, e))? .unwrap_or_default(); let mut formatted = document.iter() .filter(|(key, _)| all_formatted.contains(key.as_str())) .map(|(k, v)| (k.clone(), v.clone())) .collect(); let mut matches = doc.highlights.clone(); // Crops fields if needed if let Some(fields) = &self.attributes_to_crop { crop_document(&mut formatted, &mut matches, &schema, fields); } // Transform to readable matches if let Some(attributes_to_highlight) = &self.attributes_to_highlight { let matches = calculate_matches( &matches, self.attributes_to_highlight.clone(), &schema, ); formatted = calculate_highlights(&formatted, &matches, attributes_to_highlight); } let matches_info = if self.matches { Some(calculate_matches(&matches, self.attributes_to_retrieve.clone(), &schema)) } else { None }; if let Some(attributes_to_retrieve) = &self.attributes_to_retrieve { document.retain(|key, _| attributes_to_retrieve.contains(&key.to_string())) } let hit = SearchHit { document, formatted, matches_info, }; hits.push(hit); } let results = SearchResult { hits, offset: self.offset, limit: self.limit, nb_hits: search_result.nb_hits, exhaustive_nb_hits: search_result.exhaustive_nb_hit, processing_time_ms: time_ms, query: self.query.unwrap_or_default(), facets_distribution: search_result.facets, exhaustive_facets_count: search_result.exhaustive_facets_count, }; Ok(results) } pub fn get_criteria( &self, reader: &MainReader, ranked_map: &'a RankedMap, schema: &Schema, strategy: Option<String>, ) -> Result<Option<Criteria<'a>>, ResponseError> { let ranking_rules = if let Some(strategy) = strategy { self.index.main.sort_strategies(reader)?.unwrap_or(std::collections::BTreeMap::new()).get(&strategy).cloned() } else { self.index.main.ranking_rules(reader)? }; if let Some(ranking_rules) = ranking_rules { let mut builder = CriteriaBuilder::with_capacity(7 + ranking_rules.len()); for rule in ranking_rules { match rule { RankingRule::Typo => builder.push(Typo), RankingRule::Words => builder.push(Words), RankingRule::Proximity => builder.push(Proximity), RankingRule::Attribute => builder.push(Attribute), RankingRule::WordsPosition => builder.push(WordsPosition), RankingRule::Exactness => builder.push(Exactness), RankingRule::Asc(field) => { match SortByAttr::lower_is_better(&ranked_map, &schema, &field) { Ok(rule) => builder.push(rule), Err(err) => error!("Error during criteria builder; {:?}", err), } } RankingRule::Desc(field) => { match SortByAttr::higher_is_better(&ranked_map, &schema, &field) { Ok(rule) => builder.push(rule), Err(err) => error!("Error during criteria builder; {:?}", err), } } } } builder.push(DocumentId); return Ok(Some(builder.build())); } Ok(None) } } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize)] pub struct MatchPosition { pub start: usize, pub length: usize, } impl PartialOrd for MatchPosition { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl Ord for MatchPosition { fn cmp(&self, other: &Self) -> Ordering { match self.start.cmp(&other.start) { Ordering::Equal => self.length.cmp(&other.length), _ => self.start.cmp(&other.start), } } } pub type HighlightInfos = HashMap<String, Value>; pub type MatchesInfos = HashMap<String, Vec<MatchPosition>>; // pub type RankingInfos = HashMap<String, u64>; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct SearchHit { #[serde(flatten)] pub document: IndexMap<String, Value>, #[serde(rename = "_formatted", skip_serializing_if = "IndexMap::is_empty")] pub formatted: IndexMap<String, Value>, #[serde(rename = "_matchesInfo", skip_serializing_if = "Option::is_none")] pub matches_info: Option<MatchesInfos>, } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "camelCase")] pub struct SearchResult { pub hits: Vec<SearchHit>, pub offset: usize, pub limit: usize, pub nb_hits: usize, pub exhaustive_nb_hits: bool, pub processing_time_ms: usize, pub query: String, #[serde(skip_serializing_if = "Option::is_none")] pub facets_distribution: Option<HashMap<String, HashMap<String, usize>>>, #[serde(skip_serializing_if = "Option::is_none")] pub exhaustive_facets_count: Option<bool>, } /// returns the start index and the length on the crop. fn aligned_crop(text: &str, match_index: usize, context: usize) -> (usize, usize) { let is_word_component = |c: &char| c.is_alphanumeric() && !super::is_cjk(*c); let word_end_index = |mut index| { if text.chars().nth(index - 1).map_or(false, |c| is_word_component(&c)) { index += text.chars().skip(index).take_while(is_word_component).count(); } index }; if context == 0 { // count need to be at least 1 for cjk queries to return something return (match_index, 1 + text.chars().skip(match_index).take_while(is_word_component).count()); } let start = match match_index.saturating_sub(context) { 0 => 0, n => { let word_end_index = word_end_index(n); // skip whitespaces if any word_end_index + text.chars().skip(word_end_index).take_while(char::is_ascii_whitespace).count() } }; let end = word_end_index(match_index + context); (start, end - start) } fn crop_text( text: &str, matches: impl IntoIterator<Item = Highlight>, context: usize, ) -> (String, Vec<Highlight>) { let mut matches = matches.into_iter().peekable(); let char_index = matches.peek().map(|m| m.char_index as usize).unwrap_or(0); let (start, count) = aligned_crop(text, char_index, context); // TODO do something about double allocation let text = text .chars() .skip(start) .take(count) .collect::<String>() .trim() .to_string(); // update matches index to match the new cropped text let matches = matches .take_while(|m| (m.char_index as usize) + (m.char_length as usize) <= start + count) .map(|m| Highlight { char_index: m.char_index - start as u16, ..m }) .collect(); (text, matches) } fn crop_document( document: &mut IndexMap<String, Value>, matches: &mut Vec<Highlight>, schema: &Schema, fields: &HashMap<String, usize>, ) { matches.sort_unstable_by_key(|m| (m.char_index, m.char_length)); for (field, length) in fields { let attribute = match schema.id(field) { Some(attribute) => attribute, None => continue, }; let selected_matches = matches .iter() .filter(|m| FieldId::new(m.attribute) == attribute) .cloned(); if let Some(Value::String(ref mut original_text)) = document.get_mut(field) { let (cropped_text, cropped_matches) = crop_text(original_text, selected_matches, *length); *original_text = cropped_text; matches.retain(|m| FieldId::new(m.attribute) != attribute); matches.extend_from_slice(&cropped_matches); } } } fn calculate_matches( matches: &[Highlight], attributes_to_retrieve: Option<HashSet<String>>, schema: &Schema, ) -> MatchesInfos { let mut matches_result: HashMap<String, Vec<MatchPosition>> = HashMap::new(); for m in matches.iter() { if let Some(attribute) = schema.name(FieldId::new(m.attribute)) { if let Some(ref attributes_to_retrieve) = attributes_to_retrieve { if !attributes_to_retrieve.contains(attribute) { continue; } } if !schema.displayed_names().contains(&attribute) { continue; } if let Some(pos) = matches_result.get_mut(attribute) { pos.push(MatchPosition { start: m.char_index as usize, length: m.char_length as usize, }); } else { let mut positions = Vec::new(); positions.push(MatchPosition { start: m.char_index as usize, length: m.char_length as usize, }); matches_result.insert(attribute.to_string(), positions); } } } for (_, val) in matches_result.iter_mut() { val.sort_unstable(); val.dedup(); } matches_result } fn calculate_highlights( document: &IndexMap<String, Value>, matches: &MatchesInfos, attributes_to_highlight: &HashSet<String>, ) -> IndexMap<String, Value> { let mut highlight_result = document.clone(); for (attribute, matches) in matches.iter() { if attributes_to_highlight.contains(attribute) { if let Some(Value::String(value)) = document.get(attribute) { let value = value; let mut highlighted_value = String::new(); let mut index = 0; let longest_matches = matches .linear_group_by_key(|m| m.start) .map(|group| group.last().unwrap()) .filter(move |m| m.start >= index); for m in longest_matches { let before = value.get(index..m.start); let highlighted = value.get(m.start..(m.start + m.length)); if let (Some(before), Some(highlighted)) = (before, highlighted) { highlighted_value.push_str(before); highlighted_value.push_str("<em>"); highlighted_value.push_str(highlighted); highlighted_value.push_str("</em>"); index = m.start + m.length; } else { error!("value: {:?}; index: {:?}, match: {:?}", value, index, m); } } highlighted_value.push_str(&value[index..]); highlight_result.insert(attribute.to_string(), Value::String(highlighted_value)); }; } } highlight_result } #[cfg(test)] mod tests { use super::*; #[test] fn aligned_crops() { let text = r#"En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la Fondation."#; // simple test let (start, length) = aligned_crop(&text, 6, 2); let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string(); assert_eq!("début", cropped); // first word test let (start, length) = aligned_crop(&text, 0, 1); let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string(); assert_eq!("En", cropped); // last word test let (start, length) = aligned_crop(&text, 510, 2); let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string(); assert_eq!("Fondation", cropped); // CJK tests let text = "this isのス foo myタイリ test"; // mixed charset let (start, length) = aligned_crop(&text, 5, 3); let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string(); assert_eq!("isの", cropped); // split regular word / CJK word, no space let (start, length) = aligned_crop(&text, 7, 1); let cropped = text.chars().skip(start).take(length).collect::<String>().trim().to_string(); assert_eq!("の", cropped); } #[test] fn calculate_matches() { let mut matches = Vec::n
hlights() { let data = r#"{ "title": "Fondation (Isaac ASIMOV)", "description": "En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la Fondation." }"#; let document: IndexMap<String, Value> = serde_json::from_str(data).unwrap(); let mut attributes_to_highlight = HashSet::new(); attributes_to_highlight.insert("title".to_string()); attributes_to_highlight.insert("description".to_string()); let mut matches = HashMap::new(); let mut m = Vec::new(); m.push(MatchPosition { start: 0, length: 9, }); matches.insert("title".to_string(), m); let mut m = Vec::new(); m.push(MatchPosition { start: 529, length: 9, }); matches.insert("description".to_string(), m); let result = super::calculate_highlights(&document, &matches, &attributes_to_highlight); let mut result_expected = IndexMap::new(); result_expected.insert( "title".to_string(), Value::String("<em>Fondation</em> (Isaac ASIMOV)".to_string()), ); result_expected.insert("description".to_string(), Value::String("En ce début de trentième millénaire, l'Empire n'a jamais été aussi puissant, aussi étendu à travers toute la galaxie. C'est dans sa capitale, Trantor, que l'éminent savant Hari Seldon invente la psychohistoire, une science toute nouvelle, à base de psychologie et de mathématiques, qui lui permet de prédire l'avenir... C'est-à-dire l'effondrement de l'Empire d'ici cinq siècles et au-delà, trente mille années de chaos et de ténèbres. Pour empêcher cette catastrophe et sauver la civilisation, Seldon crée la <em>Fondation</em>.".to_string())); assert_eq!(result, result_expected); } #[test] fn highlight_longest_match() { let data = r#"{ "title": "Ice" }"#; let document: IndexMap<String, Value> = serde_json::from_str(data).unwrap(); let mut attributes_to_highlight = HashSet::new(); attributes_to_highlight.insert("title".to_string()); let mut matches = HashMap::new(); let mut m = Vec::new(); m.push(MatchPosition { start: 0, length: 2, }); m.push(MatchPosition { start: 0, length: 3, }); matches.insert("title".to_string(), m); let result = super::calculate_highlights(&document, &matches, &attributes_to_highlight); let mut result_expected = IndexMap::new(); result_expected.insert( "title".to_string(), Value::String("<em>Ice</em>".to_string()), ); assert_eq!(result, result_expected); } }
ew(); matches.push(Highlight { attribute: 0, char_index: 0, char_length: 3}); matches.push(Highlight { attribute: 0, char_index: 0, char_length: 2}); let mut attributes_to_retrieve: HashSet<String> = HashSet::new(); attributes_to_retrieve.insert("title".to_string()); let schema = Schema::with_primary_key("title"); let matches_result = super::calculate_matches(&matches, Some(attributes_to_retrieve), &schema); let mut matches_result_expected: HashMap<String, Vec<MatchPosition>> = HashMap::new(); let mut positions = Vec::new(); positions.push(MatchPosition { start: 0, length: 2, }); positions.push(MatchPosition { start: 0, length: 3, }); matches_result_expected.insert("title".to_string(), positions); assert_eq!(matches_result, matches_result_expected); } #[test] fn calculate_hig
string.rs
// Copyright 2014 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // // ignore-lexer-test FIXME #15679 //! An owned, growable string that enforces that its contents are valid UTF-8. #![stable] use core::prelude::*; use core::borrow::{Cow, IntoCow}; use core::default::Default; use core::fmt; use core::hash; use core::mem; use core::ptr; use core::ops; use core::raw::Slice as RawSlice; use unicode::str as unicode_str; use unicode::str::Utf16Item; use slice::CloneSliceExt; use str::{mod, CharRange, FromStr, Utf8Error}; use vec::{DerefVec, Vec, as_vec}; /// A growable string stored as a UTF-8 encoded buffer. #[deriving(Clone, PartialOrd, Eq, Ord)] #[stable] pub struct String { vec: Vec<u8>, } /// A possible error value from the `String::from_utf8` function. #[stable] pub struct FromUtf8Error { bytes: Vec<u8>, error: Utf8Error, } /// A possible error value from the `String::from_utf16` function. #[stable] #[allow(missing_copy_implementations)] pub struct FromUtf16Error(()); impl String { /// Creates a new string buffer initialized with the empty string. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// ``` #[inline] #[stable] pub fn new() -> String { String { vec: Vec::new(), } } /// Creates a new string buffer with the given capacity. /// The string will be able to hold exactly `capacity` bytes without /// reallocating. If `capacity` is 0, the string will not allocate. /// /// # Examples /// /// ``` /// let mut s = String::with_capacity(10); /// ``` #[inline] #[stable] pub fn with_capacity(capacity: uint) -> String { String { vec: Vec::with_capacity(capacity), } } /// Creates a new string buffer from the given string. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// assert_eq!(s.as_slice(), "hello"); /// ``` #[inline] #[experimental = "needs investigation to see if to_string() can match perf"] pub fn from_str(string: &str) -> String { String { vec: string.as_bytes().to_vec() } } /// Returns the vector as a string buffer, if possible, taking care not to /// copy it. /// /// # Failure /// /// If the given vector is not valid UTF-8, then the original vector and the /// corresponding error is returned. /// /// # Examples /// /// ```rust /// # #![allow(deprecated)] /// use std::str::Utf8Error; /// /// let hello_vec = vec![104, 101, 108, 108, 111]; /// let s = String::from_utf8(hello_vec).unwrap(); /// assert_eq!(s, "hello"); /// /// let invalid_vec = vec![240, 144, 128]; /// let s = String::from_utf8(invalid_vec).err().unwrap(); /// assert_eq!(s.utf8_error(), Utf8Error::TooShort); /// assert_eq!(s.into_bytes(), vec![240, 144, 128]); /// ``` #[inline] #[stable] pub fn from_utf8(vec: Vec<u8>) -> Result<String, FromUtf8Error> { match str::from_utf8(vec.as_slice()) { Ok(..) => Ok(String { vec: vec }), Err(e) => Err(FromUtf8Error { bytes: vec, error: e }) } } /// Converts a vector of bytes to a new UTF-8 string. /// Any invalid UTF-8 sequences are replaced with U+FFFD REPLACEMENT CHARACTER. /// /// # Examples /// /// ```rust /// let input = b"Hello \xF0\x90\x80World"; /// let output = String::from_utf8_lossy(input); /// assert_eq!(output.as_slice(), "Hello \u{FFFD}World"); /// ``` #[stable] pub fn from_utf8_lossy<'a>(v: &'a [u8]) -> CowString<'a> { match str::from_utf8(v) { Ok(s) => return Cow::Borrowed(s), Err(..) => {} } static TAG_CONT_U8: u8 = 128u8; static REPLACEMENT: &'static [u8] = b"\xEF\xBF\xBD"; // U+FFFD in UTF-8 let mut i = 0; let total = v.len(); fn unsafe_get(xs: &[u8], i: uint) -> u8 { unsafe { *xs.get_unchecked(i) } } fn safe_get(xs: &[u8], i: uint, total: uint) -> u8 { if i >= total { 0 } else { unsafe_get(xs, i) } } let mut res = String::with_capacity(total); if i > 0 { unsafe { res.as_mut_vec().push_all(v[..i]) }; } // subseqidx is the index of the first byte of the subsequence we're looking at. // It's used to copy a bunch of contiguous good codepoints at once instead of copying // them one by one. let mut subseqidx = 0; while i < total { let i_ = i; let byte = unsafe_get(v, i); i += 1; macro_rules! error(() => ({ unsafe { if subseqidx != i_ { res.as_mut_vec().push_all(v[subseqidx..i_]); } subseqidx = i; res.as_mut_vec().push_all(REPLACEMENT); } })); if byte < 128u8 { // subseqidx handles this } else { let w = unicode_str::utf8_char_width(byte); match w { 2 => { if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 { error!(); continue; } i += 1; } 3 => { match (byte, safe_get(v, i, total)) { (0xE0 , 0xA0 ... 0xBF) => (), (0xE1 ... 0xEC, 0x80 ... 0xBF) => (), (0xED , 0x80 ... 0x9F) => (), (0xEE ... 0xEF, 0x80 ... 0xBF) => (), _ => { error!(); continue; } } i += 1; if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 { error!(); continue; } i += 1; } 4 => { match (byte, safe_get(v, i, total)) { (0xF0 , 0x90 ... 0xBF) => (), (0xF1 ... 0xF3, 0x80 ... 0xBF) => (), (0xF4 , 0x80 ... 0x8F) => (), _ => { error!(); continue; } } i += 1; if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 { error!(); continue; } i += 1; if safe_get(v, i, total) & 192u8 != TAG_CONT_U8 { error!(); continue; } i += 1; } _ => { error!(); continue; } } } } if subseqidx < total { unsafe { res.as_mut_vec().push_all(v[subseqidx..total]) }; } Cow::Owned(res) } /// Decode a UTF-16 encoded vector `v` into a `String`, returning `None` /// if `v` contains any invalid data. /// /// # Examples /// /// ```rust /// // 𝄞music /// let mut v = &mut [0xD834, 0xDD1E, 0x006d, 0x0075, /// 0x0073, 0x0069, 0x0063]; /// assert_eq!(String::from_utf16(v).unwrap(), /// "𝄞music".to_string()); /// /// // 𝄞mu<invalid>ic /// v[4] = 0xD800; /// assert!(String::from_utf16(v).is_err()); /// ``` #[stable] pub fn from_utf16(v: &[u16]) -> Result<String, FromUtf16Error> { let mut s = String::with_capacity(v.len()); for c in unicode_str::utf16_items(v) { match c { Utf16Item::ScalarValue(c) => s.push(c), Utf16Item::LoneSurrogate(_) => return Err(FromUtf16Error(())), } } Ok(s) } /// Decode a UTF-16 encoded vector `v` into a string, replacing /// invalid data with the replacement character (U+FFFD). /// /// # Examples /// /// ```rust /// // 𝄞mus<invalid>ic<invalid> /// let v = &[0xD834, 0xDD1E, 0x006d, 0x0075, /// 0x0073, 0xDD1E, 0x0069, 0x0063, /// 0xD834]; /// /// assert_eq!(String::from_utf16_lossy(v), /// "𝄞mus\u{FFFD}ic\u{FFFD}".to_string()); /// ``` #[stable] pub fn from_utf16_lossy(v: &[u16]) -> String { unicode_str::utf16_items(v).map(|c| c.to_char_lossy()).collect() } /// Convert a vector of `char`s to a `String`. /// /// # Examples /// /// ```rust /// # #![allow(deprecated)] /// let chars = &['h', 'e', 'l', 'l', 'o']; /// let s = String::from_chars(chars); /// assert_eq!(s.as_slice(), "hello"); /// ``` #[inline] #[deprecated = "use .collect() instead"] pub fn from_chars(chs: &[char]) -> String { chs.iter().map(|c| *c).collect() } /// Creates a new `String` from a length, capacity, and pointer. /// /// This is unsafe because: /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`; /// * We assume that the `Vec` contains valid UTF-8. #[inline] #[stable] pub unsafe fn from_raw_parts(buf: *mut u8, length: uint, capacity: uint) -> String { String { vec: Vec::from_raw_parts(buf, length, capacity), } } /// Creates a `String` from a null-terminated `*const u8` buffer. /// /// This function is unsafe because we dereference memory until we find the /// NUL character, which is not guaranteed to be present. Additionally, the /// slice is not checked to see whether it contains valid UTF-8 #[unstable = "just renamed from `mod raw`"] pub unsafe fn from_raw_buf(buf: *const u8) -> String { String::from_str(str::from_c_str(buf as *const i8)) } /// Creates a `String` from a `*const u8` buffer of the given length. /// /// This function is unsafe because it blindly assumes the validity of the /// pointer `buf` for `len` bytes of memory. This function will copy the /// memory from `buf` into a new allocation (owned by the returned /// `String`). /// /// This function is also unsafe because it does not validate that the /// buffer is valid UTF-8 encoded data. #[unstable = "just renamed from `mod raw`"] pub unsafe fn from_raw_buf_len(buf: *const u8, len: uint) -> String { String::from_utf8_unchecked(Vec::from_raw_buf(buf, len)) } /// Converts a vector of bytes to a new `String` without checking if /// it contains valid UTF-8. This is unsafe because it assumes that /// the UTF-8-ness of the vector has already been validated. #[inline] #[stable] pub unsafe fn from_utf8_unchecked(bytes: Vec<u8>) -> String { String { vec: bytes } } /// Return the underlying byte buffer, encoded as UTF-8. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// let bytes = s.into_bytes(); /// assert_eq!(bytes, vec![104, 101, 108, 108, 111]); /// ``` #[inline] #[stable] pub fn into_bytes(self) -> Vec<u8> { self.vec } /// Creates a string buffer by repeating a character `length` times. /// /// # Examples /// /// ``` /// # #![allow(deprecated)] /// let s = String::from_char(5, 'a'); /// assert_eq!(s.as_slice(), "aaaaa"); /// ``` #[inline] #[deprecated = "use repeat(ch).take(length).collect() instead"] pub fn from_char(length: uint, ch: char) -> String { if length == 0 { return String::new() } let mut buf = String::new(); buf.push(ch); let size = buf.len() * (length - 1); buf.reserve_exact(size); for _ in range(1, length) { buf.push(ch) } buf } /// Pushes the given string onto this string buffer. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// s.push_str("bar"); /// assert_eq!(s.as_slice(), "foobar"); /// ``` #[inline] #[stable] pub fn push_str(&mut self, string: &str) { self.vec.push_all(string.as_bytes()) } /// Pushes `ch` onto the given string `count` times. /// /// # Examples /// /// ``` /// # #![allow(deprecated)] /// let mut s = String::from_str("foo"); /// s.grow(5, 'Z'); /// assert_eq!(s.as_slice(), "fooZZZZZ"); /// ``` #[inline] #[deprecated = "deprecated in favor of .extend(repeat(ch).take(count))"] pub fn grow(&mut self, count: uint, ch: char) { for _ in range(0, count) { self.push(ch) } } /// Returns the number of bytes that this string buffer can hold without /// reallocating. /// /// # Examples /// /// ``` /// let s = String::with_capacity(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable] pub fn capacity(&self) -> uint { self.vec.capacity() } /// Deprecated: Renamed to `reserve`. #[deprecated = "Renamed to `reserve`"] pub fn reserve_additional(&mut self, extra: uint) { self.vec.reserve(extra) } /// Reserves capacity for at least `additional` more bytes to be inserted /// in the given `String`. The collection may reserve more space to avoid /// frequent reallocations. /// /// # Panics /// /// Panics if the new capacity overflows `uint`. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// s.reserve(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable] pub fn reserve(&mut self, additional: uint) { self.vec.reserve(additional) } /// Reserves the minimum capacity for exactly `additional` more bytes to be /// inserted in the given `String`. Does nothing if the capacity is already /// sufficient. /// /// Note that the allocator may give the collection more space than it /// requests. Therefore capacity can not be relied upon to be precisely /// minimal. Prefer `reserve` if future insertions are expected. /// /// # Panics /// /// Panics if the new capacity overflows `uint`. /// /// # Examples /// /// ``` /// let mut s = String::new(); /// s.reserve(10); /// assert!(s.capacity() >= 10); /// ``` #[inline] #[stable] pub fn reserve_exact(&mut self, additional: uint) { self.vec.reserve_exact(additional) } /// Shrinks the capacity of this string buffer to match its length. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// s.reserve(100); /// assert!(s.capacity() >= 100); /// s.shrink_to_fit(); /// assert_eq!(s.capacity(), 3); /// ``` #[inline] #[stable] pub fn shrink_to_fit(&mut self) { self.vec.shrink_to_fit() } /// Adds the given character to the end of the string. /// /// # Examples /// /// ``` /// let mut s = String::from_str("abc"); /// s.push('1'); /// s.push('2'); /// s.push('3'); /// assert_eq!(s.as_slice(), "abc123"); /// ``` #[inline] #[stable] pub fn push(&mut self, ch: char) { if (ch as u32) < 0x80 { self.vec.push(ch as u8); return; } let cur_len = self.len(); // This may use up to 4 bytes. self.vec.reserve(4); unsafe { // Attempt to not use an intermediate buffer by just pushing bytes // directly onto this string. let slice = RawSlice { data: self.vec.as_ptr().offset(cur_len as int), len: 4, }; let used = ch.encode_utf8(mem::transmute(slice)).unwrap_or(0); self.vec.set_len(cur_len + used); } } /// Works with the underlying buffer as a byte slice. /// /// # Examples /// /// ``` /// let s = String::from_str("hello"); /// let b: &[_] = &[104, 101, 108, 108, 111]; /// assert_eq!(s.as_bytes(), b); /// ``` #[inline] #[stable] pub fn as_bytes<'a>(&'a self) -> &'a [u8] { self.vec.as_slice() } /// Shortens a string to the specified length. /// /// # Panics /// /// Panics if `new_len` > current length, /// or if `new_len` is not a character boundary. /// /// # Examples /// /// ``` /// let mut s = String::from_str("hello"); /// s.truncate(2); /// assert_eq!(s.as_slice(), "he"); /// ``` #[inline] #[stable] pub fn truncate(&mut self, new_len: uint) { assert!(self.is_char_boundary(new_len)); self.vec.truncate(new_len) } /// Removes the last character from the string buffer and returns it. /// Returns `None` if this string buffer is empty. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// assert_eq!(s.pop(), Some('o')); /// assert_eq!(s.pop(), Some('o')); /// assert_eq!(s.pop(), Some('f')); /// assert_eq!(s.pop(), None); /// ``` #[inline] #[stable] pub fn pop(&mut self) -> Option<char> { let len = self.len(); if len == 0 { return None } let CharRange {ch, next} = self.char_range_at_reverse(len); unsafe { self.vec.set_len(next); } Some(ch) } /// Removes the character from the string buffer at byte position `idx` and /// returns it. /// /// # Warning /// /// This is an O(n) operation as it requires copying every element in the /// buffer. /// /// # Panics /// /// If `idx` does not lie on a character boundary, or if it is out of /// bounds, then this function will panic. /// /// # Examples /// /// ``` /// let mut s = String::from_str("foo"); /// assert_eq!(s.remove(0), 'f'); /// assert_eq!(s.remove(1), 'o'); /// assert_eq!(s.remove(0), 'o'); /// ``` #[stable] pub fn remove(&mut self, idx: uint) -> char { let len = self.len(); assert!(idx <= len); let CharRange { ch, next } = self.char_range_at(idx); unsafe { ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int), self.vec.as_ptr().offset(next as int), len - next); self.vec.set_len(len - (next - idx)); } ch } /// Insert a character into the string buffer at byte position `idx`. /// /// # Warning /// /// This is an O(n) operation as it requires copying every element in the /// buffer. /// /// # Panics /// /// If `idx` does not lie on a character boundary or is out of bounds, then /// this function will panic. #[stable] pub fn insert(&mut self, idx: uint, ch: char) { let len = self.len(); assert!(idx <= len); assert!(self.is_char_boundary(idx)); self.vec.reserve(4); let mut bits = [0, ..4]; let amt = ch.encode_utf8(&mut bits).unwrap(); unsafe { ptr::copy_memory(self.vec.as_mut_ptr().offset((idx + amt) as int), self.vec.as_ptr().offset(idx as int), len - idx); ptr::copy_memory(self.vec.as_mut_ptr().offset(idx as int), bits.as_ptr(), amt); self.vec.set_len(len + amt); } } /// Views the string buffer as a mutable sequence of bytes. /// /// This is unsafe because it does not check /// to ensure that the resulting string will be valid UTF-8. /// /// # Examples /// /// ``` /// let mut s = String::from_str("hello"); /// unsafe { /// let vec = s.as_mut_vec(); /// assert!(vec == &mut vec![104, 101, 108, 108, 111]); /// vec.reverse(); /// } /// assert_eq!(s.as_slice(), "olleh"); /// ``` #[stable] pub unsafe fn as_mut_vec<'a>(&'a mut self) -> &'a mut Vec<u8> { &mut self.vec } /// Return the number of bytes in this string. /// /// # Examples /// /// ``` /// let a = "foo".to_string(); /// assert_eq!(a.len(), 3); /// ``` #[inline] #[stable] pub fn len(&self) -> uint { self.vec.len() } /// Returns true if the string contains no bytes /// /// # Examples /// /// ``` /// let mut v = String::new(); /// assert!(v.is_empty()); /// v.push('a'); /// assert!(!v.is_empty()); /// ``` #[stable] pub fn is_empty(&self) -> bool { self.len() == 0 } /// Truncates the string, returning it to 0 length. /// /// # Examples /// /// ``` /// let mut s = "foo".to_string(); /// s.clear(); /// assert!(s.is_empty()); /// ``` #[inline] #[stable] pub fn clear(&mut self) { self.vec.clear() } } impl FromUtf8Error { /// Consume this error, returning the bytes that were attempted to make a /// `String` with. #[stable] pub fn into_bytes(self) -> Vec<u8> { self.bytes } /// Access the underlying UTF8-error that was the cause of this error. #[stable] pub fn utf8_error(&self) -> Utf8Error { self.error } } impl fmt::Show for FromUtf8Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.error.fmt(f) } } impl fmt::Show for FromUtf16Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { "invalid utf-16: lone surrogate found".fmt(f) } } #[experimental = "waiting on FromIterator stabilization"] impl FromIterator<char> for String { fn from_iter<I:Iterator<char>>(iterator: I) -> String { let mut buf = String::new(); buf.extend(iterator); buf } } #[experimental = "waiting on FromIterator stabilization"] impl<'a> FromIterator<&'a str> for String { fn from_iter<I:Iterator<&'a str>>(iterator: I) -> String { let mut buf = String::new(); buf.extend(iterator); buf } } #[experimental = "waiting on Extend stabilization"] impl Extend<char> for String { fn extend<I:Iterator<char>>(&mut self, mut iterator: I) { let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); for ch in iterator { self.push(ch) } } } #[experimental = "waiting on Extend stabilization"] impl<'a> Extend<&'a str> for String { fn extend<I: Iterator<&'a str>>(&mut self, mut iterator: I) { // A guess that at least one byte per iterator element will be needed. let (lower_bound, _) = iterator.size_hint(); self.reserve(lower_bound); for s in iterator { self.push_str(s) } } } #[stable] impl PartialEq for String { #[inline] fn eq(&self, other: &String) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &String) -> bool { PartialEq::ne(&**self, &**other) } } macro_rules! impl_eq { ($lhs:ty, $rhs: ty) => { #[stable] impl<'a> PartialEq<$rhs> for $lhs { #[inline] fn eq(&self, other: &$rhs) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &$rhs) -> bool { PartialEq::ne(&**self, &**other) } } #[stable] impl<'a> PartialEq<$lhs> for $rhs { #[inline] fn eq(&self, other: &$lhs) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &$lhs) -> bool { PartialEq::ne(&**self, &**other) } } } } impl_eq! { String, &'a str } impl_eq! { CowString<'a>, String } #[stable] impl<'a, 'b> PartialEq<&'b str> for CowString<'a> { #[inline] fn eq(&self, other: &&'b str) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &&'b str) -> bool { PartialEq::ne(&**self, &**other) } } #[stable] impl<'a, 'b> PartialEq<CowString<'a>> for &'b str { #[inline] fn eq(&self, other: &CowString<'a>) -> bool { PartialEq::eq(&**self, &**other) } #[inline] fn ne(&self, other: &CowString<'a>) -> bool { PartialEq::ne(&**self, &**other) } } #[experimental = "waiting on Str stabilization"] #[allow(deprecated)] impl Str for String { #[inline] #[stable] fn as_slice<'a>(&'a self) -> &'a str { unsafe { mem::transmute(self.vec.as_slice()) } } } #[stable] impl Default for String { #[stable] fn default() -> String { String::new() } } #[experimental = "waiting on Show stabilization"] impl fmt::Show for String { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { (**self).fmt(f) } } #[experimental = "waiting on Hash stabilization"] impl<H: hash::Writer> hash::Hash<H> for String { #[inline] fn hash(&self, hasher: &mut H) { (**self).hash(hasher) } } #[allow(deprecated)] #[deprecated = "Use overloaded `core::cmp::PartialEq`"] impl<'a, S: Str> Equiv<S> for String { #[inline] fn equiv(&self, other: &S) -> bool { self.as_slice() == other.as_slice() } } #[experimental = "waiting on Add stabilization"] impl<'a> Add<&'a str, String> for String { fn add(mut self, other: &str) -> String { self.push_str(other); self } } impl ops::Slice<uint, str> for String { #[inline] fn as_slice_<'a>(&'a self) -> &'a str { unsafe { mem::transmute(self.vec.as_slice()) } } #[inline] fn slice_from_or_fail<'a>(&'a self, from: &uint) -> &'a str { self[][*from..] } #[inline] fn slice_to_or_fail<'a>(&'a self, to: &uint) -> &'a str { self[][..*to] } #[inline] fn slice_or_fail<'a>(&'a self, from: &uint, to: &uint) -> &'a str { self[][*from..*to] } } #[experimental = "waiting on Deref stabilization"] impl ops::Deref<str> for String { fn deref<'a>(&'a self) -> &'a str { unsafe { mem::transmute(self.vec[]) } } } /// Wrapper type providing a `&String` reference via `Deref`. #[experimental] pub struct DerefString<'a> { x: DerefVec<'a, u8> } impl<'a> Deref<String> for DerefString<'a> { fn deref<'b>(&'b self) -> &'b String { unsafe { mem::transmute(&*self.x) } } } /// Convert a string slice to a wrapper type providing a `&String` reference. /// /// # Examples /// /// ``` /// use std::string::as_string; /// /// fn string_consumer(s: String) { /// assert_eq!(s, "foo".to_string()); /// } /// /// let string = as_string("foo").clone(); /// string_consumer(string); /// ``` #[experimental] pub fn as_string<'a>(x: &'a str) -> DerefString<'a> { DerefString { x: as_vec(x.as_bytes()) } } impl FromStr for String { #[inline] fn from_str(s: &str) -> Option<String> { Some(String::from_str(s)) } } /// Trait for converting a type to a string, consuming it in the process. #[deprecated = "trait will be removed"] pub trait IntoString { /// Consume and convert to a string. fn into_string(self) -> String; } /// A generic trait for converting a value to a string pub trait ToString { /// Converts the value of `self` to an owned string fn to_string(&self) -> String; } impl<T: fmt::Show> ToString for T { fn to_string(&self) -> String { let mut buf = Vec::<u8>::new(); let _ = fmt::write(&mut buf, format_args!("{}", *self)); String::from_utf8(buf).unwrap() } } impl IntoCow<'static, String, str> for String { fn into_cow(self) -> CowString<'static> { Cow::Owned(self) } } impl<'a> IntoCow<'a, String, str> for &'a str { fn into_cow(self) -> CowString<'a> { Cow::Borrowed(self) } } /// Unsafe operations #[deprecated] pub mod raw { use super::String; use vec::Vec; /// Creates a new `String` from a length, capacity, and pointer. /// /// This is unsafe because: /// * We call `Vec::from_raw_parts` to get a `Vec<u8>`; /// * We assume that the `Vec` contains valid UTF-8. #[inline] #[deprecated = "renamed to String::from_raw_parts"] pub unsafe fn from_parts(buf: *mut u8, length: uint, capacity: uint) -> String { String::from_raw_parts(buf, length, capacity) } /// Creates a `String` from a `*const u8` buffer of the given length. /// /// This function is unsafe because of two reasons: /// /// * A raw pointer is dereferenced and transmuted to `&[u8]`; /// * The slice is not checked to see whether it contains valid UTF-8. #[deprecated = "renamed to String::from_raw_buf_len"] pub unsafe fn from_buf_len(buf: *const u8, len: uint) -> String { String::from_raw_buf_len(buf, len) } /// Creates a `String` from a null-terminated `*const u8` buffer. /// /// This function is unsafe because we dereference memory until we find the NUL character, /// which is not guaranteed to be present. Additionally, the slice is not checked to see /// whether it contains valid UTF-8 #[deprecated = "renamed to String::from_raw_buf"] pub unsafe fn from_buf(buf: *const u8) -> String { String::from_raw_buf(buf) } /// Converts a vector of bytes to a new `String` without checking if /// it contains valid UTF-8. This is unsafe because it assumes that /// the UTF-8-ness of the vector has already been validated. #[inline] #[deprecated = "renamed to String::from_utf8_unchecked"] pub unsafe fn from_utf8(bytes: Vec<u8>) -> String { String::from_utf8_unchecked(bytes) } } /// A clone-on-write string #[stable] pub type CowString<'a> = Cow<'a, String, str>; #[allow(deprecated)] impl<'a> Str for CowString<'a> { #[inline] fn as_slice<'b>(&'
-> &'b str { (**self).as_slice() } } #[cfg(test)] mod tests { use prelude::*; use test::Bencher; use str::Utf8Error; use str; use super::as_string; #[test] fn test_as_string() { let x = "foo"; assert_eq!(x, as_string(x).as_slice()); } #[test] fn test_from_str() { let owned: Option<::std::string::String> = from_str("string"); assert_eq!(owned.as_ref().map(|s| s.as_slice()), Some("string")); } #[test] fn test_from_utf8() { let xs = b"hello".to_vec(); assert_eq!(String::from_utf8(xs).unwrap(), String::from_str("hello")); let xs = "ศไทย中华Việt Nam".as_bytes().to_vec(); assert_eq!(String::from_utf8(xs).unwrap(), String::from_str("ศไทย中华Việt Nam")); let xs = b"hello\xFF".to_vec(); let err = String::from_utf8(xs).err().unwrap(); assert_eq!(err.utf8_error(), Utf8Error::TooShort); assert_eq!(err.into_bytes(), b"hello\xff".to_vec()); } #[test] fn test_from_utf8_lossy() { let xs = b"hello"; let ys: str::CowString = "hello".into_cow(); assert_eq!(String::from_utf8_lossy(xs), ys); let xs = "ศไทย中华Việt Nam".as_bytes(); let ys: str::CowString = "ศไทย中华Việt Nam".into_cow(); assert_eq!(String::from_utf8_lossy(xs), ys); let xs = b"Hello\xC2 There\xFF Goodbye"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("Hello\u{FFFD} There\u{FFFD} Goodbye").into_cow()); let xs = b"Hello\xC0\x80 There\xE6\x83 Goodbye"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("Hello\u{FFFD}\u{FFFD} There\u{FFFD} Goodbye").into_cow()); let xs = b"\xF5foo\xF5\x80bar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}\u{FFFD}bar").into_cow()); let xs = b"\xF1foo\xF1\x80bar\xF1\x80\x80baz"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}baz").into_cow()); let xs = b"\xF4foo\xF4\x80bar\xF4\xBFbaz"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}foo\u{FFFD}bar\u{FFFD}\u{FFFD}baz").into_cow()); let xs = b"\xF0\x80\x80\x80foo\xF0\x90\x80\x80bar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}\ foo\u{10000}bar").into_cow()); // surrogates let xs = b"\xED\xA0\x80foo\xED\xBF\xBFbar"; assert_eq!(String::from_utf8_lossy(xs), String::from_str("\u{FFFD}\u{FFFD}\u{FFFD}foo\ \u{FFFD}\u{FFFD}\u{FFFD}bar").into_cow()); } #[test] fn test_from_utf16() { let pairs = [(String::from_str("𐍅𐌿𐌻𐍆𐌹𐌻𐌰\n"), vec![0xd800_u16, 0xdf45_u16, 0xd800_u16, 0xdf3f_u16, 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf46_u16, 0xd800_u16, 0xdf39_u16, 0xd800_u16, 0xdf3b_u16, 0xd800_u16, 0xdf30_u16, 0x000a_u16]), (String::from_str("𐐒𐑉𐐮𐑀𐐲𐑋 𐐏𐐲𐑍\n"), vec![0xd801_u16, 0xdc12_u16, 0xd801_u16, 0xdc49_u16, 0xd801_u16, 0xdc2e_u16, 0xd801_u16, 0xdc40_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4b_u16, 0x0020_u16, 0xd801_u16, 0xdc0f_u16, 0xd801_u16, 0xdc32_u16, 0xd801_u16, 0xdc4d_u16, 0x000a_u16]), (String::from_str("𐌀𐌖𐌋𐌄𐌑𐌉·𐌌𐌄𐌕𐌄𐌋𐌉𐌑\n"), vec![0xd800_u16, 0xdf00_u16, 0xd800_u16, 0xdf16_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf04_u16, 0xd800_u16, 0xdf11_u16, 0xd800_u16, 0xdf09_u16, 0x00b7_u16, 0xd800_u16, 0xdf0c_u16, 0xd800_u16, 0xdf04_u16, 0xd800_u16, 0xdf15_u16, 0xd800_u16, 0xdf04_u16, 0xd800_u16, 0xdf0b_u16, 0xd800_u16, 0xdf09_u16, 0xd800_u16, 0xdf11_u16, 0x000a_u16 ]), (String::from_str("𐒋𐒘𐒈𐒑𐒛𐒒 𐒕𐒓 𐒈𐒚𐒍 𐒏𐒜𐒒𐒖𐒆 𐒕𐒆\n"), vec![0xd801_u16, 0xdc8b_u16, 0xd801_u16, 0xdc98_u16, 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc91_u16, 0xd801_u16, 0xdc9b_u16, 0xd801_u16, 0xdc92_u16, 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc93_u16, 0x0020_u16, 0xd801_u16, 0xdc88_u16, 0xd801_u16, 0xdc9a_u16, 0xd801_u16, 0xdc8d_u16, 0x0020_u16, 0xd801_u16, 0xdc8f_u16, 0xd801_u16, 0xdc9c_u16, 0xd801_u16, 0xdc92_u16, 0xd801_u16, 0xdc96_u16, 0xd801_u16, 0xdc86_u16, 0x0020_u16, 0xd801_u16, 0xdc95_u16, 0xd801_u16, 0xdc86_u16, 0x000a_u16 ]), // Issue #12318, even-numbered non-BMP planes (String::from_str("\u{20000}"), vec![0xD840, 0xDC00])]; for p in pairs.iter() { let (s, u) = (*p).clone(); let s_as_utf16 = s.utf16_units().collect::<Vec<u16>>(); let u_as_string = String::from_utf16(u.as_slice()).unwrap(); assert!(::unicode::str::is_utf16(u.as_slice())); assert_eq!(s_as_utf16, u); assert_eq!(u_as_string, s); assert_eq!(String::from_utf16_lossy(u.as_slice()), s); assert_eq!(String::from_utf16(s_as_utf16.as_slice()).unwrap(), s); assert_eq!(u_as_string.utf16_units().collect::<Vec<u16>>(), u); } } #[test] fn test_utf16_invalid() { // completely positive cases tested above. // lead + eof assert!(String::from_utf16(&[0xD800]).is_err()); // lead + lead assert!(String::from_utf16(&[0xD800, 0xD800]).is_err()); // isolated trail assert!(String::from_utf16(&[0x0061, 0xDC00]).is_err()); // general assert!(String::from_utf16(&[0xD800, 0xd801, 0xdc8b, 0xD800]).is_err()); } #[test] fn test_from_utf16_lossy() { // completely positive cases tested above. // lead + eof assert_eq!(String::from_utf16_lossy(&[0xD800]), String::from_str("\u{FFFD}")); // lead + lead assert_eq!(String::from_utf16_lossy(&[0xD800, 0xD800]), String::from_str("\u{FFFD}\u{FFFD}")); // isolated trail assert_eq!(String::from_utf16_lossy(&[0x0061, 0xDC00]), String::from_str("a\u{FFFD}")); // general assert_eq!(String::from_utf16_lossy(&[0xD800, 0xd801, 0xdc8b, 0xD800]), String::from_str("\u{FFFD}𐒋\u{FFFD}")); } #[test] fn test_from_buf_len() { unsafe { let a = vec![65u8, 65, 65, 65, 65, 65, 65, 0]; assert_eq!(super::raw::from_buf_len(a.as_ptr(), 3), String::from_str("AAA")); } } #[test] fn test_from_buf() { unsafe { let a = vec![65, 65, 65, 65, 65, 65, 65, 0]; let b = a.as_ptr(); let c = super::raw::from_buf(b); assert_eq!(c, String::from_str("AAAAAAA")); } } #[test] fn test_push_bytes() { let mut s = String::from_str("ABC"); unsafe { let mv = s.as_mut_vec(); mv.push_all(&[b'D']); } assert_eq!(s, "ABCD"); } #[test] fn test_push_str() { let mut s = String::new(); s.push_str(""); assert_eq!(s.slice_from(0), ""); s.push_str("abc"); assert_eq!(s.slice_from(0), "abc"); s.push_str("ประเทศไทย中华Việt Nam"); assert_eq!(s.slice_from(0), "abcประเทศไทย中华Việt Nam"); } #[test] fn test_push() { let mut data = String::from_str("ประเทศไทย中"); data.push('华'); data.push('b'); // 1 byte data.push('¢'); // 2 byte data.push('€'); // 3 byte data.push('𤭢'); // 4 byte assert_eq!(data, "ประเทศไทย中华b¢€𤭢"); } #[test] fn test_pop() { let mut data = String::from_str("ประเทศไทย中华b¢€𤭢"); assert_eq!(data.pop().unwrap(), '𤭢'); // 4 bytes assert_eq!(data.pop().unwrap(), '€'); // 3 bytes assert_eq!(data.pop().unwrap(), '¢'); // 2 bytes assert_eq!(data.pop().unwrap(), 'b'); // 1 bytes assert_eq!(data.pop().unwrap(), '华'); assert_eq!(data, "ประเทศไทย中"); } #[test] fn test_str_truncate() { let mut s = String::from_str("12345"); s.truncate(5); assert_eq!(s, "12345"); s.truncate(3); assert_eq!(s, "123"); s.truncate(0); assert_eq!(s, ""); let mut s = String::from_str("12345"); let p = s.as_ptr(); s.truncate(3); s.push_str("6"); let p_ = s.as_ptr(); assert_eq!(p_, p); } #[test] #[should_fail] fn test_str_truncate_invalid_len() { let mut s = String::from_str("12345"); s.truncate(6); } #[test] #[should_fail] fn test_str_truncate_split_codepoint() { let mut s = String::from_str("\u{FC}"); // ü s.truncate(1); } #[test] fn test_str_clear() { let mut s = String::from_str("12345"); s.clear(); assert_eq!(s.len(), 0); assert_eq!(s, ""); } #[test] fn test_str_add() { let a = String::from_str("12345"); let b = a + "2"; let b = b + "2"; assert_eq!(b.len(), 7); assert_eq!(b, "1234522"); } #[test] fn remove() { let mut s = "ศไทย中华Việt Nam; foobar".to_string();; assert_eq!(s.remove(0), 'ศ'); assert_eq!(s.len(), 33); assert_eq!(s, "ไทย中华Việt Nam; foobar"); assert_eq!(s.remove(17), 'ệ'); assert_eq!(s, "ไทย中华Vit Nam; foobar"); } #[test] #[should_fail] fn remove_bad() { "ศ".to_string().remove(1); } #[test] fn insert() { let mut s = "foobar".to_string(); s.insert(0, 'ệ'); assert_eq!(s, "ệfoobar"); s.insert(6, 'ย'); assert_eq!(s, "ệfooยbar"); } #[test] #[should_fail] fn insert_bad1() { "".to_string().insert(1, 't'); } #[test] #[should_fail] fn insert_bad2() { "ệ".to_string().insert(1, 't'); } #[test] fn test_slicing() { let s = "foobar".to_string(); assert_eq!("foobar", s[]); assert_eq!("foo", s[..3]); assert_eq!("bar", s[3..]); assert_eq!("oob", s[1..4]); } #[test] fn test_simple_types() { assert_eq!(1i.to_string(), "1"); assert_eq!((-1i).to_string(), "-1"); assert_eq!(200u.to_string(), "200"); assert_eq!(2u8.to_string(), "2"); assert_eq!(true.to_string(), "true"); assert_eq!(false.to_string(), "false"); assert_eq!(().to_string(), "()"); assert_eq!(("hi".to_string()).to_string(), "hi"); } #[test] fn test_vectors() { let x: Vec<int> = vec![]; assert_eq!(x.to_string(), "[]"); assert_eq!((vec![1i]).to_string(), "[1]"); assert_eq!((vec![1i, 2, 3]).to_string(), "[1, 2, 3]"); assert!((vec![vec![], vec![1i], vec![1i, 1]]).to_string() == "[[], [1], [1, 1]]"); } #[test] fn test_from_iterator() { let s = "ศไทย中华Việt Nam".to_string(); let t = "ศไทย中华"; let u = "Việt Nam"; let a: String = s.chars().collect(); assert_eq!(s, a); let mut b = t.to_string(); b.extend(u.chars()); assert_eq!(s, b); let c: String = vec![t, u].into_iter().collect(); assert_eq!(s, c); let mut d = t.to_string(); d.extend(vec![u].into_iter()); assert_eq!(s, d); } #[bench] fn bench_with_capacity(b: &mut Bencher) { b.iter(|| { String::with_capacity(100) }); } #[bench] fn bench_push_str(b: &mut Bencher) { let s = "ศไทย中华Việt Nam; Mary had a little lamb, Little lamb"; b.iter(|| { let mut r = String::new(); r.push_str(s); }); } const REPETITIONS: u64 = 10_000; #[bench] fn bench_push_str_one_byte(b: &mut Bencher) { b.bytes = REPETITIONS; b.iter(|| { let mut r = String::new(); for _ in range(0, REPETITIONS) { r.push_str("a") } }); } #[bench] fn bench_push_char_one_byte(b: &mut Bencher) { b.bytes = REPETITIONS; b.iter(|| { let mut r = String::new(); for _ in range(0, REPETITIONS) { r.push('a') } }); } #[bench] fn bench_push_char_two_bytes(b: &mut Bencher) { b.bytes = REPETITIONS * 2; b.iter(|| { let mut r = String::new(); for _ in range(0, REPETITIONS) { r.push('â') } }); } #[bench] fn from_utf8_lossy_100_ascii(b: &mut Bencher) { let s = b"Hello there, the quick brown fox jumped over the lazy dog! \ Lorem ipsum dolor sit amet, consectetur. "; assert_eq!(100, s.len()); b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_100_multibyte(b: &mut Bencher) { let s = "𐌀𐌖𐌋𐌄𐌑𐌉ปรدولة الكويتทศไทย中华𐍅𐌿𐌻𐍆𐌹𐌻𐌰".as_bytes(); assert_eq!(100, s.len()); b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_invalid(b: &mut Bencher) { let s = b"Hello\xC0\x80 There\xE6\x83 Goodbye"; b.iter(|| { let _ = String::from_utf8_lossy(s); }); } #[bench] fn from_utf8_lossy_100_invalid(b: &mut Bencher) { let s = Vec::from_elem(100, 0xF5u8); b.iter(|| { let _ = String::from_utf8_lossy(s.as_slice()); }); } }
b self)
message.rs
//! Cached message-related models. use serde::Serialize; use twilight_model::{ application::{component::Component, interaction::InteractionType}, channel::{ embed::Embed, message::{ sticker::MessageSticker, Message, MessageActivity, MessageApplication, MessageFlags, MessageInteraction, MessageReaction, MessageReference, MessageType, }, Attachment, ChannelMention, }, datetime::Timestamp, guild::PartialMember, id::{ marker::{ ApplicationMarker, ChannelMarker, GuildMarker, InteractionMarker, MessageMarker, RoleMarker, UserMarker, WebhookMarker, }, Id, }, }; /// Information about the message interaction. #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CachedMessageInteraction { id: Id<InteractionMarker>, #[serde(rename = "type")] kind: InteractionType, name: String, user_id: Id<UserMarker>, } impl CachedMessageInteraction { /// ID of the interaction. pub const fn id(&self) -> Id<InteractionMarker> { self.id } /// Type of the interaction. pub const fn kind(&self) -> InteractionType { self.kind } /// Name of the interaction used. pub fn name(&self) -> &str { &self.name } /// ID of the user who invoked the interaction. pub const fn
(&self) -> Id<UserMarker> { self.user_id } /// Construct a cached message interaction from its [`twilight_model`] form. #[allow(clippy::missing_const_for_fn)] pub(crate) fn from_model(message_interaction: MessageInteraction) -> Self { // Reasons for dropping fields: // // - `member`: we have the user's ID from the `user_id` field let MessageInteraction { id, kind, member: _, name, user, } = message_interaction; Self { id, kind, name, user_id: user.id, } } } /// Represents a cached [`Message`]. /// /// [`Message`]: twilight_model::channel::Message #[derive(Clone, Debug, Eq, PartialEq, Serialize)] pub struct CachedMessage { activity: Option<MessageActivity>, application: Option<MessageApplication>, application_id: Option<Id<ApplicationMarker>>, pub(crate) attachments: Vec<Attachment>, author: Id<UserMarker>, channel_id: Id<ChannelMarker>, components: Vec<Component>, pub(crate) content: String, pub(crate) edited_timestamp: Option<Timestamp>, pub(crate) embeds: Vec<Embed>, flags: Option<MessageFlags>, guild_id: Option<Id<GuildMarker>>, id: Id<MessageMarker>, interaction: Option<CachedMessageInteraction>, kind: MessageType, member: Option<PartialMember>, mention_channels: Vec<ChannelMention>, pub(crate) mention_everyone: bool, pub(crate) mention_roles: Vec<Id<RoleMarker>>, pub(crate) mentions: Vec<Id<UserMarker>>, pub(crate) pinned: bool, pub(crate) reactions: Vec<MessageReaction>, reference: Option<MessageReference>, sticker_items: Vec<MessageSticker>, thread_id: Option<Id<ChannelMarker>>, pub(crate) timestamp: Timestamp, pub(crate) tts: bool, webhook_id: Option<Id<WebhookMarker>>, } impl CachedMessage { /// For rich presence chat embeds, the activity object. pub const fn activity(&self) -> Option<&MessageActivity> { self.activity.as_ref() } /// For interaction responses, the ID of the interaction's application. pub const fn application(&self) -> Option<&MessageApplication> { self.application.as_ref() } /// Associated application's ID. /// /// Sent if the message is a response to an Interaction. pub const fn application_id(&self) -> Option<Id<ApplicationMarker>> { self.application_id } /// List of attached files. /// /// Refer to the documentation for [`Message::attachments`] for caveats with /// receiving the attachments of messages. /// /// [`Message::attachments`]: twilight_model::channel::Message::attachments pub fn attachments(&self) -> &[Attachment] { &self.attachments } /// ID of the message author. /// /// If the author is a webhook, this is its ID. pub const fn author(&self) -> Id<UserMarker> { self.author } /// ID of the channel the message was sent in. pub const fn channel_id(&self) -> Id<ChannelMarker> { self.channel_id } /// List of provided components, such as buttons. /// /// Refer to the documentation for [`Message::components`] for caveats with /// receiving the components of messages. /// /// [`Message::components`]: twilight_model::channel::Message::components pub fn components(&self) -> &[Component] { &self.components } /// Content of a message. /// /// Refer to the documentation for [`Message::content`] for caveats with /// receiving the content of messages. /// /// [`Message::content`]: twilight_model::channel::Message::content pub fn content(&self) -> &str { &self.content } /// [`Timestamp`] of the date the message was last edited. pub const fn edited_timestamp(&self) -> Option<Timestamp> { self.edited_timestamp } /// List of embeds. /// /// Refer to the documentation for [`Message::embeds`] for caveats with /// receiving the embeds of messages. /// /// [`Message::embeds`]: twilight_model::channel::Message::embeds pub fn embeds(&self) -> &[Embed] { &self.embeds } /// Message flags. pub const fn flags(&self) -> Option<MessageFlags> { self.flags } /// ID of the guild the message was sent in, if there is one. pub const fn guild_id(&self) -> Option<Id<GuildMarker>> { self.guild_id } /// ID of the message. pub const fn id(&self) -> Id<MessageMarker> { self.id } /// Information about the message interaction. pub const fn interaction(&self) -> Option<&CachedMessageInteraction> { self.interaction.as_ref() } /// Type of the message. pub const fn kind(&self) -> MessageType { self.kind } /// Member data for the author, if there is any. pub const fn member(&self) -> Option<&PartialMember> { self.member.as_ref() } /// Channels mentioned in the content. pub fn mention_channels(&self) -> &[ChannelMention] { &self.mention_channels } /// Whether or not '@everyone' or '@here' is mentioned in the content. pub const fn mention_everyone(&self) -> bool { self.mention_everyone } /// Roles mentioned in the content. pub fn mention_roles(&self) -> &[Id<RoleMarker>] { &self.mention_roles } /// Users mentioned in the content. pub fn mentions(&self) -> &[Id<UserMarker>] { &self.mentions } /// Whether or not the message is pinned. pub const fn pinned(&self) -> bool { self.pinned } /// Reactions to the message. pub fn reactions(&self) -> &[MessageReaction] { &self.reactions } /// Message reference. pub const fn reference(&self) -> Option<&MessageReference> { self.reference.as_ref() } /// Stickers within the message. pub fn sticker_items(&self) -> &[MessageSticker] { &self.sticker_items } /// ID of the thread the message was sent in. pub const fn thread_id(&self) -> Option<Id<ChannelMarker>> { self.thread_id } /// [`Timestamp`] of the date the message was sent. pub const fn timestamp(&self) -> Timestamp { self.timestamp } /// Whether the message is text-to-speech. pub const fn tts(&self) -> bool { self.tts } /// For messages sent by webhooks, the webhook ID. pub const fn webhook_id(&self) -> Option<Id<WebhookMarker>> { self.webhook_id } /// Construct a cached message from its [`twilight_model`] form. pub(crate) fn from_model(message: Message) -> Self { let Message { activity, application, application_id, attachments, author, channel_id, components, content, edited_timestamp, embeds, flags, guild_id, id, interaction, kind, member, mention_channels, mention_everyone, mention_roles, mentions, pinned, reactions, reference, referenced_message: _, sticker_items, timestamp, thread, tts, webhook_id, } = message; Self { id, activity, application, application_id, attachments, author: author.id, channel_id, components, content, edited_timestamp, embeds, flags, guild_id, interaction: interaction.map(CachedMessageInteraction::from_model), kind, member, mention_channels, mention_everyone, mention_roles, mentions: mentions.into_iter().map(|mention| mention.id).collect(), pinned, reactions, reference, sticker_items, thread_id: thread.map(|thread| thread.id), timestamp, tts, webhook_id, } } } impl From<Message> for CachedMessage { fn from(message: Message) -> Self { Self::from_model(message) } } #[cfg(test)] mod tests { use super::{CachedMessage, CachedMessageInteraction}; use serde::Serialize; use static_assertions::{assert_fields, assert_impl_all}; use std::fmt::Debug; use twilight_model::channel::message::Message; assert_fields!( CachedMessage: activity, application, application_id, attachments, author, channel_id, components, content, edited_timestamp, embeds, flags, guild_id, id, interaction, kind, member, mention_channels, mention_everyone, mention_roles, mentions, pinned, reactions, reference, sticker_items, thread_id, timestamp, tts, webhook_id ); assert_impl_all!( CachedMessage: Clone, Debug, Eq, From<Message>, PartialEq, Send, Serialize, Sync, ); assert_fields!(CachedMessageInteraction: id, kind, name, user_id); assert_impl_all!( CachedMessageInteraction: Clone, Debug, Eq, PartialEq, Send, Serialize, Sync, ); }
user_id
moved-package-cache.ts
import { join, dirname, resolve, sep, isAbsolute } from 'path'; import { ensureSymlinkSync, readdirSync, readlinkSync, realpathSync, lstatSync } from 'fs-extra'; import { Memoize } from 'typescript-memoize'; import { PackageCache, Package, getOrCreate } from '@embroider/core'; import { MacrosConfig } from '@embroider/macros'; function assertNoTildeExpansion(source: string, target: string) { if (target.includes('~')) { throw new Error( `The symbolic link: ${source}'s target: ${target} contained a bash expansion '~' which is not supported.` ); } } export class MovablePackageCache extends PackageCache { constructor(private macrosConfig: MacrosConfig) { super(); } moveAddons(appSrcDir: string, destDir: string): MovedPackageCache { // start with the plain old app package let origApp = this.getApp(appSrcDir); // discover the set of all packages that will need to be moved into the // workspace let movedSet = new MovedSet(origApp); return new MovedPackageCache(this.rootCache, this.resolutionCache, destDir, movedSet, origApp, this.macrosConfig); } }
readonly appDestDir: string; private commonSegmentCount: number; readonly moved: Map<Package, Package> = new Map(); constructor( rootCache: PackageCache['rootCache'], resolutionCache: PackageCache['resolutionCache'], private destDir: string, movedSet: MovedSet, private origApp: Package, private macrosConfig: MacrosConfig ) { super(); // that gives us our common segment count, which enables localPath mapping this.commonSegmentCount = movedSet.commonSegmentCount; // so we can now determine where the app will go inside the workspace this.appDestDir = this.localPath(origApp.root); this.macrosConfig.packageMoved(origApp.root, this.appDestDir); for (let originalPkg of movedSet.packages) { // Update our rootCache so we don't need to rediscover moved packages let movedPkg; if (originalPkg === origApp) { // this wraps the original app package with one that will use moved // dependencies. The app itself hasn't moved yet, which is why a proxy // is needed at this level. movedPkg = packageProxy(origApp, (pkg: Package) => this.moved.get(pkg) || pkg); this.app = movedPkg; rootCache.set(movedPkg.root, movedPkg); } else { movedPkg = this.movedPackage(originalPkg); this.moved.set(originalPkg, movedPkg); this.macrosConfig.packageMoved(originalPkg.root, movedPkg.root); } // Update our resolutionCache so we still know as much about the moved // packages as we did before we moved them, without redoing package // resolution. let resolutions = new Map(); for (let dep of originalPkg.dependencies) { if (movedSet.packages.has(dep)) { resolutions.set(dep.name, this.movedPackage(dep)); } else { resolutions.set(dep.name, dep); } } resolutionCache.set(movedPkg, resolutions); } this.rootCache = rootCache; this.resolutionCache = resolutionCache; } private movedPackage(originalPkg: Package): Package { let newRoot = this.localPath(originalPkg.root); return getOrCreate(this.rootCache, newRoot, () => new Package(newRoot, this, false)); } private localPath(filename: string) { return join(this.destDir, ...pathSegments(filename).slice(this.commonSegmentCount)); } // hunt for symlinks that may be needed to do node_modules resolution from the // given path. async updatePreexistingResolvableSymlinks(): Promise<void> { let roots = this.originalRoots(); [...this.candidateDirs()].map(path => { let links = symlinksInNodeModules(path); for (let { source, target } of links) { let realTarget = realpathSync(resolve(dirname(source), target)); let pkg = roots.get(realTarget); if (pkg) { // we found a symlink that points at a package that was copied. // Replicate it in the new structure pointing at the new package. ensureSymlinkSync(pkg.root, this.localPath(source)); } } }); } // places that might have symlinks we need to mimic private candidateDirs(): Set<string> { let candidates = new Set() as Set<string>; let originalPackages = [this.origApp, ...this.moved.keys()]; for (let pkg of originalPackages) { let segments = pathSegments(pkg.root); let candidate = join(pkg.root, 'node_modules'); candidates.add(candidate); for (let i = segments.length - 1; i >= this.commonSegmentCount; i--) { if (segments[i - 1] !== 'node_modules') { let candidate = '/' + join(...segments.slice(0, i), 'node_modules'); if (candidates.has(candidate)) { break; } candidates.add(candidate); } } } return candidates; } private originalRoots(): Map<string, Package> { let originalRoots = new Map(); for (let [originalPackage, movedPackage] of this.moved.entries()) { originalRoots.set(originalPackage.root, movedPackage); } return originalRoots; } } function maybeReaddirSync(path: string) { try { return readdirSync(path); } catch (err) { if (err.code !== 'ENOTDIR' && err.code !== 'ENOENT') { throw err; } return []; } } function symlinksInNodeModules(path: string): { source: string; target: string }[] { let results: { source: string; target: string }[] = []; let names = maybeReaddirSync(path); names.map(name => { let source = join(path, name); let stats = lstatSync(source); if (stats.isSymbolicLink()) { let target = readlinkSync(source); assertNoTildeExpansion(source, target); results.push({ source, target }); } else if (stats.isDirectory() && name.startsWith('@')) { let innerNames = maybeReaddirSync(source); innerNames.map(innerName => { let innerSource = join(source, innerName); let innerStats = lstatSync(innerSource); if (innerStats.isSymbolicLink()) { let target = readlinkSync(innerSource); assertNoTildeExpansion(innerSource, target); results.push({ source: innerSource, target }); } }); } }); return results; } function pathSegments(filename: string) { let segments = filename.split(sep); if (isAbsolute(filename)) { segments.shift(); } return segments; } class MovedSet { private mustMove: Map<Package, boolean> = new Map(); constructor(private app: Package) { this.check(app); } private check(pkg: Package): boolean { if (this.mustMove.has(pkg)) { return this.mustMove.get(pkg)!; } // non-ember packages don't need to move if (pkg !== this.app && !pkg.isEmberPackage()) { this.mustMove.set(pkg, false); return false; } let mustMove = // The app always moves (because we need a place to mash all the // addon-provided "app-js" trees), pkg === this.app || // For the same reason, engines need to move (we need a place to mash all // their child addon's provided app-js trees into) pkg.isEngine() || // any other ember package that isn't native v2 must move because we've // got to rewrite them !pkg.isV2Ember(); // this is a partial answer. After we check our children, our own `mustMove` // may change from false to true. But it's OK that our children see false in // that case, because they don't need to move on our behalf. // // We need to already be in the `this.mustMove` cache at this moment in // order to avoid infinite recursion if any of our children end up depending // back on us. this.mustMove.set(pkg, mustMove); for (let dep of pkg.dependencies) { // or if any of your deps need to move mustMove = this.check(dep) || mustMove; } this.mustMove.set(pkg, mustMove); return mustMove; } @Memoize() get packages(): Set<Package> { let result = new Set() as Set<Package>; for (let [pkg, mustMove] of this.mustMove) { if (mustMove) { result.add(pkg); } } return result; } // the npm structure we're shadowing could have a dependency nearly anywhere // on disk. We want to maintain their relations to each other. So we must find // the point in the filesystem that contains all of them, which could even be // "/" (for example, if you npm-linked a dependency that lives in /tmp). // // The commonSegmentCount is how many leading path segments are shared by all // our packages. @Memoize() get commonSegmentCount(): number { return [...this.packages].reduce((longestPrefix, pkg) => { let candidate = pathSegments(pkg.root); let shorter, longer; if (longestPrefix.length > candidate.length) { shorter = candidate; longer = longestPrefix; } else { shorter = longestPrefix; longer = candidate; } let i = 0; for (; i < shorter.length; i++) { if (shorter[i] !== longer[i]) { break; } } return shorter.slice(0, i); }, pathSegments(this.app.root)).length; } } function packageProxy(pkg: Package, getMovedPackage: (pkg: Package) => Package) { let p: Package = new Proxy(pkg, { get(pkg: Package, prop: string | number | symbol) { if (prop === 'dependencies') { return pkg.dependencies.map(getMovedPackage); } if (prop === 'nonResolvableDeps') { if (!pkg.nonResolvableDeps) { return pkg.nonResolvableDeps; } return new Map([...pkg.nonResolvableDeps.values()].map(dep => [dep.name, getMovedPackage(dep)])); } if (prop === 'findDescendants') { return pkg.findDescendants.bind(p); } return (pkg as any)[prop]; }, }); return p; }
export class MovedPackageCache extends PackageCache { readonly app!: Package;
user.dto.ts
import { ApiModelProperty } from '@nestjs/swagger'; import { IsString, IsDefined, IsEmail, IsDate, IsEnum } from 'class-validator'; import { Type } from 'class-transformer'; import { IUser } from '../repository/schema/user.entity'; import { Role } from '../repository/enum/role.enum'; export class
implements IUser { @IsString() @ApiModelProperty() _id?: string; @IsEmail() @IsDefined() @ApiModelProperty() email: string; @IsString() @IsDefined() @ApiModelProperty() password: string; @IsDefined() @IsEnum(Role) @ApiModelProperty() role: Role; @IsString() @IsDefined() @ApiModelProperty() name: string; @IsString() @Type(() => Date) @ApiModelProperty() lastLoginAttempt?: Date; @IsDate() @Type(() => Date) @ApiModelProperty() lastLoginSuccessful?: Date; @ApiModelProperty() @Type(() => Date) @IsDate() createdOn?: Date; @ApiModelProperty() @Type(() => Date) @IsDate() updatedOn?: Date; }
UserDto
cap14.rs
#[doc = "Register `CAP14` reader"] pub struct
(crate::R<CAP14_SPEC>); impl core::ops::Deref for R { type Target = crate::R<CAP14_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl From<crate::R<CAP14_SPEC>> for R { #[inline(always)] fn from(reader: crate::R<CAP14_SPEC>) -> Self { R(reader) } } #[doc = "Register `CAP14` writer"] pub struct W(crate::W<CAP14_SPEC>); impl core::ops::Deref for W { type Target = crate::W<CAP14_SPEC>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } impl core::ops::DerefMut for W { #[inline(always)] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl From<crate::W<CAP14_SPEC>> for W { #[inline(always)] fn from(writer: crate::W<CAP14_SPEC>) -> Self { W(writer) } } #[doc = "Field `CAPn_L` reader - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the lower 16 bits of the 32-bit value at which this register was last captured."] pub struct CAPN_L_R(crate::FieldReader<u16, u16>); impl CAPN_L_R { #[inline(always)] pub(crate) fn new(bits: u16) -> Self { CAPN_L_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CAPN_L_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CAPn_L` writer - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the lower 16 bits of the 32-bit value at which this register was last captured."] pub struct CAPN_L_W<'a> { w: &'a mut W, } impl<'a> CAPN_L_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !0xffff) | (value as u32 & 0xffff); self.w } } #[doc = "Field `CAPn_H` reader - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the upper 16 bits of the 32-bit value at which this register was last captured."] pub struct CAPN_H_R(crate::FieldReader<u16, u16>); impl CAPN_H_R { #[inline(always)] pub(crate) fn new(bits: u16) -> Self { CAPN_H_R(crate::FieldReader::new(bits)) } } impl core::ops::Deref for CAPN_H_R { type Target = crate::FieldReader<u16, u16>; #[inline(always)] fn deref(&self) -> &Self::Target { &self.0 } } #[doc = "Field `CAPn_H` writer - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the upper 16 bits of the 32-bit value at which this register was last captured."] pub struct CAPN_H_W<'a> { w: &'a mut W, } impl<'a> CAPN_H_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u16) -> &'a mut W { self.w.bits = (self.w.bits & !(0xffff << 16)) | ((value as u32 & 0xffff) << 16); self.w } } impl R { #[doc = "Bits 0:15 - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the lower 16 bits of the 32-bit value at which this register was last captured."] #[inline(always)] pub fn capn_l(&self) -> CAPN_L_R { CAPN_L_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:31 - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the upper 16 bits of the 32-bit value at which this register was last captured."] #[inline(always)] pub fn capn_h(&self) -> CAPN_H_R { CAPN_H_R::new(((self.bits >> 16) & 0xffff) as u16) } } impl W { #[doc = "Bits 0:15 - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the lower 16 bits of the 32-bit value at which this register was last captured."] #[inline(always)] pub fn capn_l(&mut self) -> CAPN_L_W { CAPN_L_W { w: self } } #[doc = "Bits 16:31 - When UNIFY = 0, read the 16-bit counter value at which this register was last captured. When UNIFY = 1, read the upper 16 bits of the 32-bit value at which this register was last captured."] #[inline(always)] pub fn capn_h(&mut self) -> CAPN_H_W { CAPN_H_W { w: self } } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.0.bits(bits); self } } #[doc = "SCT capture register of capture channel\n\nThis register you can [`read`](crate::generic::Reg::read), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cap14](index.html) module"] pub struct CAP14_SPEC; impl crate::RegisterSpec for CAP14_SPEC { type Ux = u32; } #[doc = "`read()` method returns [cap14::R](R) reader structure"] impl crate::Readable for CAP14_SPEC { type Reader = R; } #[doc = "`write(|w| ..)` method takes [cap14::W](W) writer structure"] impl crate::Writable for CAP14_SPEC { type Writer = W; } #[doc = "`reset()` method sets CAP14 to value 0"] impl crate::Resettable for CAP14_SPEC { #[inline(always)] fn reset_value() -> Self::Ux { 0 } }
R