repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
9Cloud/orion
site/guide/routes.tsx
2099
import * as React from "react"; import {action} from "mobx"; import {route} from "tide/router/route"; import {bind_all_methods} from "tide/utils/object"; import {Home} from "./views/home"; import {Interactions} from "./views/interactions"; import {UIComponents} from "./views/components"; import {HelpersPage} from "./views/helpers"; import {TypographyPage} from "./views/typography"; import {NavComponent} from "./views/nav"; import {FormsPage} from "./views/forms"; import {ColorsPage} from "./views/colors"; import {NotFound} from "./views/404"; class Controller { constructor() { bind_all_methods(this); } @action home_page(tide, request, params) { tide.render(request, Home, {}) } @action interactions_page(tide, request, params) { tide.render(request, Interactions, {}) } @action ui_page(tide, request, params) { tide.render(request, UIComponents, {}) } @action helpers_page(tide, request, params) { tide.render(request, HelpersPage, {}) } @action typography_page(tide, request, params) { tide.render(request, TypographyPage, {}) } @action nav_page(tide, request, params) { tide.render(request, NavComponent, {}) } @action forms_page(tide, request, params) { tide.render(request, FormsPage, {}) } @action color_page(tide, request, params) { tide.render(request, ColorsPage, {}) } @action not_found(tide, request, params) { tide.render(request, NotFound, {}) } } const controller = new Controller(); /** * @type Array.<Route> */ export const routes = [ route("/", controller.home_page, "home"), route("/interactions_page/", controller.interactions_page, "interactions_page"), route("/ui_page/", controller.ui_page, "ui_page"), route("/helpers_page/", controller.helpers_page, "helpers_page"), route("/typography_page/", controller.typography_page, "typography_page"), route("/nav_page/", controller.nav_page, "nav_page"), route("/forms_page/", controller.forms_page, "forms_page"), route("/color_page/", controller.color_page, "color_page"), route("/{path*}", controller.not_found, "not_found"), ];
mit
stivalet/PHP-Vulnerability-test-suite
Injection/CWE_90/safe/CWE_90__POST__whitelist_using_array__userByCN-sprintf_%s_simple_quote.php
1508
<?php /* Safe sample input : get the field UserData from the variable $_POST SANITIZE : use in_array to check if $tainted is in the white list construction : use of sprintf via a %s with simple quote */ /*Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.*/ $tainted = $_POST['UserData']; $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } $query = sprintf("(&(objectCategory=person)(objectClass=user)(cn='%s'))", $tainted); $ds=ldap_connect("localhost"); $r=ldap_bind($ds); $sr=ldap_search($ds,"o=My Company, c=US", $query); ldap_close($ds); ?>
mit
mikeireland/pyxao
doc/conf.py
9331
# -*- coding: utf-8 -*- # # pyxao documentation build configuration file, created by # sphinx-quickstart on Wed Nov 11 12:35:11 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys import os import shlex # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath('..')) # -- General configuration ------------------------------------------------ numpydoc_show_class_members = False # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.todo', 'sphinx.ext.pngmath', 'sphinx.ext.viewcode', 'numpydoc' ] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'pyxao' copyright = u'2016, Michael J. Ireland' author = u'Michael J. Ireland' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = '0.1' # The full version, including alpha/beta/rc tags. release = '0.1' # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all # documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. #keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = True # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'nature' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. #html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # "<project> v<release> documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. #html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a <link> tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' #html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value #html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. #html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = 'pyxaodoc' # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', # Latex figure (float) alignment #'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, 'pyxao.tex', u'pyxao Documentation', u'Michael J. Ireland', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ (master_doc, 'pyxao', u'pyxao Documentation', [author], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ (master_doc, 'pyxao', u'pyxao Documentation', author, 'pyxao', 'Python eXtreme AO tools.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. #texinfo_no_detailmenu = False
mit
julio73/scratchbook
code/fizzbuzz/fizzbuzz.py
321
import sys def fizzbuzz(number): for x in xrange(1, number+1): div5 = x%5 == 0 div3 = x%3 == 0 if div5 and div3: print "fizz-buzz" elif div3: print "buzz" elif div5: print "fizz" else: print x if __name__ == '__main__': if sys.argv[1:]: fizzbuzz(int(sys.argv[1]))
mit
Bullseyed/Bullseye
app/components/Threads/SingleThread.js
1990
import React, { Component } from 'react'; import { Row, Col, Button } from 'react-materialize'; import { connect } from 'react-redux'; import { upvoteThread } from '../../reducers/thread-reducer'; import Comments from './Comments'; import AddComment from './AddComment'; class SingleThread extends Component { constructor() { super(); this.state = { votingDisabled: false }; this.upvoteHandler = this.upvoteHandler.bind(this); } componentWillMount() { if (!this.props.currentUser) { this.setState({ votingDisabled: true }); } else if (this.props.thread.scoreAuthors && (this.props.thread.scoreAuthors.includes(this.props.currentUser.id))) { this.setState({ votingDisabled: true }); } } upvoteHandler() { this.setState({ votingDisabled: true }); this.props.upvote(this.props.thread, this.props.currentUser.id); } render() { return ( <div> <Row> <Col l={9} style={{ padding: 0 }}> <Row style={{ marginBottom: 0 }}> <b> Description: </b> </Row> <Row style={{ fontSize: 16 }}> {this.props.thread.description} </Row> </Col> <Col l={1} style={{ float: 'right' }}> <Row> <Button floating large className='green' waves='light' icon='thumb_up' onClick={this.upvoteHandler} disabled={this.state.votingDisabled ? true : false}> Upvote </Button> </Row> <Row className='center-align'> Score: {this.props.thread.score} </Row> </Col> </Row> <Row style={{ marginBottom: 0 }}> <b> Comments: </b> </Row> <Row style={{ fontSize: 12 }}> <Comments thread={this.props.thread} /> </Row> <Row> <AddComment thread={this.props.thread} /> </Row> </div> ); } } const mapStateToProps = ({ currentUser }) => ({ currentUser }); const mapDispatchToProps = dispatch => ({ upvote: (threadObj, userId) => dispatch(upvoteThread(threadObj, userId)) }); export default connect(mapStateToProps, mapDispatchToProps)(SingleThread);
mit
sygcom/diesel_2016
application/controllers/crm/bkp/Products_2016_09_12.php
13874
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Products extends CI_Controller { var $database_limit = 10; public function __construct() { parent::__construct(); $this->load->helper('crm'); $this->load->helper('common'); $this->load->library('Digg_Pagination'); //********************SET UP PAGINATION VALUES**************************** //set up per_page_value, per_page_seg, cur_page_seg and $data['pbase_url'] //************************************************************************ $this->load->helper('pagination'); $this->load->model('crm/Crm_product_model', 'crm_product_model'); $this->load->model('Product_model', 'product_model'); if (!is_logged_in()) { redirect("crm/admin/login"); } } public function index() { $_SESSION['search_products_listing'] = ""; $data['visible_product_count'] = $this->crm_product_model->get_visible_products_count(); $data['invisible_product_count'] = $this->crm_product_model->get_invisible_products_count(); $data['recent_products'] = $this->crm_product_model->get_recent_products(); $view_file_name = 'product_view'; $data['view_file_name'] = $view_file_name; $this->template->load_crm_view($view_file_name, $data); } public function search_product() { if ($this->input->post()) { $_SESSION['search_products_listing'] = $this->input->post(); } redirect('crm/products/product_list'); } public function _where_clause() { $appendquery = array(); $appendquery['where'] = ''; $appendquery['having'] = ''; $appendquery['visible'] = ''; if ($_SESSION['search_products_listing'] != '') { $searchdata = $_SESSION['search_products_listing']; foreach ($searchdata as $key => $val) { if ($val == '') { continue; } $val = trim($this->db->escape_like_str($val)); switch ($key) { case 'prod_name': $appendquery['where'].=" AND a.disp_name LIKE '%" . $val . "%' "; break; case 'prod_style': $appendquery['where'].=" AND a.style LIKE '%" . $val . "%' "; break; case 'prod_barcode': $appendquery['where'].=" AND c.barcode LIKE '%" . $val . "%' "; break; case 'product_date': $date = explode("-", trim($val)); $start_date = $date[0]; $end_date = $date[1]; $appendquery['where'].=' AND (ac.release_dt >= "' . date('Y-m-d', strtotime($start_date)) . '") AND (ac.release_dt <= "' . date('Y-m-d', strtotime($end_date)) . '")'; break; case 'amount_text': $amount_crit = ""; if ($searchdata['amount_criteria'] == "") { $amount_crit = " = "; } else { $amount_crit = $searchdata['amount_criteria']; } if ($val != 0 && $val != 0.00) { $appendquery['having'].=" AND ((c.price " . $amount_crit . " " . $val . ") OR (c.price_sale " . $amount_crit . " " . $val . "))"; } break; case 'visible': if ($val == "yes") { $appendquery['visible'] = "yes"; } else if ($val == "no") { $appendquery['visible'] = "no"; } else if ($val == "all") { $appendquery['visible'] = ""; } break; case 'gender': $gender = ""; if ($val == "Male") { $gender = "M"; $appendquery['where'].=" AND a.genderCode LIKE '%" . $gender . "%' "; } else if ($val == "Female") { $gender = "F"; $appendquery['where'].=" AND a.genderCode LIKE '%" . $gender . "%' "; } else if ($val == "Both") { $gender = ""; $appendquery['where'].=" AND (a.genderCode LIKE '%M%' OR a.genderCode LIKE '%F%' OR a.genderCode LIKE '%U%') "; } break; } } } return $appendquery; } public function product_list($per_page = '', $offset = '', $is_csv_export = '') { $all_products_detail = array(); $where = ""; $having = ''; $visible_query = ""; $all_products_detail_csv = array(); $data = array(); $search_data = isset($_SESSION['search_products_listing']) ? $_SESSION['search_products_listing'] : ''; if (!empty($search_data)) { $appendquery = $this->_where_clause(); } $per_page = 0; $per_page_value = $this->database_limit; $per_page_seg = 4; $cur_page_seg = 5; $per_page = ($per_page) ? $per_page : get_per_page($per_page_value, $per_page_seg); $data['per_page_records'] = $per_page; $offset = get_offset($cur_page_seg, $per_page); $data['offset'] = $offset; $appendLimit = ' LIMIT ' . $per_page . ' OFFSET ' . $offset; if (!empty($appendquery)) { $where.= isset($appendquery['where']) ? $appendquery['where'] : ""; $having.=isset($appendquery['having']) ? $appendquery['having'] : ""; $visible_query.=isset($appendquery['visible']) ? $appendquery['visible'] : ""; } if (isset($visible_query) && $visible_query != "") { if ($visible_query == "yes") { //$all_products_detail_query = ("SELECT a.*,c.barcode,b.attr_type,b.attr_code,b.attr_value,MAX(c.price) As Price,MAX(c.price_sale) As Price_sale, c.sku_idx,c.color,clridx,release_dt,sale_status FROM prod_mast a,prod_variation b,prod_barcode c,ap21_colour ac WHERE a.style = b.style AND b.style = c.style AND ac.clridx = c.color_idx AND b.attr_type = 'color' AND c.visible !='init' AND c.visible ='Yes' $where $having GROUP BY b.style ORDER BY `ac`.`release_dt` DESC "); $all_products_detail_query = ("SELECT a.*, b.attr_type,b.attr_code,b.attr_value,MAX(c.price) As Price,MAX(c.price_sale) As Price_sale, c.sku_idx,c.color,clridx,release_dt,sale_status FROM prod_mast a,prod_variation b,prod_barcode c,ap21_colour ac WHERE a.style = b.style AND b.style = c.style AND c.visible !='init' AND c.visible ='Yes' $where $having GROUP BY b.style ORDER BY `ac`.`release_dt` DESC"); } else if ($visible_query == "no") { $all_products_detail_query = ("SELECT a.*,c.barcode,b.attr_type,b.attr_code,b.attr_value,MAX(c.price) As Price,MAX(c.price_sale) As Price_sale, c.sku_idx,c.color,clridx,release_dt,sale_status FROM prod_mast a,prod_variation b,prod_barcode c,ap21_colour ac WHERE a.style = b.style AND b.style = c.style AND c.visible !='init' AND c.visible ='No' AND $where `a`.`product_mast_id` NOT IN (SELECT DISTINCT `a`.`product_mast_id` FROM prod_mast a,prod_variation b,prod_barcode c,ap21_colour ac WHERE a.style = b.style AND b.style = c.style AND c.visible !='init' AND c.visible ='YES' GROUP BY b.style ORDER BY `a`.`product_mast_id` ASC) $having GROUP BY b.style ORDER BY `ac`.`release_dt` DESC "); } } else { $all_products_detail_query = ("SELECT a.*, b.attr_type,b.attr_code,b.attr_value,MAX(c.price) As Price,MAX(c.price_sale) As Price_sale, c.sku_idx,c.color,clridx,release_dt,sale_status FROM prod_mast a,prod_variation b,prod_barcode c,ap21_colour ac WHERE a.style = b.style AND b.style = c.style AND c.visible !='init' $where $having GROUP BY b.style ORDER BY `ac`.`release_dt` DESC"); } $total_rows = ($this->db->query($all_products_detail_query)->num_rows() > 0) ? $this->db->query($all_products_detail_query)->num_rows() : 0; $sql_data_query = $all_products_detail_query . $appendLimit; $all_products_detail_res = $this->db->query($sql_data_query)->result(); if (isset($is_csv_export) && $is_csv_export == "csv") { $all_products_detail_csv = $this->db->query($all_products_detail_query)->result(); if (isset($all_products_detail_csv) && !empty($all_products_detail_csv)) { foreach ($all_products_detail_csv as $product_csv) { $product_price_sale = $product_csv->Price_sale; $product_price = $product_csv->Price; if ($product_price_sale != 0 && $product_price_sale != '' && $product_price_sale < $product_price): $product_price = $product_price_sale; else: $product_price = $product_price; endif; $product_csv->price = "$" . number_format($product_price, 2); $product_csv->release_dt = date('d M Y', strtotime($product_csv->release_dt)); } } return $all_products_detail_csv; } foreach ($all_products_detail_res as $key => $product_detail) { $image_path = get_image_path($product_detail->image_path, $product_detail->style); //COMMON HELPER $all_products_detail[$key]['image_path'] = $image_path; $all_products_detail[$key]['product_mast_id'] = $product_detail->product_mast_id; $all_products_detail[$key]['disp_name'] = trim($product_detail->disp_name); $all_products_detail[$key]['style'] = $product_detail->style; $product_price_sale = $product_detail->Price_sale; $product_price = $product_detail->Price; if ($product_price_sale != 0 && $product_price_sale != '' && $product_price_sale < $product_price): $product_price = $product_price_sale; else: $product_price = $product_price; endif; $all_products_detail[$key]['price'] = "$" . number_format($product_price, 2); $all_products_detail[$key]['barcode'] = $product_detail->barcode; $all_products_detail[$key]['sku_idx'] = $product_detail->sku_idx; $all_products_detail[$key]['release_dt'] = date('d M Y', strtotime($product_detail->release_dt)); } $data['pbase_url'] = base_url() . "crm/products/product_list"; $data['pagination'] = init_paginate($cur_page_seg, $total_rows, $per_page, $per_page_seg, $data['pbase_url']); $num_pages = ceil($total_rows / $per_page); if ($this->uri->segment(5) != 0) { $cur_page = $this->uri->segment(5); $cur_page = preg_replace("/[a-z\-]/", "", $cur_page); } else { $cur_page = 1; } $data['start_limit'] = ($cur_page > 1) ? (($per_page * ($cur_page - 1)) + 1) : "1"; $data['end_limit'] = ($cur_page == $num_pages) ? ($total_rows) : ($per_page * $cur_page); $data['total_rows'] = $total_rows; $data['searchdata'] = $search_data; $data['all_products_detail'] = $all_products_detail; $view_file_name = 'product_list'; $data['view_file_name'] = $view_file_name; $this->template->load_crm_view($view_file_name, $data); } public function export_csv() { $all_products = $this->product_list('', '', 'csv'); $total_products = array(); $k = 0; foreach ($all_products as $value) { $total_products[$k]['disp_name'] = trim($value->disp_name); $total_products[$k]['style'] = $value->style; $total_products[$k]['barcode'] = $value->barcode; $total_products[$k]['sku_idx'] = $value->sku_idx; $total_products[$k]['price'] = $value->price; $total_products[$k]['release_dt'] = $value->release_dt; $k++; } $csv_fields = array('Product Name', 'Style', 'Barcode', 'SkuIdx', 'Price', 'Date'); $file = fopen('excel/export_product_csv.csv', 'w'); fputcsv($file, $csv_fields); foreach ($total_products as $row) { fputcsv($file, $row); } fclose($file); header("Content-type: text/csv"); header("Content-Disposition: attachment; filename=export_product_csv.csv"); readfile('excel/export_product_csv.csv'); exit; } public function show_product_details() { $this->data = array(); $style = $this->input->post('style'); $visible = $this->input->post('visible'); if ($style != '') { $this->data['prod_arr'] = $this->crm_product_model->get_showproduct_detail($style, $visible); $this->data['prod_color'] = $this->crm_product_model->get_product_color($style, $visible); foreach ($this->data['prod_color'] as $key => $curr_color) { $this->data['prod_color'][$key]['size'] = $this->product_model->get_size($style, $curr_color['attr_code']); $this->data['prod_color'][$key]['length'] = $this->product_model->get_length($style, $curr_color['attr_code']); $this->data['prod_color'][$key]['product_images'] = $this->product_model->get_product_img_url($style, 1, $curr_color['attr_code']); } } $this->load->view('crm/product_detail_view', $this->data); } }
mit
cie/rubylog
benchmark/benchmark.rb
2494
#!/usr/bin/env ruby # benchmark # # The task is to collect all grandparent-granchild relationships in a family # tree to an array. # First it is done with pure rubylog. Second, it is done with compiled rubylog # # require "rubylog" require "benchmark" require "ruby-prof" DEGREES = 3 LEVELS = 6 NAME_LENGTH = 5 class Person def initialize name @name = name end def inspect # this is a quick solution for compiled*.rb code to retrieve the object "ObjectSpace._id2ref(#{object_id})" end def to_s # this is needed for comparing results @name end end # create a random person def random_person # create random name name = "" NAME_LENGTH.times { name << (97+$random.rand(26)).chr} name if $person_class == String name elsif $person_class == Symbol name.to_sym elsif $person_class = Person Person.new(name) end end def run_benchmark(id, person_class, name) $person_class = person_class $random = Random.new(1) load "./examples/benchmark/#{id}.rb" puts name result = nil time = Benchmark.realtime { result = rubylog do A.grandparent_of(B).map do [A.to_s,B.to_s] end end } puts "%0.5f sec" % time # forget result result = result.inspect # compare with last result raise "#{$last_result} != #{result}" if $last_result && $last_result != result $last_result = result # make garbage collection GC.start; sleep(time*1.2+1) end puts "Rubylog Grandparent Benchmark" puts puts "DEGREES = #{DEGREES}" puts "LEVELS = #{LEVELS}" puts "NAME_LENGTH = #{NAME_LENGTH}" puts "NODES = #{DEGREES**LEVELS}" puts run_benchmark "pure", String, "Strings" run_benchmark "pure", Person, "Objects" run_benchmark "pure", Symbol, "Symbols" puts require "./examples/benchmark/indexed_procedure" run_benchmark "pure", String, "Strings indexed" run_benchmark "pure", Person, "Objects indexed" run_benchmark "pure", Symbol, "Symbols indexed" puts run_benchmark "compiled_not_indexed", String, "Strings compiled" run_benchmark "compiled_not_indexed", Person, "Objects compiled" run_benchmark "compiled_not_indexed", Symbol, "Symbols compiled" puts run_benchmark "compiled_sequence_indexed", String, "Strings compiled, sequentially indexed" #run_benchmark "compiled_sequence_indexed", Person, "Objects compiled, sequentially indexed" run_benchmark "compiled_sequence_indexed", Symbol, "Symbols compiled, sequentially indexed" puts # native prolog load "./examples/benchmark/prolog.rb"
mit
sgwill/familyblog
Tests/Williamsonfamily.Models.Tests/Family/FamilyRepositoryTests.cs
2085
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using WilliamsonFamily.Models.Data; using WilliamsonFamily.Models.Data.Tests; namespace Williamsonfamily.Models.Tests { [TestClass] public class FamilyRepositoryTests { #region Load Tests [TestMethod] public void Family_LoadbyFamilyName_GetFamilyByFamilyname() { string familyName = "williamson"; int id = 1; var persister = GetPersister(); persister.DataContext.Insert(new Family { PkID = id, FamilyName = familyName }); var family = persister.Load(familyName); Assert.AreEqual(id, family.UniqueKey); } [TestMethod] public void Family_LoadbyFamilyName_InvalidFamilynameReturnsNull() { string familyName = "williamson"; var persister = GetPersister(); persister.DataContext.Insert(new Family { FamilyName = familyName }); var family = persister.Load("noone"); Assert.IsNull(family); } [TestMethod] public void Family_LoadbyFamilyName_TwoFamiliesWithSameFamilyNameThrowsException() { string familyName = "williamson"; var persister = GetPersister(); persister.DataContext.Insert(new Family { FamilyName = familyName }); persister.DataContext.Insert(new Family { FamilyName = familyName }); try { var user = persister.Load(familyName); Assert.Fail(); } catch (Exception ex) { Assert.IsInstanceOfType(ex, typeof(InvalidOperationException)); } } #endregion #region Provider private FamilyRepository GetPersister() { var dc = new InMemoryDataContext(); var dcf = new InMemoryDataContextFactory { DataContext = dc }; return new FamilyRepository { DataContext = dc, DataContextFactory = dcf }; } #endregion } }
mit
JFCCoding12/ellen-s-mirror
plugins/rss/controller.js
1618
function Rss($scope, $http, $q, $interval) { $scope.currentIndex = 0; var rss = {}; rss.feed = []; rss.get = function () { rss.feed = []; rss.updated = new moment().format('MMM DD, h:mm a'); if (typeof config.rss != 'undefined' && typeof config.rss.feeds != 'undefined') { var promises = []; angular.forEach(config.rss.feeds, function (url) { promises.push($http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%20%3D%20\'' + encodeURIComponent(url) + '\'&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=JSON_CALLBACK')); }); return $q.all(promises) } }; var refreshNews = function () { $scope.news = null; rss.get().then(function (response) { //For each feed for (var i = 0; i < response.length; i++) { for (var j = 0; j < response[i].data.query.results.rss.channel.item.length; j++) { var feedEntry = { title: response[i].data.query.results.rss.channel.item[j].title, //content: response[i].data.query.results.rss.channel.item[j].description[0], }; rss.feed.push(feedEntry); } } $scope.currentIndex = 0; $scope.rss = rss; }); }; var cycleNews = function(){ $scope.currentIndex = ($scope.currentIndex >= $scope.rss.feed.length)? 0: $scope.currentIndex + 1; } if (typeof config.rss !== 'undefined' && typeof config.rss.feeds != 'undefined') { refreshNews(); $interval(refreshNews, config.rss.refreshInterval * 60000 || 1800000) $interval(cycleNews, 8000) } } angular.module('SmartMirror') .controller('Rss', Rss);
mit
HackMerced/Admit
client/assets/js/src/components.js
4247
function generateComponents(){ Vue.component('hilite', { props: ['text'], template: '<span class="hilite">{{ text }}</span>' }); Vue.component('information', { props: ['info', 'hilite'], template: '<div class="information">{{ info }} <hilite v-bind:text="hilite"></hilite></div>' }); Vue.component('error', { props: ['error_text'], template: '<div class="error-bar">{{ error_text }}</div>' }); Vue.component('success', { props: ['hacker'], template: '<div class="success-bar">Congrats! {{hacker.name}} has been confirmed to participate in HackMerced!</div>' }); Vue.component('loginblock', { props: ['credentials'], template: `<div class="input-block"> <label class='textCenter' for='input_access_token'> Enter your access code </label> <input type='password' v-model='credentials.access_key' placeholder='Access Key' id='input_access_token'> </div>` }); Vue.component('emailblock', { props: ['search'], methods:{ verifyEmail:user.findEmail }, template: `<div style='margin:25px 0px;' class="input-block"> <label for='input_email'> Enter a student email </label> <input type='email' @keypress.enter='verifyEmail' v-model='search.email' placeholder='Student Email' id='input_email'> <div class='input-button' @click='verifyEmail' v-bind:class="{ isActive: search.email }">Go</div> </div>` }); Vue.component('phoneblock', { props: ['save'], methods:{ confirmAttendance:user.confirmAttendance, }, template: `<div style='margin:25px 0px;' class="input-block"> <label class='textCenter' for='input_phone_number'> Enter student's phone number (no dashes) </label> <input @keypress.enter='confirmAttendance' type='number' v-model='save.phone' placeholder='2340535432' id='input_phone_number'> </div>` }); Vue.component('flag', { props:['flag_title'], template: `<div class='flag'>{{flag_title}}</div>` }); Vue.component('hacker', { props: ['hacker', 'save'], methods:{ confirmAttendance:user.confirmAttendance, }, template: `<div style='margin:25px 0px;' class="hacker"> <div class='hacker--header'> <div style='background-color:${generateRandomColor()}' class='smallinfo--icon hacker--header-image'> {{ hacker.name[0] }} </div> <div class='hacker--header-userinfo smallinfo--text'> <div class='hacker--header-name semibold'>{{ hacker.name }}</div> <div class='hacker--header-email'>{{ hacker.email }}</div> </div> <div class='clear'></div> </div> <div class='hacker--content-bar'> <div class='hacker--content-wide'> <div class='semibold'>Education</div> {{ hacker.survey.education }} </div> <div class='hacker--content-short'> <div class='semibold'>Age</div> {{ hacker.survey.age }} </div> </div> <div class='hacker--content-bar'> <div class='hacker--content-wide'> <div class='semibold'>Flags</div> <div> <flag v-for='flag in hacker.survey.flags' :flag_title="flag"></flag> </div> </div> <div class='hacker--content-short'> <div class='semibold'>Shirt Size</div> {{ hacker.survey.shirt_size }} </div> </div> <phoneblock :save="save"></phoneblock> <button @click='confirmAttendance' v-if='hacker.status !== "attending"' class='centerObject full'>Confirm Attendance</button> <button @click='confirmAttendance' v-if='hacker.status === "attending"' class='centerObject full'>Update Phone Number</button> </div>` }); }
mit
dragonworx/axial
test/lib/test.js
252795
/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var Axial = __webpack_require__(1); var util = Axial.util; var expect = __webpack_require__(3); if (typeof window !== 'undefined') { window.Axial = Axial; Axial.addDefaultLogListeners(); } window.debug = false; Object.defineProperty(window, '$debug', { get: function get() { window.debug = true; } }); //$debug describe('1. Types', function () { it('1.1 should determine correct types', function () { // return as type instances expect(util.typeOf(null)).toBe(Axial.Null); expect(util.typeOf(undefined)).toBe(Axial.Undefined); expect(util.typeOf('abc')).toBe(Axial.String); expect(util.typeOf(123)).toBe(Axial.Number); expect(util.typeOf(true)).toBe(Axial.Boolean); expect(util.typeOf(false)).toBe(Axial.Boolean); expect(util.typeOf(new Date())).toBe(Axial.Date); expect(util.typeOf(/abc/)).toBe(Axial.Regex); expect(util.typeOf(function () {})).toBe(Axial.Function); expect(util.typeOf([])).toBe(Axial.Array()); expect(util.typeOf(['abc'])).toBe(Axial.Array(Axial.String)); expect(util.typeOf([123])).toBe(Axial.Array(Axial.Number)); expect(util.typeOf({})).toBe(Axial.Object); // check name of type expect(util.typeOf(null).id).toBe('null'); expect(util.typeOf(undefined).id).toBe('undefined'); expect(util.typeOf('abc').id).toBe('string'); expect(util.typeOf(123).id).toBe('number'); expect(util.typeOf(true).id).toBe('boolean'); expect(util.typeOf(false).id).toBe('boolean'); expect(util.typeOf(new Date()).id).toBe('date'); expect(util.typeOf(/abc/).id).toBe('regex'); expect(util.typeOf(function () {}).id).toBe('function'); expect(util.typeOf([]).id).toBe('array[*]'); expect(util.typeOf([]).type).toBe(undefined); expect(util.typeOf(['abc']).id).toBe('array[string]'); expect(util.typeOf(['abc']).type.id).toBe('string'); expect(util.typeOf([1, 2, 3]).id).toBe('array[number]'); expect(util.typeOf([1, 2, 3]).type.id).toBe('number'); expect(util.typeOf({}).id).toBe('object'); }); }); describe('2. Defining Interfaces', function () { var iface = null; var a = null; it('2.1 should be able to define an interface without a name', function () { iface = Axial.define({ x: { y: { z: [Axial.Number, Axial.Boolean] } }, 'a.b.c': Axial.Boolean }); expect(iface).toBeA(Axial.Interface.constructor); expect(iface.property('a.b.c').is(Axial.Boolean)).toBe(true); }); it('2.2 should be able to define an interface with a name', function () { iface = Axial.define('iface', { 'x.y.z': [Axial.Number, Axial.Boolean], v: Axial.Array(), w: Axial.Array(Axial.String) }); expect(iface.property('iface.x.y.z').iface.id).toBe('iface.x.y'); }); it('2.3 should be able to access interface properties by path', function () { expect(iface.property('iface.x').is(Axial.Interface)).toBe(true); expect(iface.property('iface.x').is(Axial.String)).toBe(false); expect(iface.property('iface.x.y.z').is(Axial.Number)).toBe(true); expect(iface.property('iface.x.y.z').is(Axial.Boolean)).toBe(true); expect(iface.property('iface.v').is(Axial.Array())).toBe(true); expect(iface.property('iface.v').is(Axial.Array(Axial.String))).toBe(false); expect(iface.property('iface.w').is(Axial.Array(Axial.String))).toBe(true); expect(iface.property('iface.w').is(Axial.Array(Axial.Number))).toBe(false); }); it('2.4 should not be able to define the same type more than once', function () { expect(function () { Axial.define({ x: [Axial.String, Axial.Number, Axial.String] }); }).toThrow(Axial.TypeAlreadyDefined); expect(function () { Axial.define({ x: [Axial.Array(), Axial.Number, Axial.Array()] }); }).toThrow(Axial.TypeAlreadyDefined); expect(function () { Axial.define({ x: [Axial.Array(Axial.String), Axial.Array(Axial.Number), Axial.Array(Axial.String)] }); }).toThrow(Axial.TypeAlreadyDefined); }); it('2.5 should be able to define multiple interface with same name (as stack)', function () { var a = Axial.define('iface25', { a: Axial.String }); expect(Axial.getInterface('iface25').has('a')).toBe(true); var b = Axial.define('iface25', { b: Axial.String }); expect(Axial.getInterface('iface25').has('a')).toBe(false); expect(Axial.getInterface('iface25').has('b')).toBe(true); var c = Axial.define('iface25', { c: Axial.String }); expect(Axial.getInterface('iface25').has('a')).toBe(false); expect(Axial.getInterface('iface25').has('b')).toBe(false); expect(Axial.getInterface('iface25').has('c')).toBe(true); expect(Axial.interfaces()['iface25'].length).toBe(3); expect(Axial.interfaces()['iface25'][0].has('a')).toBe(true); expect(Axial.interfaces()['iface25'][1].has('b')).toBe(true); expect(Axial.interfaces()['iface25'][2].has('c')).toBe(true); }); it('2.6 should be able to test equality of interfaces to objects', function () { var iface26A = Axial.define('iface26A', { a: Axial.String, b: Axial.Number }); var iface26B = Axial.define('iface26B', { a: Axial.Boolean, b: iface26A }); var instA = iface26B.new({ a: true, b: { a: 'abc', b: 5 } }); expect(instA.equals({ a: true, b: { a: 'abc', b: 5 } })).toBe(true); expect(instA.equals({ a: false, b: { a: 'abc', b: 5 } })).toBe(false); expect(instA.equals({ a: true, b: { a: 'abc', b: 6 } })).toBe(false); }); }); describe('3. Creating Instances', function () { var iface = void 0; var a = null; before(function () { iface = Axial.define('iface', { x: { y: { z: [Axial.Number, Axial.Boolean, Axial.Undefined] } }, a: { b: Axial.Function } }); }); it('3.1.a should be able to create instances of interfaces', function () { a = iface.new(); expect(a).toBeA(Axial.Instance.constructor); expect(Axial.typeOf(a)).toBe(iface); expect(a.stringify()).toBe('{"x":{"y":{"z":0}},"a":{}}'); }); it('3.1.b should be able to create instances of interfaces with given values', function () { iface = Axial.define('iface', { x: { y: { z: [Axial.Number, Axial.Boolean, Axial.Undefined] } }, a: { b: Axial.Function.orNull() } }); a = iface.new({ 'x.y.z': 6, a: { b: function b() { return this.rootOwner.x.y.z; } } }); expect(a.x).toBeA(Axial.Instance.constructor); expect(a.x.y).toBeA(Axial.Instance.constructor); expect(a.x.y.z).toBe(6); expect(a.a.b()).toBe(6); expect(Axial.getInterface('iface')).toBe(iface); expect(Axial.typeOf(a)).toBe(iface); expect(a.stringify()).toBe('{"x":{"y":{"z":6}},"a":{}}'); }); it('3.2.a should NOT be allowed to create instance with non-interface properties', function () { expect(function () { iface.new({ a: 1 }); }).toThrow(Axial.UnknownInterfaceKey); }); it('3.2.b should NOT be allowed to create instance with invalid type', function () { expect(function () { iface.new({ x: { y: false } }); }).toThrow(Axial.InvalidType); expect(function () { iface.new({ x: { y: { z: 'foo' } } }); }).toThrow(Axial.InvalidType); expect(function () { iface.new({ a: { b: 3 } }); }).toThrow(Axial.InvalidType); }); it('3.3 should be able to set multiple types', function () { expect(function () { a.x.y.z = 5; a.x.y.z = false; }).toNotThrow(); expect(function () { a.x.y.z = {}; }).toThrow(Axial.InvalidType); }); it('3.4 should be able to use arrays', function () { iface = Axial.define('iface', { a: Axial.Array(), b: Axial.Array(Axial.String), c: Axial.Array(Axial.Object), d: Axial.Array(Axial.Array(Axial.String)) }); a = iface.new(); a.a = []; a.b = []; a.b = ['abc']; a.c = []; a.c = [{ x: 1 }]; a.d = []; a.d = [['abc'], ['efg']]; expect(function () { return a.a = false; }).toThrow(Axial.InvalidType); expect(function () { return a.b = [123]; }).toThrow(Axial.InvalidType); expect(function () { return a.c = [[]]; }).toThrow(Axial.InvalidType); expect(function () { return a.c = [[123]]; }).toThrow(Axial.InvalidType); expect(a.stringify()).toBe('{"a":[],"b":["abc"],"c":[{"x":1}],"d":[["abc"],["efg"]]}'); }); it('3.5 should be able to use objects', function () { iface = Axial.define('iface', { a: Axial.Object }); a = iface.new(); a.a = { x: 1 }; expect(function () { return a.a = null; }).toThrow(Axial.InvalidType); expect(function () { return a.a = [123]; }).toThrow(Axial.InvalidType); }); it('3.6 should NOT be able to create empty instances with required properties', function () { iface = Axial.define({ a: [Axial.String.required()] }); expect(function () { a = iface.new(); }).toThrow(); expect(function () { a = iface.new({ a: 'foo' }); }).toNotThrow(); }); }); describe('4. Configuring Interface Property Types', function () { var iface = void 0; it('4.1 should be able to set default property', function () { iface = Axial.define({ x: Axial.Number.extend({ defaultValue: 5, min: -10, max: 10 }), y: Axial.String.extend({ defaultValue: 'foo', pattern: /foo/ }), a: Axial.String.extend({ defaultValue: 'baz', validate: function validate(value) { if (value !== 'baz') { throw new Error('Not a baz!'); } } }), b: Axial.Number.extend({ validate: function validate(value) { if (value % 10 !== 0) { throw new Error('Must be multiple of 10'); } } }) }); expect(iface.new().x).toBe(5); }); it('4.2 should be able to set min/max values for numbers', function () { expect(function () { iface.new({ x: -11 }); }).toThrow(Axial.InvalidNumericType); expect(function () { iface.new({ x: 11 }); }).toThrow(Axial.InvalidNumericType); }); it('4.3 should be able to match a string with a regex pattern', function () { expect(function () { iface.new({ y: 'bah' }); }).toThrow(Axial.InvalidStringPattern); expect(function () { iface.new({ y: 'foo' }); }).toNotThrow(); }); it('4.4 should be able to supply custom validator function', function () { expect(function () { iface.new({ a: 'bah' }); }).toThrow(); expect(function () { iface.new({ a: 'baz' }); }).toNotThrow(); expect(function () { iface.new({ b: 1000 }); }).toNotThrow(); expect(function () { iface.new({ b: 12 }); }).toThrow(); }); }); describe('5. Listening to instance changes', function () { var iface = Axial.define('iface', { a: Axial.Object }); var a = iface.new(); it('5.1 should be able to listen to set property changes of instances (global/local)', function () { var handlerCount = 0; var fn = function fn(eventData) { expect(eventData.method).toBe('set'); expect(eventData.value.y).toBe(5); handlerCount++; }; Axial.bind(fn); a.bind('a', fn); a.a = { y: 5 }; a.unbind(); Axial.unbind(); expect(handlerCount).toBe(2); }); it('5.2 should be able to listen to get property changes of instances (global/local)', function () { var handlerCount = 0; var fn = function fn(eventData) { expect(eventData.method).toBe('get'); expect(eventData.value.y).toBe(5); handlerCount++; }; Axial.bind(fn); a.bind('a', fn); var test = a.a; a.unbind(); Axial.unbind(); expect(handlerCount).toBe(2); }); }); describe('6. Composite interfaces', function () { var ifaceA = void 0, ifaceB = void 0; it('6.1 should be able to compose interfaces from other interfaces', function () { ifaceA = Axial.define('ifaceA', { x: [Axial.String, Axial.Undefined], y: { z: [Axial.Number, Axial.Undefined] } }); ifaceB = Axial.define('ifaceB', { a: ifaceA, b: { c: [Axial.Number, ifaceA] } }); var a = ifaceB.new(); expect(function () { ifaceB.new({ a: { x: 'a', y: { z: 3 } }, b: { c: 2 } }); }).toNotThrow(); expect(function () { ifaceB.new({ a: { x: 'a', y: { z: 'abc' // <- error } }, b: { c: 2 } }); }).toThrow(); expect(function () { ifaceB.new({ a: { x: 'a', y: { z: 3 } }, b: { c: { x: 'a', y: { z: 3 } } } }); }).toNotThrow(); expect(function () { ifaceB.new({ a: { x: 'a', y: { z: 3 } }, b: { c: { x: 'a', y: { z: 3 } } } }); }).toNotThrow(); expect(function () { ifaceB.new({ a: { x: 'a', y: { z: 3 } }, b: { c: { x: 'a', y: { z: 'a' // <- error } } } }); }).toThrow(); expect(Axial.typeOf({ a: { x: 'a', y: { z: 3 } }, b: { c: 2 } })).toBe(ifaceB); expect(Axial.typeOf({ x: undefined, y: { z: 3 } })).toBe(ifaceA); }); it('6.2 should be able to test whether an object matches an interface', function () { expect(ifaceA.is({ x: undefined, y: { z: 1 } })).toBe(true); expect(ifaceA.is({ x: 3, //<- error y: { z: 1 } })).toBe(false); expect(ifaceA.is({ x: 'a', y: {} //<- partial value ok })).toBe(true); expect(ifaceB.is({ a: { x: undefined, y: { z: 1 } }, b: { c: 3 } })).toBe(true); expect(ifaceB.is({ a: { x: undefined, y: { z: 1 } }, b: { c: { x: undefined, y: { z: 1 } } } })).toBe(true); expect(ifaceB.is({ a: { x: undefined, y: { z: 1 } }, b: { c: { x: 3, //<- error y: { z: 1 } } } })).toBe(false); }); }); describe('7. Arrays', function () { it('7.1.a should detect nested array types', function () { expect(Axial.Array(Axial.Array(Axial.Array(Axial.String))).is([[['abc']]])).toBe(true); expect(Axial.Array(Axial.Array(Axial.Array(Axial.String))).is([[[3]]])).toBe(false); expect(Axial.Array(Axial.Array(Axial.Array(Axial.String))).is([[['abc', 3]]])).toBe(false); }); it('7.1.b should detect complex array types', function () { var subIFace = Axial.define({ x: Axial.String }); var iface = Axial.define({ a: Axial.Array(Axial.Array(subIFace)) }); expect(function () { return iface.new({ a: [[{ x: 'foo' }]] }); }).toNotThrow(); expect(function () { return iface.new({ a: [[{ x: 1 }]] }); }).toThrow(); expect(function () { return iface.new({ a: [[{ y: 'foo' }]] }); }).toThrow(); expect(iface.new({ a: [[{ x: 'foo' }]] }).a[0][0].constructor).toBe(Axial.Instance.constructor); expect(iface.new({ a: [[{ x: 'foo' }]] }).a[0][0].iface).toBe(subIFace); }); it('7.2 should be able to bind array mutations to instance values', function () { var IFace = Axial.define({ a: Axial.Array(Axial.Number) }); var instance = IFace.new({ a: [1, 2, 3] }); var array = instance.a; var dispatch = 0; // get indexes instance.bind('a', function (e) { expect(e.method).toBe('get'); expect(e.arrayMethod).toBe('index'); expect(e.index).toBe(2); expect(e.value).toEqual(3); dispatch++; }); expect(array[2]).toBe(3); instance.unbind('a'); // get indexes instance.bind('a', function (e) { expect(e.method).toBe('set'); expect(e.arrayMethod).toBe('index'); expect(e.index).toBe(2); expect(e.value).toEqual(6); dispatch++; }); array[2] = 6; instance.unbind('a'); // copyWithin instance.bind('a', function (e) { expect(e.arrayMethod).toBe('copyWithin'); expect(array.length).toBe(3); expect(array.array).toEqual([2, 6, 6]); dispatch++; }); array.copyWithin(0, 1); instance.unbind('a'); // fill instance.bind('a', function (e) { expect(e.arrayMethod).toBe('fill'); expect(array.length).toBe(3); expect(array.array).toEqual([4, 4, 4]); dispatch++; }); array.fill(4); instance.unbind('a'); // pop instance.bind('a', function (e) { expect(e.arrayMethod).toBe('pop'); expect(array.length).toBe(2); expect(array.array).toEqual([4, 4]); dispatch++; }); array.pop(); instance.unbind('a'); // push instance.bind('a', function (e) { expect(e.arrayMethod).toBe('push'); expect(array.length).toBe(3); expect(array.array).toEqual([4, 4, 5]); dispatch++; }); array.push(5); instance.unbind('a'); // reverse instance.bind('a', function (e) { expect(e.arrayMethod).toBe('reverse'); expect(array.length).toBe(3); expect(array.array).toEqual([5, 4, 4]); dispatch++; }); array.reverse(); instance.unbind('a'); // shift instance.bind('a', function (e) { expect(e.arrayMethod).toBe('shift'); expect(array.length).toBe(2); expect(array.array).toEqual([4, 4]); dispatch++; }); expect(array.shift()).toBe(5); instance.unbind('a'); // sort array.push(3); instance.bind('a', function (e) { expect(e.arrayMethod).toBe('sort'); expect(array.length).toBe(3); expect(array.array).toEqual([3, 4, 4]); dispatch++; }); array.sort(function (a, b) { return a < b ? -1 : a > b ? 1 : 0; }); instance.unbind('a'); // splice var round = 1; instance.bind('a', function (e) { expect(e.arrayMethod).toBe('splice'); if (round === 1) { expect(array.length).toBe(2); expect(array.array).toEqual([3, 4]); } else if (round === 2) { expect(array.length).toBe(5); expect(array.array).toEqual([1, 2, 3, 3, 4]); } else { throw new Error('Too many rounds!'); } round++; dispatch++; }); array.splice(1, 1); array.splice(0, 0, 1, 2, 3); instance.unbind('a'); // unshift instance.bind('a', function (e) { expect(e.arrayMethod).toBe('unshift'); expect(array.length).toBe(7); expect(array.array).toEqual([7, 8, 1, 2, 3, 3, 4]); dispatch++; }); expect(array.unshift(7, 8)).toBe(7); instance.unbind('a'); expect(dispatch).toBe(12); }); it('7.3 should not be able to add illegal type to typed array', function () { var Item = Axial.define({ text: Axial.String }); var List = Axial.define({ items: Axial.Array(Item) }); var list = List.new(); var validItem = Item.new({ text: 'valid' }); var invalidItem = { foo: 'bar' }; list.items.add(validItem); expect(function () { list.items.add(invalidItem); }).toThrow(); expect(list.items.contains(validItem)).toBe(true); expect(list.items.contains(invalidItem)).toBe(false); list.items.remove(validItem); expect(list.items.isEmpty).toBe(true); expect(list.items.contains(validItem)).toBe(false); }); it('7.4 should convert arrays to AxialInstanceArray', function () { var iface = Axial.define({ a: Axial.Array(Axial.Array(Axial.Number)) }); var inst = iface.new({ a: [[123]] }); expect(inst.a).toBeA(Axial.InstanceArray); expect(inst.a[0].constructor).toBeA(Axial.InstanceArray.constructor); expect(inst.a[0][0].constructor).toBeA(Axial.InstanceArray.constructor); }); it('7.5 should convert plain objects to AxialInstances', function () { var iface = Axial.define({ a: Axial.String }); var aiface = Axial.define({ x: Axial.Array(iface) }); var inst = aiface.new({ x: [{ a: 'abc' }] }); expect(inst.x[0].constructor).toBe(Axial.Instance.constructor); inst.x[0] = { a: 'efg' }; expect(inst.x[0].constructor).toBe(Axial.Instance.constructor); expect(inst.x[0].a).toBe('efg'); }); }); describe('8. Interface Inheritance', function () { var ifaceA = void 0, ifaceB = void 0, ifaceC = void 0; var inst = void 0; it('8.1 should be able to define interfaces which inherit from another interface', function () { ifaceA = Axial.define('ifaceA', { a: Axial.String.set('a'), foo: Axial.String, who: Axial.Function.set(function (x) { return 'ifaceA-' + x; }) }); ifaceB = ifaceA.extend('ifaceB', { b: Axial.String.set('b'), foo: Axial.Number, who: Axial.Function.set(function (x) { return 'ifaceB-' + x; }) }); ifaceC = ifaceB.extend('ifaceC', { c: Axial.String.set('c'), foo: Axial.Boolean, who: Axial.Function.set(function (x) { return 'ifaceC-' + x; }) }); }); it('8.2.a interface should be able to inherit from another interface by one level', function () { inst = ifaceB.new(); expect(function () { inst.foo = 'string'; // invalid input }).toThrow(); expect(function () { inst.foo = 3; // valid input }).toNotThrow(); expect(ifaceB.has('a')).toBe(true); expect(ifaceB.has('b')).toBe(true); expect(ifaceB.has('foo')).toBe(true); expect(ifaceB.has('who')).toBe(true); expect(ifaceB.property('a').iface.id).toBe('ifaceA'); expect(ifaceB.property('b').iface.id).toBe('ifaceB'); expect(ifaceB.property('foo').iface.id).toBe('ifaceB'); expect(ifaceB.property('who').iface.id).toBe('ifaceB'); expect(inst.who(123)).toBe('ifaceB-123'); expect(inst.super.ifaceA.who(123)).toBe('ifaceA-123'); }); it('8.2.b interface should be able to to inherit from another interface by multiple levels', function () { inst = ifaceC.new(); expect(function () { inst.foo = 3; // invalid input }).toThrow(); expect(function () { inst.foo = false; // valid input }).toNotThrow(); expect(ifaceC.has('a')).toBe(true); expect(ifaceC.has('b')).toBe(true); expect(ifaceC.has('c')).toBe(true); expect(ifaceC.has('foo')).toBe(true); expect(ifaceC.has('who')).toBe(true); expect(ifaceC.property('a').iface.id).toBe('ifaceA'); expect(ifaceC.property('b').iface.id).toBe('ifaceB'); expect(ifaceC.property('c').iface.id).toBe('ifaceC'); expect(ifaceC.property('foo').iface.id).toBe('ifaceC'); expect(ifaceC.property('who').iface.id).toBe('ifaceC'); expect(inst.who(123)).toBe('ifaceC-123'); expect(inst.super.ifaceA.who(123)).toBe('ifaceA-123'); expect(inst.super.ifaceB.who(123)).toBe('ifaceB-123'); }); }); /***/ }, /* 1 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } module.exports = function Define_Axial() { var _Axial; var CONST = __webpack_require__(2); var BLANK_INTERFACE_NAME = CONST.BLANK_INTERFACE_NAME; var _arrayTypes = {}; var _listeners = []; var _interfaces = {}; var _instances = {}; var _instancesCreated = []; var _bindings = []; var _arrayMembers = CONST.ARRAY_MEMBERS; var _arrayMutators = CONST.ARRAY_MUTATORS; var _validKeys = CONST.VALID_KEYS; var _logListeners = {}; var _logListenerCount = 0; var util = void 0, T = void 0; var _interfaceId = 0, _instanceArrayId = 0, _instanceIds = {}; function _isValidKey(key) { return _validKeys.indexOf(key) > -1; } function getInstanceId(iface) { if (!iface) { return '0'; } var ifaceId = iface.id; if (!_instanceIds[ifaceId]) { _instanceIds[ifaceId] = 0; } _instanceIds[ifaceId]++; return iface.id + '#' + _instanceIds[ifaceId]; } // -------------------------------------------------------------------------------------- Errors var Exception = function ExtendableBuiltin(cls) { function ExtendableBuiltin() { cls.apply(this, arguments); } ExtendableBuiltin.prototype = Object.create(cls.prototype); Object.setPrototypeOf(ExtendableBuiltin, cls); return ExtendableBuiltin; }(Error); var AxialUnsupportedType = function (_Exception) { _inherits(AxialUnsupportedType, _Exception); function AxialUnsupportedType(value, iface, key) { _classCallCheck(this, AxialUnsupportedType); var type = void 0; if (value instanceof AxialInstance) { type = value.iface.id + '(AxialInstance)'; } else { try { type = util.typeOf(value).id; } catch (e) { type = typeof value === 'undefined' ? 'undefined' : _typeof(value); } } var message = 'Unsupported Axial type "' + type + '"' + (iface ? ' used to define property "' + key + '" of interface "' + iface.id + '"' : '') + '. Only instances of AxialType can be provided.'; var _this = _possibleConstructorReturn(this, (AxialUnsupportedType.__proto__ || Object.getPrototypeOf(AxialUnsupportedType)).call(this, message)); _this.value = value; _this.message = message; return _this; } return AxialUnsupportedType; }(Exception); var AxialInvalidType = function (_Exception2) { _inherits(AxialInvalidType, _Exception2); function AxialInvalidType(given, expected, instance, property) { _classCallCheck(this, AxialInvalidType); var instString = instance ? instance.toString() : '?'; var message = 'Invalid type for property "' + property.path + ('" ~ "' + given + '" given, "' + expected + '" expected.'); var _this2 = _possibleConstructorReturn(this, (AxialInvalidType.__proto__ || Object.getPrototypeOf(AxialInvalidType)).call(this, message)); _this2.given = given; _this2.expected = expected; _this2.instance = instance; _this2.property = property; _this2.message = message; return _this2; } return AxialInvalidType; }(Exception); var AxialInvalidNumericRange = function (_Exception3) { _inherits(AxialInvalidNumericRange, _Exception3); function AxialInvalidNumericRange(given, min, max) { _classCallCheck(this, AxialInvalidNumericRange); var message = 'Invalid numeric range - expected [' + min + ' .. ' + max + '], given ' + given + '.'; var _this3 = _possibleConstructorReturn(this, (AxialInvalidNumericRange.__proto__ || Object.getPrototypeOf(AxialInvalidNumericRange)).call(this, message)); _this3.given = given; _this3.min = min; _this3.max = max; _this3.message = message; return _this3; } return AxialInvalidNumericRange; }(Exception); var AxialInvalidStringPattern = function (_Exception4) { _inherits(AxialInvalidStringPattern, _Exception4); function AxialInvalidStringPattern(given, pattern) { _classCallCheck(this, AxialInvalidStringPattern); var message = 'Invalid string pattern - expected "' + pattern + '", given "' + given + '".'; var _this4 = _possibleConstructorReturn(this, (AxialInvalidStringPattern.__proto__ || Object.getPrototypeOf(AxialInvalidStringPattern)).call(this, message)); _this4.given = given; _this4.pattern = pattern; _this4.message = message; return _this4; } return AxialInvalidStringPattern; }(Exception); var AxialUndefinedValue = function (_Exception5) { _inherits(AxialUndefinedValue, _Exception5); function AxialUndefinedValue(source, path) { _classCallCheck(this, AxialUndefinedValue); var message = 'Undefined value for object path "' + path + '".'; var _this5 = _possibleConstructorReturn(this, (AxialUndefinedValue.__proto__ || Object.getPrototypeOf(AxialUndefinedValue)).call(this, message)); _this5.source = source; _this5.path = path; _this5.message = message; return _this5; } return AxialUndefinedValue; }(Exception); var AxialTypeAlreadyDefined = function (_Exception6) { _inherits(AxialTypeAlreadyDefined, _Exception6); function AxialTypeAlreadyDefined(typeName, key, iface) { _classCallCheck(this, AxialTypeAlreadyDefined); var message = 'Type "' + typeName + '" is already defined for property "' + key + '" in schema "' + iface.id + '".'; var _this6 = _possibleConstructorReturn(this, (AxialTypeAlreadyDefined.__proto__ || Object.getPrototypeOf(AxialTypeAlreadyDefined)).call(this, message)); _this6.typeName = typeName; _this6.key = key; _this6.iface = iface; _this6.message = message; return _this6; } return AxialTypeAlreadyDefined; }(Exception); var AxialInvalidArgument = function (_Exception7) { _inherits(AxialInvalidArgument, _Exception7); function AxialInvalidArgument(index, expected, given) { _classCallCheck(this, AxialInvalidArgument); var message = 'Invalid argument #' + index + ' - Expected "' + expected + '", given "' + given + '".'; var _this7 = _possibleConstructorReturn(this, (AxialInvalidArgument.__proto__ || Object.getPrototypeOf(AxialInvalidArgument)).call(this, message)); _this7.index = index; _this7.expected = expected; _this7.given = given; return _this7; } return AxialInvalidArgument; }(Exception); var AxialMissingProperty = function (_Exception8) { _inherits(AxialMissingProperty, _Exception8); function AxialMissingProperty(key, iface, object) { _classCallCheck(this, AxialMissingProperty); var message = 'Missing interface property "' + key + '" from given object.'; var _this8 = _possibleConstructorReturn(this, (AxialMissingProperty.__proto__ || Object.getPrototypeOf(AxialMissingProperty)).call(this, message)); _this8.key = key; _this8.object = object; _this8.iface = iface; _this8.message = message; return _this8; } return AxialMissingProperty; }(Exception); var AxialUnexpectedProperty = function (_Exception9) { _inherits(AxialUnexpectedProperty, _Exception9); function AxialUnexpectedProperty(key, iface, instance) { _classCallCheck(this, AxialUnexpectedProperty); var message = 'Unexpected key "' + key + '" found in given object not declared in interface "' + iface.id + '".'; var _this9 = _possibleConstructorReturn(this, (AxialUnexpectedProperty.__proto__ || Object.getPrototypeOf(AxialUnexpectedProperty)).call(this, message)); _this9.key = key; _this9.iface = iface; _this9.instance = instance; _this9.message = message; return _this9; } return AxialUnexpectedProperty; }(Exception); var AxialDockRejection = function (_Exception10) { _inherits(AxialDockRejection, _Exception10); function AxialDockRejection(message) { _classCallCheck(this, AxialDockRejection); message = 'Dock Rejected: ' + message; var _this10 = _possibleConstructorReturn(this, (AxialDockRejection.__proto__ || Object.getPrototypeOf(AxialDockRejection)).call(this, message)); _this10.message = message; return _this10; } return AxialDockRejection; }(Exception); var Errors = { UnsupportedType: AxialUnsupportedType, InvalidType: AxialInvalidType, InvalidNumericRange: AxialInvalidNumericRange, InvalidStringPattern: AxialInvalidStringPattern, UndefinedValue: AxialUndefinedValue, TypeAlreadyDefined: AxialTypeAlreadyDefined, InvalidArgument: AxialInvalidArgument, MissingProperty: AxialMissingProperty, IllegalProperty: AxialUnexpectedProperty, DockRejection: AxialDockRejection }; // -------------------------------------------------------------------------------------- Types var AxialType = function () { function AxialType() { _classCallCheck(this, AxialType); this._defaultValue = undefined; this._required = false; this._baseType = this; this._validate = null; this._exports = true; } _createClass(AxialType, [{ key: 'validate', value: function validate(value, instance, property) { if (typeof this._validate === 'function') { return this._validate.call(instance, value); } if (!this.is(value)) { //given, expected, key, instance throw new AxialInvalidType(this.id, util.typeOf(value).id, instance, property); } } }, { key: 'is', value: function is(value) { return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === this.id; } }, { key: 'toString', value: function toString() { return this.id; } }, { key: 'clone', value: function clone() { var copy = new this.constructor(); for (var key in this) { if (this.hasOwnProperty(key)) { copy[key] = this[key]; } } copy._baseType = this.baseType; return copy; } }, { key: 'extend', value: function extend(options) { var copy = this.clone(); if (util.isPlainObject(options)) { for (var key in options) { if (options.hasOwnProperty(key)) { if (key === 'value') { copy['_defaultValue'] = options[key]; } else { copy['_' + key] = options[key]; } } } } else if (typeof options !== 'undefined') { copy._defaultValue = options; } return copy; } }, { key: 'defaultValue', value: function defaultValue(value) { var copy = this.clone(); copy._defaultValue = value; return copy; } }, { key: 'value', value: function value(_value) { return this.defaultValue(_value); } }, { key: 'required', value: function required() { var copy = this.clone(); copy._required = true; return copy; } }, { key: 'exports', value: function exports(bool) { var copy = this.clone(); copy._exports = bool; return copy; } }, { key: 'id', get: function get() { return this._id || this.constructor.id; } }, { key: 'baseType', get: function get() { return this._baseType ? this._baseType : this; } }], [{ key: 'id', get: function get() { return '?'; } }]); return AxialType; }(); var AxialTypePrototype = AxialType.prototype; var AxialNull = function (_AxialType) { _inherits(AxialNull, _AxialType); function AxialNull() { _classCallCheck(this, AxialNull); var _this11 = _possibleConstructorReturn(this, (AxialNull.__proto__ || Object.getPrototypeOf(AxialNull)).call(this)); _this11._defaultValue = null; return _this11; } _createClass(AxialNull, [{ key: 'is', value: function is(value) { return value === null; } }], [{ key: 'id', get: function get() { return 'null'; } }]); return AxialNull; }(AxialType); var AxialUndefined = function (_AxialType2) { _inherits(AxialUndefined, _AxialType2); function AxialUndefined() { _classCallCheck(this, AxialUndefined); var _this12 = _possibleConstructorReturn(this, (AxialUndefined.__proto__ || Object.getPrototypeOf(AxialUndefined)).call(this)); _this12._defaultValue = undefined; return _this12; } _createClass(AxialUndefined, [{ key: 'is', value: function is(value) { return typeof value === 'undefined'; } }], [{ key: 'id', get: function get() { return 'undefined'; } }]); return AxialUndefined; }(AxialType); var AxialString = function (_AxialType3) { _inherits(AxialString, _AxialType3); function AxialString() { _classCallCheck(this, AxialString); var _this13 = _possibleConstructorReturn(this, (AxialString.__proto__ || Object.getPrototypeOf(AxialString)).call(this)); _this13._pattern = null; _this13._defaultValue = ''; return _this13; } _createClass(AxialString, [{ key: 'validate', value: function validate(value, instance, property) { if (typeof this._validate === 'function') { return this._validate.call(instance, value); } if (!this.is(value)) { if (typeof value !== 'string') { throw new AxialInvalidType(util.typeOf(value).id, 'string', instance, property); } throw new AxialInvalidStringPattern(value, this._pattern); } } }, { key: 'is', value: function is(value) { return AxialTypePrototype.is.call(this, value) && (this._pattern ? !!value.match(this._pattern) : true); } }], [{ key: 'id', get: function get() { return 'string'; } }]); return AxialString; }(AxialType); var AxialNumber = function (_AxialType4) { _inherits(AxialNumber, _AxialType4); function AxialNumber() { _classCallCheck(this, AxialNumber); var _this14 = _possibleConstructorReturn(this, (AxialNumber.__proto__ || Object.getPrototypeOf(AxialNumber)).call(this)); _this14._min = Number.MIN_SAFE_INTEGER; _this14._max = Number.MAX_SAFE_INTEGER; _this14._defaultValue = 0; return _this14; } _createClass(AxialNumber, [{ key: 'validate', value: function validate(value, instance, property) { if (typeof this._validate === 'function') { return this._validate.call(instance, value); } if (!this.is(value)) { if (typeof value !== 'number') { throw new AxialInvalidType('number', util.typeOf(value).id, instance, property); } throw new AxialInvalidNumericRange(value, this._min, this._max); } } }, { key: 'is', value: function is(value) { if (this._clip === true) { value = this.clip(value); } return AxialTypePrototype.is.call(this, value) && value >= this._min && value <= this._max; } }, { key: 'clip', value: function clip(value) { value = Math.max(value, this._min); value = Math.min(value, this._max); return value; } }, { key: 'between', value: function between(min, max, clip) { var opts = { clip: !!clip }; if (typeof min === 'number') { opts.min = min; } if (typeof max === 'number') { opts.max = max; } return this.extend(opts); } }], [{ key: 'id', get: function get() { return 'number'; } }]); return AxialNumber; }(AxialType); var AxialBoolean = function (_AxialType5) { _inherits(AxialBoolean, _AxialType5); function AxialBoolean() { _classCallCheck(this, AxialBoolean); var _this15 = _possibleConstructorReturn(this, (AxialBoolean.__proto__ || Object.getPrototypeOf(AxialBoolean)).call(this)); _this15._defaultValue = false; return _this15; } _createClass(AxialBoolean, null, [{ key: 'id', get: function get() { return 'boolean'; } }]); return AxialBoolean; }(AxialType); var AxialDate = function (_AxialType6) { _inherits(AxialDate, _AxialType6); function AxialDate() { _classCallCheck(this, AxialDate); var _this16 = _possibleConstructorReturn(this, (AxialDate.__proto__ || Object.getPrototypeOf(AxialDate)).call(this)); _this16._defaultValue = new Date(); return _this16; } _createClass(AxialDate, [{ key: 'is', value: function is(value) { return value instanceof Date; } }], [{ key: 'id', get: function get() { return 'date'; } }]); return AxialDate; }(AxialType); var AxialRegex = function (_AxialType7) { _inherits(AxialRegex, _AxialType7); function AxialRegex() { _classCallCheck(this, AxialRegex); var _this17 = _possibleConstructorReturn(this, (AxialRegex.__proto__ || Object.getPrototypeOf(AxialRegex)).call(this)); _this17._defaultValue = new RegExp('.*', 'i'); return _this17; } _createClass(AxialRegex, [{ key: 'is', value: function is(value) { return value instanceof RegExp; } }], [{ key: 'id', get: function get() { return 'regex'; } }]); return AxialRegex; }(AxialType); var AxialFunction = function (_AxialType8) { _inherits(AxialFunction, _AxialType8); function AxialFunction() { _classCallCheck(this, AxialFunction); var _this18 = _possibleConstructorReturn(this, (AxialFunction.__proto__ || Object.getPrototypeOf(AxialFunction)).call(this)); _this18._defaultValue = new Function(); return _this18; } _createClass(AxialFunction, [{ key: 'is', value: function is(value) { return typeof value === 'function'; } }], [{ key: 'id', get: function get() { return 'function'; } }]); return AxialFunction; }(AxialType); var AxialArray = function (_AxialType9) { _inherits(AxialArray, _AxialType9); function AxialArray(type) { _classCallCheck(this, AxialArray); var _this19 = _possibleConstructorReturn(this, (AxialArray.__proto__ || Object.getPrototypeOf(AxialArray)).call(this)); _this19._type = type; _this19._defaultValue = []; return _this19; } _createClass(AxialArray, [{ key: 'is', value: function is(value) { var isArray = Array.isArray(value); if (isArray) { if (this._type instanceof AxialType) { var l = value.length; for (var i = 0; i < l; i++) { if (!this._type.is(value[i])) { return false; } } } return true; } else { return false; } } }, { key: 'isItem', value: function isItem(item) { if (this._type) { return util.typeOf(item).id === this._type.id; } return true; } }, { key: 'validate', value: function validate(value, instance, property) { if (!Array.isArray(value)) { throw new AxialInvalidType(this.id, util.typeOf(value).id, instance, property); } if (this._type) { var l = value.length; var t = this._type; for (var i = 0; i < l; i++) { t.validate(value[i], instance, property); } } } }, { key: 'type', get: function get() { return this._type; } }], [{ key: 'id', get: function get() { return 'array'; } }]); return AxialArray; }(AxialType); var AxialObject = function (_AxialType10) { _inherits(AxialObject, _AxialType10); function AxialObject() { _classCallCheck(this, AxialObject); var _this20 = _possibleConstructorReturn(this, (AxialObject.__proto__ || Object.getPrototypeOf(AxialObject)).call(this)); _this20._defaultValue = {}; return _this20; } _createClass(AxialObject, [{ key: 'is', value: function is(value) { return util.isPlainObject(value) || (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null && !Array.isArray(value); } }], [{ key: 'id', get: function get() { return 'object'; } }]); return AxialObject; }(AxialType); var AxialReference = function (_AxialType11) { _inherits(AxialReference, _AxialType11); function AxialReference() { _classCallCheck(this, AxialReference); var _this21 = _possibleConstructorReturn(this, (AxialReference.__proto__ || Object.getPrototypeOf(AxialReference)).call(this)); _this21._defaultValue = null; return _this21; } _createClass(AxialReference, [{ key: 'is', value: function is(value) { return value instanceof AxialInstance; } }, { key: 'validate', value: function validate(value, instance, property) { if (value === null) { return true; } if (!(value instanceof AxialInstance)) { throw new AxialInvalidType(util.typeOf(value).id, 'AxialInstance', instance, property); } } }], [{ key: 'id', get: function get() { return 'reference'; } }]); return AxialReference; }(AxialType); var AxialInterface = function (_AxialObject) { _inherits(AxialInterface, _AxialObject); function AxialInterface() { var interfaceId = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : BLANK_INTERFACE_NAME; var prototype = arguments[1]; var parentInterface = arguments[2]; _classCallCheck(this, AxialInterface); var _this22 = _possibleConstructorReturn(this, (AxialInterface.__proto__ || Object.getPrototypeOf(AxialInterface)).call(this)); if (util.isPlainObject(interfaceId) && typeof prototype === 'undefined') { // handle case where just single object prototype argument given prototype = interfaceId; interfaceId = BLANK_INTERFACE_NAME; } if (interfaceId === BLANK_INTERFACE_NAME) { interfaceId += ++_interfaceId; } _this22._id = interfaceId; _this22._properties = new Map(); _this22._allProps = new Map(); _this22._parentInterface = parentInterface; _this22._methods = new Map(); _this22.define(prototype); if (interfaceId) { Axial.Interface[_this22._id] = _this22; } var _id = _this22._id; _interfaces[_id] = _interfaces[_id] ? _interfaces[_id] : []; _interfaces[_id].push(_this22); return _this22; } _createClass(AxialInterface, [{ key: 'define', value: function define(prototype) { util.expandDotSyntaxKeys(prototype, function (path, key, object) { util.setObjectAtPath(prototype, path, object); }); for (var key in prototype) { if (prototype.hasOwnProperty(key)) { var definedTypes = {}; var typeDef = prototype[key]; var Type = Axial.typeOf(typeDef); if (!(typeDef instanceof AxialType) && !Array.isArray(typeDef)) { if (Type instanceof AxialObject === false) { // extend type if given type typeDef = Type.extend(typeDef); } } var path = this._id ? this._id + '.' + key : BLANK_INTERFACE_NAME + '.' + key; var typeArray = Array.isArray(typeDef) ? typeDef : [typeDef]; if (util.isPlainObject(typeDef)) { typeArray = [new AxialInterface(path, typeDef, this)]; } else { // ensure type is wrapped in array, expand/flatten any inner arrays typeArray = util.expandArray(typeArray); // check type is only defined once and is AxialType for (var i = 0; i < typeArray.length; i++) { var t = typeArray[i]; if (!util.isType(t)) { // throw when type not found throw new AxialUnsupportedType(t, this, key); } var typeName = t.id; if (definedTypes[typeName]) { // throw when type defined multiple times throw new AxialTypeAlreadyDefined(t.id, key, this); } else { // mark type as defined definedTypes[typeName] = true; } } } // create property var property = new AxialInterfaceProperty(this, key, typeArray, path); // store property this._properties.set(key, property); if (property.is(Axial.Function)) { // track default function value in this interfaces known methods this._methods.set(key, property.getType(Axial.Function)._defaultValue); } } } } }, { key: 'create', value: function create() { var _this23 = this; var defaultValues = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; var owner = arguments[1]; // create instance var instance = new AxialInstance(this, owner); // check undefined keys are not being passed var isPlainObject = util.isPlainObject(defaultValues); if (isPlainObject) { util.expandDotSyntaxKeys(defaultValues, function (path, key, object) { if (!_this23._properties.has(key) && !_isValidKey(key)) { throw new AxialUnexpectedProperty(key, _this23, instance); } var property = _this23._properties.get(key); var subPath = path.split('.').slice(1).join('.'); var obj = {}; util.setObjectAtPath(obj, subPath, object); defaultValues[key] = property.primaryInterface.create(obj, instance); }); } for (var key in defaultValues) { if (isPlainObject && defaultValues.hasOwnProperty(key)) { if (!this._properties.has(key) && !_isValidKey(key)) { throw new AxialUnexpectedProperty(key, this, instance); } } } this._properties.forEach(function (property, key) { // install getters and setters for each property in interface var value = defaultValues[key]; // expect property definition type to be valid AxialType if (defaultValues.hasOwnProperty(key)) { property.validate(value, instance); } // define the getter and setter property of the instance instance.defineAccessors(property); // if this is an interface, swap with AxialInstance from interface using plain object sub-tree as default values if (property.is(Axial.Interface) && !value) { value = property.primaryInterface.create(value, instance); } else if (!defaultValues.hasOwnProperty(key)) { if (property.isRequired) { throw new AxialMissingProperty(key, _this23, defaultValues); } else { value = property.defaultValue; } } // set the value of the property if (typeof value !== 'undefined') { property.set(instance, value); } }); // call init if present var init = instance.init; if (typeof init === 'function') { init.call(instance); } return instance; } }, { key: 'validate', value: function validate(value, instance, property) { // check value is object if (!AxialObject.prototype.is.call(this, value)) { throw new AxialInvalidType(util.typeOf(value).id, this.id, instance, property); } // check value has no extra props for (var key in value) { if (value.hasOwnProperty(key)) { if (!this._properties.has(key) && !_isValidKey(key)) { throw new AxialUnexpectedProperty(key, this, instance); } } } // check each property validates var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = this._properties.entries()[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var _step$value = _slicedToArray(_step.value, 2), k = _step$value[0], _property = _step$value[1]; if (!value.hasOwnProperty(k) && _property.isRequired) { throw new AxialMissingProperty(k, this, value); } if (value.hasOwnProperty(k) || _property.isRequired) { _property.validate(value[k], instance); } } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } } }, { key: 'is', value: function is(value) { if (this._id === null) { // the initial Interface type will never match values return false; } if (!AxialObject.prototype.is.call(this, value)) { return false; } // check has no extra props for (var key in value) { if (value.hasOwnProperty(key)) { if (!this._properties.has(key)) { return false; } } } // check each property validates var _iteratorNormalCompletion2 = true; var _didIteratorError2 = false; var _iteratorError2 = undefined; try { for (var _iterator2 = this._properties.entries()[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) { var _step2$value = _slicedToArray(_step2.value, 2), k = _step2$value[0], property = _step2$value[1]; if (!value.hasOwnProperty(k) && property.isRequired) { // missing property return false; } try { // value must validate if (value.hasOwnProperty(k) || property.isRequired) { property.validate(value[k]); } } catch (e) { return false; } } } catch (err) { _didIteratorError2 = true; _iteratorError2 = err; } finally { try { if (!_iteratorNormalCompletion2 && _iterator2.return) { _iterator2.return(); } } finally { if (_didIteratorError2) { throw _iteratorError2; } } } return true; } }, { key: 'has', value: function has(key) { return this._properties.has(key); } }, { key: 'property', value: function property(name) { var path = name; if (this._id && path.indexOf(this._id) !== 0) { path = this._id + '.' + path; } return this.rootInterface._allProps.get(path); } }, { key: 'forEach', value: function forEach(fn) { var _iteratorNormalCompletion3 = true; var _didIteratorError3 = false; var _iteratorError3 = undefined; try { for (var _iterator3 = this._properties[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) { var _step3$value = _slicedToArray(_step3.value, 2), key = _step3$value[0], property = _step3$value[1]; fn(property, key); } } catch (err) { _didIteratorError3 = true; _iteratorError3 = err; } finally { try { if (!_iteratorNormalCompletion3 && _iterator3.return) { _iterator3.return(); } } finally { if (_didIteratorError3) { throw _iteratorError3; } } } } }, { key: 'keys', value: function keys() { var keys = []; var _iteratorNormalCompletion4 = true; var _didIteratorError4 = false; var _iteratorError4 = undefined; try { for (var _iterator4 = this.rootInterface._allProps.keys()[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) { var path = _step4.value; keys.push(path); } } catch (err) { _didIteratorError4 = true; _iteratorError4 = err; } finally { try { if (!_iteratorNormalCompletion4 && _iterator4.return) { _iterator4.return(); } } finally { if (_didIteratorError4) { throw _iteratorError4; } } } return keys; } }, { key: 'extend', value: function extend(interfaceName) { var prototype = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; if (typeof interfaceName !== 'string') { // TODO: make proper error throw new Error('Interface requires name'); } var iface = new AxialInterface(interfaceName, prototype, this._parentInterface); iface._iparent = this; var obj = this; while (obj) { var _iteratorNormalCompletion5 = true; var _didIteratorError5 = false; var _iteratorError5 = undefined; try { for (var _iterator5 = obj._properties.entries()[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) { var _step5$value = _slicedToArray(_step5.value, 2), key = _step5$value[0], property = _step5$value[1]; if (!iface.has(key)) { iface._properties.set(key, property); iface._allProps.set(interfaceName + '.' + key, property); } } } catch (err) { _didIteratorError5 = true; _iteratorError5 = err; } finally { try { if (!_iteratorNormalCompletion5 && _iterator5.return) { _iterator5.return(); } } finally { if (_didIteratorError5) { throw _iteratorError5; } } } obj = obj._iparent; } return iface; } }, { key: 'id', get: function get() { return this._id; }, set: function set(id) { if (this._id) { delete Axial.Interface[this._id]; //test-all gone? } this._id = id; Axial.Interface[this._id] = this; } }, { key: 'rootInterface', get: function get() { var iface = this; while (iface._parentInterface) { iface = iface._parentInterface; } return iface; } }, { key: 'isRootInterface', get: function get() { return this.rootInterface === this; } }, { key: 'isSubInterface', get: function get() { return !this.isRootInterface; } }]); return AxialInterface; }(AxialObject); var AxialAnything = function (_AxialType12) { _inherits(AxialAnything, _AxialType12); function AxialAnything() { _classCallCheck(this, AxialAnything); return _possibleConstructorReturn(this, (AxialAnything.__proto__ || Object.getPrototypeOf(AxialAnything)).apply(this, arguments)); } _createClass(AxialAnything, [{ key: 'is', value: function is(value) { return true; } }, { key: 'validate', value: function validate() {} }], [{ key: 'id', get: function get() { return '*'; } }]); return AxialAnything; }(AxialType); // -------------------------------------------------------------------------------------- Instances var AxialInstance = function () { function AxialInstance(iface, owner) { _classCallCheck(this, AxialInstance); this._state = {}; this._listeners = {}; this.isWatching = false; this.id = getInstanceId(iface); this.super = {}; this.owner = owner; this.iface = iface; if (iface) { // track instance var id = iface.id; var arrayAtKey = _instances[id]; _instances[id] = Array.isArray(arrayAtKey) ? arrayAtKey : []; _instances[id].push(this); if (_instancesCreated.indexOf(iface) === -1) { _instancesCreated.push(iface); } // go through each AxialInterface._methods and bind copy to this instance var interfaceToIndex = iface; while (interfaceToIndex) { var methods = {}; this.super[interfaceToIndex.id] = methods; var _iteratorNormalCompletion6 = true; var _didIteratorError6 = false; var _iteratorError6 = undefined; try { for (var _iterator6 = interfaceToIndex._methods.entries()[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) { var _step6$value = _slicedToArray(_step6.value, 2), key = _step6$value[0], fn = _step6$value[1]; methods[key] = fn.bind(this); } } catch (err) { _didIteratorError6 = true; _iteratorError6 = err; } finally { try { if (!_iteratorNormalCompletion6 && _iterator6.return) { _iterator6.return(); } } finally { if (_didIteratorError6) { throw _iteratorError6; } } } interfaceToIndex = interfaceToIndex._iparent; } } } _createClass(AxialInstance, [{ key: 'definePrivateProperties', value: function definePrivateProperties(descriptor) { for (var name in descriptor) { if (descriptor.hasOwnProperty(name)) { this.definePrivateProperty(name, descriptor[name]); } } } }, { key: 'definePrivateProperty', value: function definePrivateProperty(name, value) { var mem = { value: value }; Object.defineProperty(this, name, { enumerable: false, get: function get() { return mem.value; }, set: function set(val) { mem.value = val; } }); } }, { key: 'typeOf', value: function typeOf(ifaceOrId) { if (typeof ifaceOrId === 'string') { return this.iface.id === ifaceOrId.id; } return this.iface === ifaceOrId; } }, { key: 'shouldAssign', value: function shouldAssign(instance, property) { if (typeof this.onAssign === 'function') { var e = { instance: instance, property: property, role: 'parent', cancel: function cancel(message) { this.canceled = true; this.message = message; } }; this.onAssign(e); if (e.canceled) { this.dispatch('reject', { instance: this, target: instance, property: property, method: 'assign', role: 'parent', key: property.key, message: e.message }); return false; } } if (typeof instance.onAssign === 'function') { var _e = { instance: this, property: property, role: 'child', cancel: function cancel(message) { this.canceled = true; this.message = message; } }; instance.onAssign(_e); if (_e.canceled) { instance.dispatch('reject', { instance: instance, target: this, property: property, method: 'assign', role: 'child', key: property.key, message: _e.message }); return false; } } return true; } }, { key: 'defineAccessors', value: function defineAccessors(property) { var key = property.key; if (this.hasOwnProperty(key)) { // TODO: use real error throw new Error('Illegal property key'); } Object.defineProperty(this, key, { enumerable: true, configurable: true, // create setter for instance set: function (value) { // wrap property setter return property.set(this, value); }.bind(this), // create getter for instance get: function () { // wrap property getter return property.get(this); }.bind(this) }); } }, { key: 'equals', value: function equals(instance) { if (this === instance) { return true; } if (util.isPlainObject(instance)) { try { instance = this.iface.create(instance); } catch (e) { return false; } } if (!(instance instanceof AxialInstance)) { return false; } var _iteratorNormalCompletion7 = true; var _didIteratorError7 = false; var _iteratorError7 = undefined; try { for (var _iterator7 = this.iface._properties.entries()[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) { var _step7$value = _slicedToArray(_step7.value, 2), key = _step7$value[0], property = _step7$value[1]; var sourceValue = this._state[key]; var targetValue = instance[key]; if (sourceValue instanceof AxialInstance) { if (targetValue instanceof AxialInstance) { return sourceValue.equals(targetValue); } else { return false; } } else if (sourceValue instanceof AxialInstanceArray) { if (targetValue instanceof AxialInstanceArray) { return sourceValue.equals(targetValue); } else { return false; } } else if (sourceValue !== targetValue) { return false; } } } catch (err) { _didIteratorError7 = true; _iteratorError7 = err; } finally { try { if (!_iteratorNormalCompletion7 && _iterator7.return) { _iterator7.return(); } } finally { if (_didIteratorError7) { throw _iteratorError7; } } } return true; } }, { key: 'bind', value: function bind(key, fn, method) { if (typeof method === 'string') { (function () { var _fn = fn; fn = function fn(e) { if (e.method === method) { _fn(e); } }; })(); } this._listeners[key] = this._listeners[key] ? this._listeners[key] : []; this._listeners[key].push(fn); } }, { key: 'unbind', value: function unbind(key, fn) { if (arguments.length === 0) { this._listeners = {}; } else if (key && !fn) { this._listeners[key].length = 0; } else { var index = this._listeners[key].indexOf(fn); this._listeners[key].splice(index, 1); } } }, { key: 'dispatch', value: function dispatch(key, eventData) { // dispatch globally too var returnValue = Axial.dispatch(eventData); if (returnValue) { // global handlers override local handlers return returnValue; } // dispatch for each event listener attached to key var listeners = this._listeners[key]; if (listeners) { var l = listeners.length; for (var i = 0; i < l; i++) { returnValue = listeners[i](eventData); if (returnValue) { return returnValue; } } } } }, { key: 'onSetter', value: function onSetter(key, fn) { return this.bind(key, fn, 'set'); } }, { key: 'onGetter', value: function onGetter(key, fn) { return this.bind(key, fn, 'get'); } }, { key: 'keys', value: function keys() { return [].concat(_toConsumableArray(this.iface._properties.keys())); } }, { key: 'property', value: function property(path) { return this.iface.property(path); } }, { key: 'value', value: function value(path, shouldThrowIfNotFound) { var root = this.rootOwner; return util.getObjectAtPath(root, path, shouldThrowIfNotFound); } }, { key: 'forEach', value: function forEach(fn) { var iface = this.iface; var _iteratorNormalCompletion8 = true; var _didIteratorError8 = false; var _iteratorError8 = undefined; try { for (var _iterator8 = iface._properties.keys()[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) { var key = _step8.value; fn(key, this._state[key]); } } catch (err) { _didIteratorError8 = true; _iteratorError8 = err; } finally { try { if (!_iteratorNormalCompletion8 && _iterator8.return) { _iterator8.return(); } } finally { if (_didIteratorError8) { throw _iteratorError8; } } } return this; } }, { key: 'map', value: function map(fn) { var array = []; var iface = this.iface; var _iteratorNormalCompletion9 = true; var _didIteratorError9 = false; var _iteratorError9 = undefined; try { for (var _iterator9 = iface._properties.keys()[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) { var key = _step9.value; array.push(fn(key, this._state[key])); } } catch (err) { _didIteratorError9 = true; _iteratorError9 = err; } finally { try { if (!_iteratorNormalCompletion9 && _iterator9.return) { _iterator9.return(); } } finally { if (_didIteratorError9) { throw _iteratorError9; } } } return array; } }, { key: 'dispose', value: function dispose() { var _this25 = this; this.iface.forEach(function (property, key) { var item = _this25._state[key]; if (typeof item.dispose === 'function') { item.dispose(); } delete _this25._state[key]; delete _this25[key]; }); delete this; delete _instances[this.iface.id]; } }, { key: 'get', value: function get(key, defaultValue) { var value = this[key]; return this._state.hasOwnProperty(key) ? value : defaultValue; } }, { key: 'set', value: function set(key, value) { this[key] = value; return this; } }, { key: 'toPlainObject', value: function toPlainObject() { try { var json = {}; var _iteratorNormalCompletion10 = true; var _didIteratorError10 = false; var _iteratorError10 = undefined; try { for (var _iterator10 = this.iface._properties.keys()[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) { var key = _step10.value; var property = this.iface._properties.get(key); if (!property.exports) { debugger; // TODO: double check all this serialisation... continue; } var value = this._state[key]; var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); if (value instanceof AxialInstance) { json[key] = value.toPlainObject(); } else if (value instanceof AxialInstanceArray) { json[key] = value.toPlainObject(); } else if (type === 'string' || type === 'number' || type === 'boolean' || util.isPlainObject(value)) { json[key] = value; } } } catch (err) { _didIteratorError10 = true; _iteratorError10 = err; } finally { try { if (!_iteratorNormalCompletion10 && _iterator10.return) { _iterator10.return(); } } finally { if (_didIteratorError10) { throw _iteratorError10; } } } return json; } catch (e) { return e; } } }, { key: 'stringify', value: function stringify(prettyPrint) { return JSON.stringify.call(null, this.toPlainObject(), null, prettyPrint === true ? 4 : undefined); } }, { key: 'toString', value: function toString() { return (this.iface.isRootInterface ? '+-' : '>-') + this.id; } }, { key: 'onAssign', value: function onAssign(instance, property) { // return false to stop the instance from being assigned to the given property of this } }, { key: 'rootOwner', get: function get() { var obj = this.owner; var root = this; while (obj) { root = obj; obj = obj.owner; } return root; } }]); return AxialInstance; }(); /** * TODO: Bubble up rejection errors to root owner. * This way components can be designed to capture errors from docked children. */ var AxialInterfaceProperty = function () { function AxialInterfaceProperty(iface, key, types, path) { _classCallCheck(this, AxialInterfaceProperty); this.iface = iface; this._key = key; this._types = types; this._path = path; iface.rootInterface._allProps.set(path, this); } _createClass(AxialInterfaceProperty, [{ key: 'is', value: function is(type) { var t = this._types; var l = t.length; for (var i = 0; i < l; i++) { var pType = t[i]; if (pType instanceof type.constructor) { if (pType instanceof AxialArray) { if (type._type && pType._type !== type._type) { return false; } } return true; } } return false; } }, { key: 'validate', value: function validate(value, instance) { var t = this._types; var l = t.length; var hasValidated = false; var errors = []; if (value instanceof AxialInstanceArray) { value = value._array; } for (var i = 0; i < l; i++) { var type = t[i]; try { var didValidate = type.validate(value, instance, this) !== false; if (!didValidate) { return false; } hasValidated = true; } catch (e) { e.key = this.key; errors.push({ type: type, error: e }); } } if (!hasValidated) { throw errors[0].error; } return true; } /** * setter * @param instance * @param value */ }, { key: 'set', value: function set(instance, value) { var _this26 = this; var oldValue = instance._state[this._key]; var rawValue = value; var type = util.typeOf(value); var didValidate = void 0; try { didValidate = this.validate(value, instance); if (!didValidate) { // if any built-in or validate() validation method returns false, // don't set the value instance.dispatch('reject', { instance: instance, target: instance, property: this, method: 'set', key: this._key, value: value, newValue: rawValue, oldValue: oldValue }); return; } } catch (e) { instance.dispatch('reject', { instance: instance, target: instance, property: this, method: 'set', key: this._key, value: value, newValue: rawValue, oldValue: oldValue, error: e }); throw e; } // clip if number with clipping if (this.is(Axial.Number) && type.id === 'number') { var numType = this.getType(Axial.Number); if (numType._clip) { value = numType.clip(value); } } // convert to AxialInstance if Interface and object given if (this.is(Axial.Interface) && util.isPlainObject(value)) { var iface = this.primaryInterface; value = iface.create(value, instance); } // trigger assign events, give owner a chance to reject the child being assigned if (value instanceof AxialInstance) { var shouldAssign = instance.shouldAssign(value, this); if (shouldAssign === false) { return false; } } // convert to AxialInstanceArray if array if (this.is(Axial.Array()) && Array.isArray(value)) { value = new AxialInstanceArray(instance, this, value); } // convert to bound function (if function) if (this.is(Axial.Function) && typeof value === 'function' && !value._isAxialBound) { (function () { var fn = value; value = function () { // dispatch call, execute function instance.dispatch(this._key, { instance: instance, target: instance, property: this, method: 'call', key: this._key, value: arguments, arguments: arguments, newValue: fn, oldValue: fn }); return fn.apply(instance, arguments); }.bind(_this26); value._isAxialBound = true; })(); } // set state instance._state[this._key] = value; // dispatch event var returnValue = instance.dispatch(this._key, { instance: instance, target: instance, property: this, method: 'set', key: this._key, value: rawValue, newValue: value, oldValue: oldValue }); if (returnValue) { // re-set state from intercepted listener return value instance[this._key] = returnValue; } if (value instanceof AxialInstance) { (function () { // let instance value know it was docked var oldOwner = value.owner; value.owner = instance; var event = { instance: instance, property: _this26, method: 'assign', role: 'child', key: _this26.key, newOwner: instance, oldOwner: oldOwner, preserveOwner: function preserveOwner() { value.owner = oldOwner; } }; if (typeof value.onAssigned === 'function') { value.onAssigned(event); } value.dispatch(_this26.key, event); })(); } } /** * getter * @param instance * @returns {*} */ }, { key: 'get', value: function get(instance) { var value = instance._state[this._key]; // dispatch event instance.dispatch(this._key, { instance: instance, target: instance, property: this, method: 'get', key: this._key, value: value }); return value; } }, { key: 'getType', value: function getType(type) { for (var i = 0; i < this._types.length; i++) { if (this._types[i].constructor === type.constructor) { return this._types[i]; } } // TODO: proper error throw new Error('Type not found'); } }, { key: 'path', get: function get() { return this._path; } }, { key: 'key', get: function get() { return this._key; } }, { key: 'types', get: function get() { return this._types; } }, { key: 'defaultValue', get: function get() { return this.primaryType._defaultValue; } }, { key: 'isSingleType', get: function get() { return this._types.length === 1; } }, { key: 'isInterface', get: function get() { return this.is(Axial.Interface); } }, { key: 'primaryType', get: function get() { return this._types[0]; } }, { key: 'deepPrimaryArrayType', get: function get() { var type = this._types[0]; if (!(type instanceof AxialArray)) { return null; } while (type instanceof AxialArray && type._type && !(type instanceof AxialInstanceArray)) { type = type._type; } return type; } }, { key: 'primaryInterface', get: function get() { return this._types.find(function (type) { return type instanceof AxialInterface; }); } }, { key: 'primaryArrayType', get: function get() { var array = this._types.find(function (type) { return type instanceof AxialArray; }); return array ? array.type : null; } }, { key: 'isRequired', get: function get() { for (var i = 0; i < this._types.length; i++) { if (this._types[i]._required) { return true; } } return false; } }, { key: 'exports', get: function get() { for (var i = 0; i < this._types.length; i++) { if (!this._types[i]._exports) { return false; } } return true; } }]); return AxialInterfaceProperty; }(); var AxialBinding = function () { function AxialBinding(instance, key, handler) { _classCallCheck(this, AxialBinding); this._instance = instance; this._key = key; this._property = instance.property(this._key); this._handler = handler; this._active = false; } _createClass(AxialBinding, [{ key: 'bind', value: function bind() { this._instance.bind(this._key, this._handler); this._active = true; _bindings.push(this); } }, { key: 'unbind', value: function unbind() { this._instance.unbind(this._key, this._handler); this._active = false; var i = _bindings.indexOf(this); _bindings.splice(i, 1); } }, { key: 'dispose', value: function dispose() { if (this._active) { this.unbind(); } delete this._instance; delete this._handler; } }, { key: 'get', value: function get() { return this._instance._state[this._key]; } }, { key: 'toString', value: function toString() { return this._instance.toString() + ':' + this._key; } }, { key: 'instance', get: function get() { return this._instance; } }, { key: 'key', get: function get() { return this._key; } }, { key: 'property', get: function get() { return this._property; } }, { key: 'handler', get: function get() { return this._handler; } }, { key: 'isActive', get: function get() { return this._active; } }]); return AxialBinding; }(); var AxialInstanceArray = function () { function AxialInstanceArray(instance, property) { var _this27 = this; var array = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : []; _classCallCheck(this, AxialInstanceArray); this._instance = instance; this.id = getInstanceId(AxialInstanceArray); this._property = property; this._key = property.key; this._indexLength = null; var self = this; // expand items to instances if interface type this._array = array; if (array.length) { this._array = this.convertArray(array); } this.length = this._array.length; _arrayMembers.forEach(function (member) { // stub each member of Array.prototype // validate arguments if mutator... Object.defineProperty(_this27, member, { enumerable: false, value: function value() { var args = Array.prototype.slice.call(arguments); var isMutator = _arrayMutators.indexOf(member) > -1; var hasValidated = true; if (member === 'push') { property.validate(args, self._instance); args = this.convertArray(args); } else if (member === 'splice') { if (args.length > 2) { // inserting property.validate(args.slice(2), self._instance); } args = this.convertArray(args); } else if (member === 'unshift') { property.validate(args, self._instance); args = this.convertArray(args); } else if (member === 'fill') { property.primaryType.isItem(args); args = [args[0]]; args = this.convertArray(args); } else { hasValidated = true; } var oldLength = this._array.length; var returnValue = Array.prototype[member].apply(this._array, args); this.length = this._array.length; // ...otherwise validate array (is valid type?) afterwards if (!hasValidated) { property.validate(this._array, self._instance); } // if this is an array mutator method, dispatch event if (isMutator) { self.bindIndexes(); this.dispatch(this._key, { instance: instance, property: this._property, method: 'set', arrayMethod: member, key: this._key, value: this, newValue: this, oldValue: null, oldLength: oldLength, newLength: this._array.length }); } return returnValue; } }); }); this.bindIndexes(); } _createClass(AxialInstanceArray, [{ key: 'bindIndexes', value: function bindIndexes() { var _this28 = this; var array = this._array; var instance = this._instance; var property = this._property; // delete previous indexes if (this._indexLength) { var _l = this._indexLength; for (var i = 0; i < _l; i++) { delete this[i]; } } // write each index as an accessor var l = array.length + 1; var _loop = function _loop(_i) { _this28._indexLength++; var key = '' + _i; if (!_this28.hasOwnProperty(key)) { Object.defineProperty(_this28, key, { get: function get() { // dispatch event instance.dispatch(property.key, { instance: instance, property: property, arrayMethod: 'index', method: 'get', index: _i, key: property.key, value: array[_i] }); return array[_i]; }, set: function set(value) { var _this29 = this; var oldValue = array[_i]; var rawValue = value; property.validate([value], instance); // convert to AxialInstance if Interface and object given var arrayType = property.primaryArrayType; if (arrayType && util.isPlainObject(value) && arrayType.is(value)) { value = arrayType.create(value, instance); } // convert to AxialInstanceArray if array if (property.is(Axial.Array()) && Array.isArray(value)) { value = new AxialInstanceArray(instance, property, value); } // convert to bound function (if function) if (property.is(Axial.Function) && typeof value === 'function' && !value._isAxialBound) { (function () { var fn = value; value = function () { // dispatch call, execute function instance.dispatch(property._key, { instance: instance, property: property, method: 'call', key: property._key, value: arguments, arguments: arguments, newValue: fn, oldValue: fn }); return fn.apply(instance, arguments); }.bind(_this29); value._isAxialBound = true; })(); } array[_i] = value; instance.dispatch(property.key, { instance: instance, property: property, arrayMethod: 'index', method: 'set', index: _i, key: property.key, value: value, oldValue: oldValue, newValue: rawValue }); }, enumerable: true, configurable: true }); } }; for (var _i = 0; _i < l; _i++) { _loop(_i); } } }, { key: 'dispatch', value: function dispatch(key, e) { this._instance.dispatch(key, e); } }, { key: 'convertArray', value: function convertArray(rawArray) { // convert plain array to array of wrapped objects ~ AxialInstance or AxialInstanceArray or value var array = []; var l = rawArray.length; for (var i = 0; i < l; i++) { var item = rawArray[i]; if (item instanceof AxialInstance || item instanceof AxialInstanceArray) { array[i] = item; continue; } var deepPrimaryArrayType = this.property.deepPrimaryArrayType; if (deepPrimaryArrayType && deepPrimaryArrayType instanceof AxialInterface && deepPrimaryArrayType.is(item)) { // find primary type form array array[i] = deepPrimaryArrayType.create(item, this._instance); continue; } var type = Axial.typeOf(item); if (type instanceof AxialInterface) { // create instance of interface with item as default values array[i] = type.create(item, this._instance); continue; } else if (type instanceof AxialArray) { array[i] = new AxialInstanceArray(this._instance, this._property, item); continue; } // plain value array[i] = item; } return array; } }, { key: 'equals', value: function equals(array) { if (this === array) { return true; } var targetArray = array instanceof AxialInstanceArray ? array._array : array; if (array.length !== this.length || !Array.isArray(targetArray)) { return false; } // iterate through and check equal items var l = targetArray.length; var sourceArray = this._array; for (var i = 0; i < l; i++) { var sourceItem = sourceArray[i]; var targetItem = targetArray[i]; if (sourceItem instanceof AxialInstance) { if (targetItem instanceof AxialInstance) { return sourceItem.equals(targetItem); } else { return false; } } else if (sourceItem instanceof AxialInstanceArray) { if (targetItem instanceof AxialInstanceArray) { return sourceItem.equals(targetItem); } else { return false; } } else if (sourceItem !== targetItem) { return false; } } return true; } }, { key: 'add', value: function add() /*items, ...*/{ var items = util.argsToItems.apply(null, arguments); this.push.apply(this, items); } }, { key: 'remove', value: function remove() /*items, ...*/{ var array = this._array; var items = util.argsToItems.apply(null, arguments); var l = items.length; for (var i = 0; i < l; i++) { var item = items[i]; var index = array.indexOf(item); this.splice(index, 1); } this.length = this._array.length; } }, { key: 'contains', value: function contains() /*items, ...*/{ var items = util.argsToItems.apply(null, arguments); var l = items.length; var array = this._array; for (var i = 0; i < l; i++) { if (array.indexOf(items[i]) > -1) { return true; } } return false; } }, { key: 'move', value: function move(fromIndex, toIndex) { var item = this.splice(fromIndex, 1)[0]; this.splice(toIndex, 0, item); return item; } }, { key: 'moveUp', value: function moveUp(item) { var fromIndex = this.indexOf(item); if (fromIndex > 0) { this.move(fromIndex, fromIndex - 1); return true; } return false; } }, { key: 'moveDown', value: function moveDown(item) { var fromIndex = this.indexOf(item); if (fromIndex > -1 && fromIndex < this._array.length - 1) { this.move(fromIndex, fromIndex + 1); return true; } return false; } }, { key: 'shiftLeft', value: function shiftLeft() { var item = this.shift(); this.push(item); return item; } }, { key: 'shiftRight', value: function shiftRight() { var item = this.pop(); this.unshift(item); return item; } }, { key: 'first', value: function first() { return this._array[0]; } }, { key: 'last', value: function last() { return this._array[this._array.length - 1]; } }, { key: 'plural', value: function plural() { return this.length === 1 ? '' : 's'; } }, { key: 'toPlainObject', value: function toPlainObject() { var array = []; var l = this._array.length; for (var i = 0; i < l; i++) { var item = this._array[i]; if (item instanceof AxialInstance) { array[i] = item.toPlainObject(); } else if (item instanceof AxialInstanceArray) { array[i] = item.toPlainObject(); } else { array[i] = item; } } return array; } }, { key: 'stringify', value: function stringify(prettyPrint) { return JSON.stringify.call(null, this.toPlainObject(), null, prettyPrint === true ? 4 : undefined); } }, { key: 'isEmpty', get: function get() { return this.length === 0; } }, { key: 'instance', get: function get() { return this._instance; } }, { key: 'property', get: function get() { return this._property; } }, { key: 'key', get: function get() { return this._key; } }, { key: 'array', get: function get() { return this._array; } }], [{ key: 'id', get: function get() { return 'AxialInstanceArray'; } }]); return AxialInstanceArray; }(); // -------------------------------------------------------------------------------------- Util util = { isPlainObject: function isPlainObject(o) { var t = o; return (typeof o === 'undefined' ? 'undefined' : _typeof(o)) !== 'object' || o === null ? false : function () { while (true) { if (Object.getPrototypeOf(t = Object.getPrototypeOf(t)) === null) { break; } } return Object.getPrototypeOf(o) === t; }(); }, merge: function merge(source, target) { var _this30 = this; var copy = function copy(_source, _target) { for (var _key in _target) { if (_target.hasOwnProperty(_key)) { var sourceValue = _source[_key]; var targetValue = _target[_key]; if (_this30.isPlainObject(targetValue)) { if (_this30.isPlainObject(sourceValue)) { copy(sourceValue, targetValue); } else { var obj = {}; _source[_key] = obj; copy(obj, targetValue); } } else { _source[_key] = targetValue; } } } return source; }; return copy(source, target); }, typeOf: function typeOf(value, nativeOnly) { if (value instanceof AxialInstance) { if (nativeOnly) { return T.Object; } return value.iface; } if (T.Null.is(value)) { return T.Null; } else if (T.Undefined.is(value)) { return T.Undefined; } else if (T.String.is(value)) { return T.String; } else if (T.Number.is(value)) { return T.Number; } else if (T.Boolean.is(value)) { return T.Boolean; } else if (T.Date.is(value)) { return T.Date; } else if (T.Regex.is(value)) { return T.Regex; } else if (T.Function.is(value)) { return T.Function; } else if (T.Array.is(value)) { if (nativeOnly) { return T.Array(); } if (value.length) { return T.Array(this.typeOf(value[0])); } else { return T.Array(); } } else if (T.Object.is(value)) { return T.Object; } else if (T.Interface.is(value)) { if (nativeOnly) { return T.Object; } return T.Interface; } throw new AxialUnsupportedType(value); }, isType: function isType(type) { type = Array.isArray(type) ? type : [type]; var l = type.length; for (var i = 0; i < l; i++) { if (!(type[i] instanceof AxialType)) { return false; } } return true; }, getObjectPaths: function getObjectPaths(obj, includeBranchPaths) { var _this31 = this; var keys = []; var ref = null; var path = null; var walk = function walk(o, p) { for (var k in o) { if (o.hasOwnProperty(k)) { ref = o[k]; path = p ? p + '.' + k : k; if (_this31.isPlainObject(ref)) { if (includeBranchPaths === true) { keys.push(path); } walk(ref, path); } else { keys.push(path); } } } }; walk(obj); return keys; }, getObjectPathValues: function getObjectPathValues(obj, includeBranchPaths) { var _this32 = this; var keyValues = []; var ref = null; var path = null; var walk = function walk(o, p) { for (var k in o) { if (o.hasOwnProperty(k)) { ref = o[k]; path = p ? p + '.' + k : k; if (_this32.isPlainObject(ref)) { if (includeBranchPaths === true) { keyValues.push({ path: path, value: ref, isBranch: true }); } walk(ref, path); } else { keyValues.push({ path: path, value: ref, isBranch: false }); } } } }; walk(obj); return keyValues; }, getObjectAtPath: function getObjectAtPath(obj, path, shouldThrowIfNotFound) { var steps = path.split('.'); var l = steps.length; var ref = obj; var k = null; for (var i = 0; i < l; i++) { k = steps[i]; ref = ref[k]; if (ref === null || typeof ref === 'undefined') { if (shouldThrowIfNotFound === true) { throw new AxialUndefinedValue(obj, path); } return ref; } } return ref; }, setObjectAtPath: function setObjectAtPath(obj, path, value) { var ref = obj; var steps = path.split('.'); var l = steps.length - 1; var k = null; for (var i = 0; i < l; i++) { k = steps[i]; if (!ref.hasOwnProperty(k)) { ref[k] = {}; } ref = ref[k]; } ref[steps[l]] = value; }, multiSetObjectAtPath: function multiSetObjectAtPath(obj, pathOrObject, value) { var modifiedPaths = null; if (this.isPlainObject(pathOrObject)) { this.merge(obj, pathOrObject); modifiedPaths = this.getObjectPaths(pathOrObject); } else if (typeof pathOrObject === 'string') { this.setObjectAtPath(obj, pathOrObject, value); modifiedPaths = [pathOrObject]; } return modifiedPaths; }, expandDotSyntaxKeys: function expandDotSyntaxKeys(obj, resolver) { for (var path in obj) { if (obj.hasOwnProperty(path)) { if (path.indexOf('.') > -1) { var _key2 = path.split('.')[0]; resolver(path, _key2, obj[path]); delete obj[path]; } } } return obj; }, expandArray: function expandArray(inArray) { var outArray = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; var l = inArray.length; for (var i = 0; i < l; i++) { var item = inArray[i]; if (Array.isArray(item)) { this.expandArray(item, outArray); } else { outArray[outArray.length] = item; } } return outArray; }, stringify: function stringify(value) { var _this33 = this; var refs = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (typeof value === 'function') { return 'function () {...}'; } if (Array.isArray(value)) { return '[#' + value.length + ']'; } if (value instanceof AxialInstance) { if (refs.indexOf(value) > -1) { return 'circular!' + value.toString(); } else { refs.push(value); } var props = value.map(function (k, v) { return k + ':' + _this33.stringify(v, refs); }); return '*' + value.iface.id + '#' + value.id + '{' + props.join(', ') + '}'; } if (value instanceof AxialInstanceArray) { return '*array#' + value.id + '[' + value.length + ']'; } try { return JSON.stringify(value); } catch (e) { return '' + value; } }, argsToItems: function argsToItems() { var array = []; var l = arguments.length; if (l === 1 && Array.isArray(arguments[0])) { array.push.apply(array, arguments); } else if (l > 0) { for (var i = 0; i < l; i++) { var item = arguments[i]; array.push(item); } } return array; }, toString: function toString(value) { if (value instanceof AxialInstance || value instanceof AxialInstanceArray) { return value.id; } try { return JSON.stringify(value); } catch (e) { return '' + value; } } }; // -------------------------------------------------------------------------------------- Define Types T = { Null: new AxialNull(), Undefined: new AxialUndefined(), String: new AxialString(), Number: new AxialNumber(), Boolean: new AxialBoolean(), Date: new AxialDate(), Regex: new AxialRegex(), Function: new AxialFunction(), Array: function Array(type) { var typeId = type ? type.id : '*'; var t = _arrayTypes[typeId]; if (t) { return t; } else { t = _arrayTypes[typeId] = new AxialArray(type); t._baseType = this.Array(); t._id = 'array[' + typeId + ']'; } return t; }, Object: new AxialObject(), Interface: new AxialInterface(null), Reference: new AxialReference(), Anything: new AxialAnything() }; Object.keys(T).forEach(function (typeName) { T[typeName].orUndefined = function () { return [T[typeName], Axial.Undefined]; }; T[typeName].orNull = function () { return [T[typeName], Axial.Null]; }; T[typeName].orUndefinedOrNull = function () { return [T[typeName], Axial.Undefined, Axial.Null]; }; }); T.Array.is = function (value) { if (value instanceof AxialInstanceArray) { return true; } return Array.isArray(value); }; T.Array.Type = T.Array(); // -------------------------------------------------------------------------------------- Axial var Axial = (_Axial = { define: function define(id, prototype) { return new AxialInterface(id, prototype); }, getInterface: function getInterface() { var id = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'null'; // return first one defined (allows easy mocking/testing) var ifaceArray = _interfaces[id]; if (ifaceArray) { return ifaceArray[ifaceArray.length - 1]; } }, interfaceIds: function interfaceIds() { return Object.keys(_interfaces).filter(function (id) { var ifaceArray = _interfaces[id]; return ifaceArray[0].isRootInterface; }); }, interfaces: function interfaces() { var o = {}; this.interfaceIds().forEach(function (id) { return o[id] = _interfaces[id]; }); return o; }, get instances() { return _instances; }, get bindings() { return _bindings; }, get bindingInfo() { return this.bindings.map(function (binding) { return binding.instance.id + ':' + binding.key; }); }, getInstance: function getInstance(id) { var arrayAtKey = _instances[id]; return Array.isArray(arrayAtKey) ? arrayAtKey[arrayAtKey.length - 1] : null; } }, _defineProperty(_Axial, 'instances', function instances() { return _instances; }), _defineProperty(_Axial, 'instanceCount', function instanceCount() { var count = {}; for (var id in _instances) { if (_instances.hasOwnProperty(id)) { count[id] = _instances[id].length; } } return count; }), _defineProperty(_Axial, 'instancesCreated', function instancesCreated(includeSubInterfaces) { return _instancesCreated.filter(function (iface) { return includeSubInterfaces || iface.isRootInterface; }).map(function (iface) { return iface.id; }); }), _defineProperty(_Axial, 'bind', function bind(fn) { _listeners.push(fn); }), _defineProperty(_Axial, 'unbind', function unbind(fn) { if (fn) { var index = _listeners.indexOf(fn); _listeners.splice(index, 1); } else { _listeners.length = 0; } }), _defineProperty(_Axial, 'dispatch', function dispatch(eventData) { if (_logListenerCount) { // logging is a separate listener collection, // in case Axial.unbind() is called logging can continue. this.log(eventData); } var l = _listeners.length; for (var i = 0; i < l; i++) { var returnValue = _listeners[i](eventData); if (returnValue) { return returnValue; } } }), _defineProperty(_Axial, 'Binding', AxialBinding), _defineProperty(_Axial, 'CONST', CONST), _defineProperty(_Axial, 'Instance', new AxialInstance()), _defineProperty(_Axial, 'InstanceArray', AxialInstanceArray), _defineProperty(_Axial, 'util', util), _defineProperty(_Axial, 'addLogListener', function addLogListener(method, fn) { _logListeners[method] = _logListeners[method] || []; _logListeners[method].push(fn); _logListenerCount++; return this; }), _defineProperty(_Axial, 'removeLogListener', function removeLogListener(method, fn) { if (typeof fn === 'undefined') { _logListeners[method] = []; return; } var index = _logListeners[method].indexOf(fn); _logListeners[method].splice(index, 1); _logListenerCount--; return this; }), _defineProperty(_Axial, 'log', function log(e) { if (_logListeners.hasOwnProperty(e.method)) { var array = _logListeners[e.method]; var l = array.length; for (var i = 0; i < l; i++) { array[i](e); } } }), _defineProperty(_Axial, 'addDefaultLogListeners', function addDefaultLogListeners() { this.addLogListener('get', function (e) { if (typeof e.value === 'function') { console.log('%cGET: ' + (e.instance.toString() + '.' + e.key) + (e.hasOwnProperty('index') ? '[' + e.index + ']' : '') + ':<' + e.property.types.join('|') + '>()', 'color:#999'); } else { console.log('%cGET: ' + (e.instance.toString() + '.' + e.key) + (e.hasOwnProperty('index') ? '[' + e.index + ']' : '') + ':<' + e.property.types.join('|') + '> = ' + util.toString(e.value), 'color:#999'); } }).addLogListener('set', function (e) { console.log('%cSET: ' + e.property.path + ':<' + e.property.types.join('|') + '> = ' + util.stringify(e.value), 'color:orange'); }).addLogListener('call', function (e) { var args = []; var l = e.arguments.length; for (var i = 0; i < l; i++) { var arg = void 0; try { arg = JSON.stringify(e.arguments[i]); } catch (ex) { arg = util.typeOf(e.arguments[i]).id; } args.push(arg + ':' + _typeof(e.arguments[i])); } console.log('%cCALL: ' + e.property.path + ('(' + (args.length ? '<' : '')) + args.join('>, <') + ((args.length ? '>' : '') + ')'), 'color:pink'); }); }), _defineProperty(_Axial, 'typeOf', function typeOf(value, nativeOnly) { var type = util.typeOf(value, nativeOnly); if (type.constructor === AxialObject) { if (nativeOnly) { return type; } var ifaceNames = this.interfaceIds(); var l = ifaceNames.length; for (var i = 0; i < l; i++) { var id = ifaceNames[i]; var iface = this.getInterface(id); // gets latest version with same id if (iface.is(value)) { return iface; } } } return type; }), _defineProperty(_Axial, 'debug', function debug() { this.addDefaultLogListeners(); }), _Axial); // merge in types and errors util.merge(Axial, T); util.merge(Axial, Errors); // extend misc types public interface AxialInterface.prototype.new = AxialInterface.prototype.create; AxialType.prototype.set = AxialType.prototype.defaultValue; if (typeof window !== 'undefined') { window.Axial = Axial; } return Axial; }(); /***/ }, /* 2 */ /***/ function(module, exports) { 'use strict'; module.exports = { BLANK_INTERFACE_NAME: 'anonymous', VALID_KEYS: ['_state', '_listeners', 'isWatching', 'super', 'id', 'iface', 'owner', '_lockedPaths'], ARRAY_MEMBERS: ['concat', 'copyWithin', 'entries', 'every', 'fill', 'filter', 'find', 'findIndex', 'forEach', 'includes', 'indexOf', 'join', 'keys', 'lastIndexOf', 'map', 'pop', 'push', 'reduce', 'reduceRight', 'reverse', 'shift', 'slice', 'some', 'sort', 'splice', 'toLocaleString', 'toSource', 'toString', 'unshift', 'values'], ARRAY_MUTATORS: ['copyWithin', 'fill', 'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], ARRAY_MUTATORS_REQUIRE_ARGS_VALIDATED: ['fill', 'push', 'splice', 'unshift'] }; /***/ }, /* 3 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var _Expectation = __webpack_require__(4); var _Expectation2 = _interopRequireDefault(_Expectation); var _SpyUtils = __webpack_require__(16); var _assert = __webpack_require__(14); var _assert2 = _interopRequireDefault(_assert); var _extend = __webpack_require__(34); var _extend2 = _interopRequireDefault(_extend); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function expect(actual) { return new _Expectation2.default(actual); } expect.createSpy = _SpyUtils.createSpy; expect.spyOn = _SpyUtils.spyOn; expect.isSpy = _SpyUtils.isSpy; expect.restoreSpies = _SpyUtils.restoreSpies; expect.assert = _assert2.default; expect.extend = _extend2.default; module.exports = expect; /***/ }, /* 4 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _has = __webpack_require__(5); var _has2 = _interopRequireDefault(_has); var _tmatch = __webpack_require__(8); var _tmatch2 = _interopRequireDefault(_tmatch); var _assert = __webpack_require__(14); var _assert2 = _interopRequireDefault(_assert); var _SpyUtils = __webpack_require__(16); var _TestUtils = __webpack_require__(21); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * An Expectation is a wrapper around an assertion that allows it to be written * in a more natural style, without the need to remember the order of arguments. * This helps prevent you from making mistakes when writing tests. */ var Expectation = function () { function Expectation(actual) { _classCallCheck(this, Expectation); this.actual = actual; if ((0, _TestUtils.isFunction)(actual)) { this.context = null; this.args = []; } } _createClass(Expectation, [{ key: 'toExist', value: function toExist(message) { (0, _assert2.default)(this.actual, message || 'Expected %s to exist', this.actual); return this; } }, { key: 'toNotExist', value: function toNotExist(message) { (0, _assert2.default)(!this.actual, message || 'Expected %s to not exist', this.actual); return this; } }, { key: 'toBe', value: function toBe(value, message) { (0, _assert2.default)(this.actual === value, message || 'Expected %s to be %s', this.actual, value); return this; } }, { key: 'toNotBe', value: function toNotBe(value, message) { (0, _assert2.default)(this.actual !== value, message || 'Expected %s to not be %s', this.actual, value); return this; } }, { key: 'toEqual', value: function toEqual(value, message) { try { (0, _assert2.default)((0, _TestUtils.isEqual)(this.actual, value), message || 'Expected %s to equal %s', this.actual, value); } catch (error) { // These attributes are consumed by Mocha to produce a diff output. error.actual = this.actual; error.expected = value; error.showDiff = true; throw error; } return this; } }, { key: 'toNotEqual', value: function toNotEqual(value, message) { (0, _assert2.default)(!(0, _TestUtils.isEqual)(this.actual, value), message || 'Expected %s to not equal %s', this.actual, value); return this; } }, { key: 'toThrow', value: function toThrow(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).toThrow() must be a function, %s was given', this.actual); (0, _assert2.default)((0, _TestUtils.functionThrows)(this.actual, this.context, this.args, value), message || 'Expected %s to throw %s', this.actual, value || 'an error'); return this; } }, { key: 'toNotThrow', value: function toNotThrow(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).toNotThrow() must be a function, %s was given', this.actual); (0, _assert2.default)(!(0, _TestUtils.functionThrows)(this.actual, this.context, this.args, value), message || 'Expected %s to not throw %s', this.actual, value || 'an error'); return this; } }, { key: 'toBeA', value: function toBeA(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(value) || typeof value === 'string', 'The "value" argument in toBeA(value) must be a function or a string'); (0, _assert2.default)((0, _TestUtils.isA)(this.actual, value), message || 'Expected %s to be a %s', this.actual, value); return this; } }, { key: 'toNotBeA', value: function toNotBeA(value, message) { (0, _assert2.default)((0, _TestUtils.isFunction)(value) || typeof value === 'string', 'The "value" argument in toNotBeA(value) must be a function or a string'); (0, _assert2.default)(!(0, _TestUtils.isA)(this.actual, value), message || 'Expected %s to not be a %s', this.actual, value); return this; } }, { key: 'toMatch', value: function toMatch(pattern, message) { (0, _assert2.default)((0, _tmatch2.default)(this.actual, pattern), message || 'Expected %s to match %s', this.actual, pattern); return this; } }, { key: 'toNotMatch', value: function toNotMatch(pattern, message) { (0, _assert2.default)(!(0, _tmatch2.default)(this.actual, pattern), message || 'Expected %s to not match %s', this.actual, pattern); return this; } }, { key: 'toBeLessThan', value: function toBeLessThan(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeLessThan() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeLessThan(value) must be a number'); (0, _assert2.default)(this.actual < value, message || 'Expected %s to be less than %s', this.actual, value); return this; } }, { key: 'toBeLessThanOrEqualTo', value: function toBeLessThanOrEqualTo(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeLessThanOrEqualTo() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeLessThanOrEqualTo(value) must be a number'); (0, _assert2.default)(this.actual <= value, message || 'Expected %s to be less than or equal to %s', this.actual, value); return this; } }, { key: 'toBeGreaterThan', value: function toBeGreaterThan(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeGreaterThan() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeGreaterThan(value) must be a number'); (0, _assert2.default)(this.actual > value, message || 'Expected %s to be greater than %s', this.actual, value); return this; } }, { key: 'toBeGreaterThanOrEqualTo', value: function toBeGreaterThanOrEqualTo(value, message) { (0, _assert2.default)(typeof this.actual === 'number', 'The "actual" argument in expect(actual).toBeGreaterThanOrEqualTo() must be a number'); (0, _assert2.default)(typeof value === 'number', 'The "value" argument in toBeGreaterThanOrEqualTo(value) must be a number'); (0, _assert2.default)(this.actual >= value, message || 'Expected %s to be greater than or equal to %s', this.actual, value); return this; } }, { key: 'toInclude', value: function toInclude(value, compareValues, message) { if (typeof compareValues === 'string') { message = compareValues; compareValues = null; } if (compareValues == null) compareValues = _TestUtils.isEqual; var contains = false; if ((0, _TestUtils.isArray)(this.actual)) { contains = (0, _TestUtils.arrayContains)(this.actual, value, compareValues); } else if ((0, _TestUtils.isObject)(this.actual)) { contains = (0, _TestUtils.objectContains)(this.actual, value, compareValues); } else if (typeof this.actual === 'string') { contains = (0, _TestUtils.stringContains)(this.actual, value); } else { (0, _assert2.default)(false, 'The "actual" argument in expect(actual).toInclude() must be an array, object, or a string'); } (0, _assert2.default)(contains, message || 'Expected %s to include %s', this.actual, value); return this; } }, { key: 'toExclude', value: function toExclude(value, compareValues, message) { if (typeof compareValues === 'string') { message = compareValues; compareValues = null; } if (compareValues == null) compareValues = _TestUtils.isEqual; var contains = false; if ((0, _TestUtils.isArray)(this.actual)) { contains = (0, _TestUtils.arrayContains)(this.actual, value, compareValues); } else if ((0, _TestUtils.isObject)(this.actual)) { contains = (0, _TestUtils.objectContains)(this.actual, value, compareValues); } else if (typeof this.actual === 'string') { contains = (0, _TestUtils.stringContains)(this.actual, value); } else { (0, _assert2.default)(false, 'The "actual" argument in expect(actual).toExclude() must be an array, object, or a string'); } (0, _assert2.default)(!contains, message || 'Expected %s to exclude %s', this.actual, value); return this; } }, { key: 'toIncludeKeys', value: function toIncludeKeys(keys, comparator, message) { var _this = this; if (typeof comparator === 'string') { message = comparator; comparator = null; } if (comparator == null) comparator = _has2.default; (0, _assert2.default)(_typeof(this.actual) === 'object', 'The "actual" argument in expect(actual).toIncludeKeys() must be an object, not %s', this.actual); (0, _assert2.default)((0, _TestUtils.isArray)(keys), 'The "keys" argument in expect(actual).toIncludeKeys(keys) must be an array, not %s', keys); var contains = keys.every(function (key) { return comparator(_this.actual, key); }); (0, _assert2.default)(contains, message || 'Expected %s to include key(s) %s', this.actual, keys.join(', ')); return this; } }, { key: 'toIncludeKey', value: function toIncludeKey(key) { for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } return this.toIncludeKeys.apply(this, [[key]].concat(args)); } }, { key: 'toExcludeKeys', value: function toExcludeKeys(keys, comparator, message) { var _this2 = this; if (typeof comparator === 'string') { message = comparator; comparator = null; } if (comparator == null) comparator = _has2.default; (0, _assert2.default)(_typeof(this.actual) === 'object', 'The "actual" argument in expect(actual).toExcludeKeys() must be an object, not %s', this.actual); (0, _assert2.default)((0, _TestUtils.isArray)(keys), 'The "keys" argument in expect(actual).toIncludeKeys(keys) must be an array, not %s', keys); var contains = keys.every(function (key) { return comparator(_this2.actual, key); }); (0, _assert2.default)(!contains, message || 'Expected %s to exclude key(s) %s', this.actual, keys.join(', ')); return this; } }, { key: 'toExcludeKey', value: function toExcludeKey(key) { for (var _len2 = arguments.length, args = Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { args[_key2 - 1] = arguments[_key2]; } return this.toExcludeKeys.apply(this, [[key]].concat(args)); } }, { key: 'toHaveBeenCalled', value: function toHaveBeenCalled(message) { var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toHaveBeenCalled() must be a spy'); (0, _assert2.default)(spy.calls.length > 0, message || 'spy was not called'); return this; } }, { key: 'toHaveBeenCalledWith', value: function toHaveBeenCalledWith() { for (var _len3 = arguments.length, expectedArgs = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { expectedArgs[_key3] = arguments[_key3]; } var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toHaveBeenCalledWith() must be a spy'); (0, _assert2.default)(spy.calls.some(function (call) { return (0, _TestUtils.isEqual)(call.arguments, expectedArgs); }), 'spy was never called with %s', expectedArgs); return this; } }, { key: 'toNotHaveBeenCalled', value: function toNotHaveBeenCalled(message) { var spy = this.actual; (0, _assert2.default)((0, _SpyUtils.isSpy)(spy), 'The "actual" argument in expect(actual).toNotHaveBeenCalled() must be a spy'); (0, _assert2.default)(spy.calls.length === 0, message || 'spy was not supposed to be called'); return this; } }]); return Expectation; }(); var deprecate = function deprecate(fn, message) { var alreadyWarned = false; return function () { if (!alreadyWarned) { alreadyWarned = true; console.warn(message); } for (var _len4 = arguments.length, args = Array(_len4), _key4 = 0; _key4 < _len4; _key4++) { args[_key4] = arguments[_key4]; } return fn.apply(this, args); }; }; Expectation.prototype.withContext = deprecate(function (context) { (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).withContext() must be a function'); this.context = context; return this; }, '\nwithContext is deprecated; use a closure instead.\n\n expect(fn).withContext(context).toThrow()\n\nbecomes\n\n expect(() => fn.call(context)).toThrow()\n'); Expectation.prototype.withArgs = deprecate(function () { var _args; (0, _assert2.default)((0, _TestUtils.isFunction)(this.actual), 'The "actual" argument in expect(actual).withArgs() must be a function'); if (arguments.length) this.args = (_args = this.args).concat.apply(_args, arguments); return this; }, '\nwithArgs is deprecated; use a closure instead.\n\n expect(fn).withArgs(a, b, c).toThrow()\n\nbecomes\n\n expect(() => fn(a, b, c)).toThrow()\n'); var aliases = { toBeAn: 'toBeA', toNotBeAn: 'toNotBeA', toBeTruthy: 'toExist', toBeFalsy: 'toNotExist', toBeFewerThan: 'toBeLessThan', toBeMoreThan: 'toBeGreaterThan', toContain: 'toInclude', toNotContain: 'toExclude', toNotInclude: 'toExclude', toContainKeys: 'toIncludeKeys', toNotContainKeys: 'toExcludeKeys', toNotIncludeKeys: 'toExcludeKeys', toContainKey: 'toIncludeKey', toNotContainKey: 'toExcludeKey', toNotIncludeKey: 'toExcludeKey' }; for (var alias in aliases) { if (aliases.hasOwnProperty(alias)) Expectation.prototype[alias] = Expectation.prototype[aliases[alias]]; }exports.default = Expectation; /***/ }, /* 5 */ /***/ function(module, exports, __webpack_require__) { var bind = __webpack_require__(6); module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); /***/ }, /* 6 */ /***/ function(module, exports, __webpack_require__) { var implementation = __webpack_require__(7); module.exports = Function.prototype.bind || implementation; /***/ }, /* 7 */ /***/ function(module, exports) { var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; var slice = Array.prototype.slice; var toStr = Object.prototype.toString; var funcType = '[object Function]'; module.exports = function bind(that) { var target = this; if (typeof target !== 'function' || toStr.call(target) !== funcType) { throw new TypeError(ERROR_MESSAGE + target); } var args = slice.call(arguments, 1); var bound; var binder = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; var boundLength = Math.max(0, target.length - args.length); var boundArgs = []; for (var i = 0; i < boundLength; i++) { boundArgs.push('$' + i); } bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); if (target.prototype) { var Empty = function Empty() {}; Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; /***/ }, /* 8 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(process, Buffer) {'use strict' function isArguments (obj) { return Object.prototype.toString.call(obj) === '[object Arguments]' } module.exports = match function match (obj, pattern) { return match_(obj, pattern, [], []) } /* istanbul ignore next */ var log = (/\btmatch\b/.test(process.env.NODE_DEBUG || '')) ? console.error : function () {} function match_ (obj, pattern, ca, cb) { log('TMATCH', typeof obj, pattern) if (obj == pattern) { log('TMATCH same object or simple value, or problem') // if one is object, and the other isn't, then this is bogus if (obj === null || pattern === null) { return true } else if (typeof obj === 'object' && typeof pattern === 'object') { return true } else if (typeof obj === 'object' && typeof pattern !== 'object') { return false } else if (typeof obj !== 'object' && typeof pattern === 'object') { return false } else { return true } } else if (obj === null || pattern === null) { log('TMATCH null test, already failed ==') return false } else if (typeof obj === 'string' && pattern instanceof RegExp) { log('TMATCH string~=regexp test') return pattern.test(obj) } else if (typeof obj === 'string' && typeof pattern === 'string' && pattern) { log('TMATCH string~=string test') return obj.indexOf(pattern) !== -1 } else if (obj instanceof Date && pattern instanceof Date) { log('TMATCH date test') return obj.getTime() === pattern.getTime() } else if (obj instanceof Date && typeof pattern === 'string') { log('TMATCH date~=string test') return obj.getTime() === new Date(pattern).getTime() } else if (isArguments(obj) || isArguments(pattern)) { log('TMATCH arguments test') var slice = Array.prototype.slice return match_(slice.call(obj), slice.call(pattern), ca, cb) } else if (pattern === Buffer) { log('TMATCH Buffer ctor') return Buffer.isBuffer(obj) } else if (pattern === Function) { log('TMATCH Function ctor') return typeof obj === 'function' } else if (pattern === Number) { log('TMATCH Number ctor (finite, not NaN)') return typeof obj === 'number' && obj === obj && isFinite(obj) } else if (pattern !== pattern) { log('TMATCH NaN') return obj !== obj } else if (pattern === String) { log('TMATCH String ctor') return typeof obj === 'string' } else if (pattern === Boolean) { log('TMATCH Boolean ctor') return typeof obj === 'boolean' } else if (pattern === Array) { log('TMATCH Array ctor', pattern, Array.isArray(obj)) return Array.isArray(obj) } else if (typeof pattern === 'function' && typeof obj === 'object') { log('TMATCH object~=function') return obj instanceof pattern } else if (typeof obj !== 'object' || typeof pattern !== 'object') { log('TMATCH obj is not object, pattern is not object, false') return false } else if (obj instanceof RegExp && pattern instanceof RegExp) { log('TMATCH regexp~=regexp test') return obj.source === pattern.source && obj.global === pattern.global && obj.multiline === pattern.multiline && obj.lastIndex === pattern.lastIndex && obj.ignoreCase === pattern.ignoreCase } else if (Buffer.isBuffer(obj) && Buffer.isBuffer(pattern)) { log('TMATCH buffer test') if (obj.equals) { return obj.equals(pattern) } else { if (obj.length !== pattern.length) return false for (var j = 0; j < obj.length; j++) if (obj[j] != pattern[j]) return false return true } } else { // both are objects. interesting case! log('TMATCH object~=object test') var kobj = Object.keys(obj) var kpat = Object.keys(pattern) log(' TMATCH patternkeys=%j objkeys=%j', kpat, kobj) // don't bother with stack acrobatics if there's nothing there if (kobj.length === 0 && kpat.length === 0) return true // if we've seen this exact pattern and object already, then // it means that pattern and obj have matching cyclicalness // however, non-cyclical patterns can match cyclical objects log(' TMATCH check seen objects...') var cal = ca.length while (cal--) if (ca[cal] === obj && cb[cal] === pattern) return true ca.push(obj); cb.push(pattern) log(' TMATCH not seen previously') var key for (var l = kpat.length - 1; l >= 0; l--) { key = kpat[l] log(' TMATCH test obj[%j]', key, obj[key], pattern[key]) if (!match_(obj[key], pattern[key], ca, cb)) return false } ca.pop() cb.pop() log(' TMATCH object pass') return true } /* istanbul ignore next */ throw new Error('impossible to reach this point') } /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9), __webpack_require__(10).Buffer)) /***/ }, /* 9 */ /***/ function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; /***/ }, /* 10 */ /***/ function(module, exports, __webpack_require__) { /* WEBPACK VAR INJECTION */(function(global) {/*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = __webpack_require__(11) var ieee754 = __webpack_require__(12) var isArray = __webpack_require__(13) exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '<Buffer ' + str + '>' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }()))) /***/ }, /* 11 */ /***/ function(module, exports) { 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return b64.length * 3 / 4 - placeHoldersCount(b64) } function toByteArray (b64) { var i, j, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr(len * 3 / 4 - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0, j = 0; i < l; i += 4, j += 3) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } /***/ }, /* 12 */ /***/ function(module, exports) { exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } /***/ }, /* 13 */ /***/ function(module, exports) { var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; /***/ }, /* 14 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _objectInspect = __webpack_require__(15); var _objectInspect2 = _interopRequireDefault(_objectInspect); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var formatString = function formatString(string, args) { var index = 0; return string.replace(/%s/g, function () { return (0, _objectInspect2.default)(args[index++]); }); }; var assert = function assert(condition, createMessage) { for (var _len = arguments.length, extraArgs = Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { extraArgs[_key - 2] = arguments[_key]; } if (condition) return; var message = typeof createMessage === 'string' ? formatString(createMessage, extraArgs) : createMessage(extraArgs); throw new Error(message); }; exports.default = assert; /***/ }, /* 15 */ /***/ function(module, exports) { var hasMap = typeof Map === 'function' && Map.prototype; var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; var mapForEach = hasMap && Map.prototype.forEach; var hasSet = typeof Set === 'function' && Set.prototype; var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; var setForEach = hasSet && Set.prototype.forEach; var booleanValueOf = Boolean.prototype.valueOf; module.exports = function inspect_ (obj, opts, depth, seen) { if (!opts) opts = {}; var maxDepth = opts.depth === undefined ? 5 : opts.depth; if (depth === undefined) depth = 0; if (depth >= maxDepth && maxDepth > 0 && obj && typeof obj === 'object') { return '[Object]'; } if (seen === undefined) seen = []; else if (indexOf(seen, obj) >= 0) { return '[Circular]'; } function inspect (value, from) { if (from) { seen = seen.slice(); seen.push(from); } return inspect_(value, opts, depth + 1, seen); } if (typeof obj === 'string') { return inspectString(obj); } else if (typeof obj === 'function') { var name = nameOf(obj); return '[Function' + (name ? ': ' + name : '') + ']'; } else if (obj === null) { return 'null'; } else if (isSymbol(obj)) { var symString = Symbol.prototype.toString.call(obj); return typeof obj === 'object' ? 'Object(' + symString + ')' : symString; } else if (isElement(obj)) { var s = '<' + String(obj.nodeName).toLowerCase(); var attrs = obj.attributes || []; for (var i = 0; i < attrs.length; i++) { s += ' ' + attrs[i].name + '="' + quote(attrs[i].value) + '"'; } s += '>'; if (obj.childNodes && obj.childNodes.length) s += '...'; s += '</' + String(obj.nodeName).toLowerCase() + '>'; return s; } else if (isArray(obj)) { if (obj.length === 0) return '[]'; var xs = Array(obj.length); for (var i = 0; i < obj.length; i++) { xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; } return '[ ' + xs.join(', ') + ' ]'; } else if (isError(obj)) { var parts = []; for (var key in obj) { if (!has(obj, key)) continue; if (/[^\w$]/.test(key)) { parts.push(inspect(key) + ': ' + inspect(obj[key])); } else { parts.push(key + ': ' + inspect(obj[key])); } } if (parts.length === 0) return '[' + obj + ']'; return '{ [' + obj + '] ' + parts.join(', ') + ' }'; } else if (typeof obj === 'object' && typeof obj.inspect === 'function') { return obj.inspect(); } else if (isMap(obj)) { var parts = []; mapForEach.call(obj, function (value, key) { parts.push(inspect(key, obj) + ' => ' + inspect(value, obj)); }); return 'Map (' + mapSize.call(obj) + ') {' + parts.join(', ') + '}'; } else if (isSet(obj)) { var parts = []; setForEach.call(obj, function (value ) { parts.push(inspect(value, obj)); }); return 'Set (' + setSize.call(obj) + ') {' + parts.join(', ') + '}'; } else if (typeof obj !== 'object') { return String(obj); } else if (isNumber(obj)) { return 'Object(' + Number(obj) + ')'; } else if (isBoolean(obj)) { return 'Object(' + booleanValueOf.call(obj) + ')'; } else if (isString(obj)) { return 'Object(' + inspect(String(obj)) + ')'; } else if (!isDate(obj) && !isRegExp(obj)) { var xs = [], keys = []; for (var key in obj) { if (has(obj, key)) keys.push(key); } keys.sort(); for (var i = 0; i < keys.length; i++) { var key = keys[i]; if (/[^\w$]/.test(key)) { xs.push(inspect(key) + ': ' + inspect(obj[key], obj)); } else xs.push(key + ': ' + inspect(obj[key], obj)); } if (xs.length === 0) return '{}'; return '{ ' + xs.join(', ') + ' }'; } else return String(obj); }; function quote (s) { return String(s).replace(/"/g, '&quot;'); } function isArray (obj) { return toStr(obj) === '[object Array]' } function isDate (obj) { return toStr(obj) === '[object Date]' } function isRegExp (obj) { return toStr(obj) === '[object RegExp]' } function isError (obj) { return toStr(obj) === '[object Error]' } function isSymbol (obj) { return toStr(obj) === '[object Symbol]' } function isString (obj) { return toStr(obj) === '[object String]' } function isNumber (obj) { return toStr(obj) === '[object Number]' } function isBoolean (obj) { return toStr(obj) === '[object Boolean]' } var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; function has (obj, key) { return hasOwn.call(obj, key); } function toStr (obj) { return Object.prototype.toString.call(obj); } function nameOf (f) { if (f.name) return f.name; var m = f.toString().match(/^function\s*([\w$]+)/); if (m) return m[1]; } function indexOf (xs, x) { if (xs.indexOf) return xs.indexOf(x); for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } function isMap (x) { if (!mapSize) { return false; } try { mapSize.call(x); return true; } catch (e) {} return false; } function isSet (x) { if (!setSize) { return false; } try { setSize.call(x); return true; } catch (e) {} return false; } function isElement (x) { if (!x || typeof x !== 'object') return false; if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { return true; } return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function' ; } function inspectString (str) { var s = str.replace(/(['\\])/g, '\\$1').replace(/[\x00-\x1f]/g, lowbyte); return "'" + s + "'"; function lowbyte (c) { var n = c.charCodeAt(0); var x = { 8: 'b', 9: 't', 10: 'n', 12: 'f', 13: 'r' }[n]; if (x) return '\\' + x; return '\\x' + (n < 0x10 ? '0' : '') + n.toString(16); } } /***/ }, /* 16 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.spyOn = exports.createSpy = exports.restoreSpies = exports.isSpy = undefined; var _defineProperties = __webpack_require__(17); var _assert = __webpack_require__(14); var _assert2 = _interopRequireDefault(_assert); var _TestUtils = __webpack_require__(21); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } } /*eslint-disable prefer-rest-params, no-underscore-dangle*/ var noop = function noop() {}; var supportsConfigurableFnLength = _defineProperties.supportsDescriptors && Object.getOwnPropertyDescriptor(function () {}, 'length').configurable; var isSpy = exports.isSpy = function isSpy(object) { return object && object.__isSpy === true; }; var spies = []; var restoreSpies = exports.restoreSpies = function restoreSpies() { for (var i = spies.length - 1; i >= 0; i--) { spies[i].restore(); }spies = []; }; var createSpy = exports.createSpy = function createSpy(fn) { var restore = arguments.length <= 1 || arguments[1] === undefined ? noop : arguments[1]; if (fn == null) fn = noop; (0, _assert2.default)((0, _TestUtils.isFunction)(fn), 'createSpy needs a function'); var targetFn = void 0, thrownValue = void 0, returnValue = void 0, spy = void 0; function spyLogic() { spy.calls.push({ context: this, arguments: Array.prototype.slice.call(arguments, 0) }); if (targetFn) return targetFn.apply(this, arguments); if (thrownValue) throw thrownValue; return returnValue; } if (supportsConfigurableFnLength) { spy = Object.defineProperty(spyLogic, 'length', { value: fn.length, writable: false, enumerable: false, configurable: true }); } else { spy = new Function('spy', 'return function(' + // eslint-disable-line no-new-func [].concat(_toConsumableArray(Array(fn.length))).map(function (_, i) { return '_' + i; }).join(',') + ') {\n return spy.apply(this, arguments)\n }')(spyLogic); } spy.calls = []; spy.andCall = function (otherFn) { targetFn = otherFn; return spy; }; spy.andCallThrough = function () { return spy.andCall(fn); }; spy.andThrow = function (value) { thrownValue = value; return spy; }; spy.andReturn = function (value) { returnValue = value; return spy; }; spy.getLastCall = function () { return spy.calls[spy.calls.length - 1]; }; spy.reset = function () { spy.calls = []; }; spy.restore = spy.destroy = restore; spy.__isSpy = true; spies.push(spy); return spy; }; var spyOn = exports.spyOn = function spyOn(object, methodName) { var original = object[methodName]; if (!isSpy(original)) { (0, _assert2.default)((0, _TestUtils.isFunction)(original), 'Cannot spyOn the %s property; it is not a function', methodName); object[methodName] = createSpy(original, function () { object[methodName] = original; }); } return object[methodName]; }; /***/ }, /* 17 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var keys = __webpack_require__(18); var foreach = __webpack_require__(20); var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; var toStr = Object.prototype.toString; var isFunction = function (fn) { return typeof fn === 'function' && toStr.call(fn) === '[object Function]'; }; var arePropertyDescriptorsSupported = function () { var obj = {}; try { Object.defineProperty(obj, 'x', { enumerable: false, value: obj }); /* eslint-disable no-unused-vars, no-restricted-syntax */ for (var _ in obj) { return false; } /* eslint-enable no-unused-vars, no-restricted-syntax */ return obj.x === obj; } catch (e) { /* this is IE 8. */ return false; } }; var supportsDescriptors = Object.defineProperty && arePropertyDescriptorsSupported(); var defineProperty = function (object, name, value, predicate) { if (name in object && (!isFunction(predicate) || !predicate())) { return; } if (supportsDescriptors) { Object.defineProperty(object, name, { configurable: true, enumerable: false, value: value, writable: true }); } else { object[name] = value; } }; var defineProperties = function (object, map) { var predicates = arguments.length > 2 ? arguments[2] : {}; var props = keys(map); if (hasSymbols) { props = props.concat(Object.getOwnPropertySymbols(map)); } foreach(props, function (name) { defineProperty(object, name, map[name], predicates[name]); }); }; defineProperties.supportsDescriptors = !!supportsDescriptors; module.exports = defineProperties; /***/ }, /* 18 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; // modified from https://github.com/es-shims/es5-shim var has = Object.prototype.hasOwnProperty; var toStr = Object.prototype.toString; var slice = Array.prototype.slice; var isArgs = __webpack_require__(19); var isEnumerable = Object.prototype.propertyIsEnumerable; var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString'); var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype'); var dontEnums = [ 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty', 'isPrototypeOf', 'propertyIsEnumerable', 'constructor' ]; var equalsConstructorPrototype = function (o) { var ctor = o.constructor; return ctor && ctor.prototype === o; }; var excludedKeys = { $console: true, $external: true, $frame: true, $frameElement: true, $frames: true, $innerHeight: true, $innerWidth: true, $outerHeight: true, $outerWidth: true, $pageXOffset: true, $pageYOffset: true, $parent: true, $scrollLeft: true, $scrollTop: true, $scrollX: true, $scrollY: true, $self: true, $webkitIndexedDB: true, $webkitStorageInfo: true, $window: true }; var hasAutomationEqualityBug = (function () { /* global window */ if (typeof window === 'undefined') { return false; } for (var k in window) { try { if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') { try { equalsConstructorPrototype(window[k]); } catch (e) { return true; } } } catch (e) { return true; } } return false; }()); var equalsConstructorPrototypeIfNotBuggy = function (o) { /* global window */ if (typeof window === 'undefined' || !hasAutomationEqualityBug) { return equalsConstructorPrototype(o); } try { return equalsConstructorPrototype(o); } catch (e) { return false; } }; var keysShim = function keys(object) { var isObject = object !== null && typeof object === 'object'; var isFunction = toStr.call(object) === '[object Function]'; var isArguments = isArgs(object); var isString = isObject && toStr.call(object) === '[object String]'; var theKeys = []; if (!isObject && !isFunction && !isArguments) { throw new TypeError('Object.keys called on a non-object'); } var skipProto = hasProtoEnumBug && isFunction; if (isString && object.length > 0 && !has.call(object, 0)) { for (var i = 0; i < object.length; ++i) { theKeys.push(String(i)); } } if (isArguments && object.length > 0) { for (var j = 0; j < object.length; ++j) { theKeys.push(String(j)); } } else { for (var name in object) { if (!(skipProto && name === 'prototype') && has.call(object, name)) { theKeys.push(String(name)); } } } if (hasDontEnumBug) { var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object); for (var k = 0; k < dontEnums.length; ++k) { if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) { theKeys.push(dontEnums[k]); } } } return theKeys; }; keysShim.shim = function shimObjectKeys() { if (Object.keys) { var keysWorksWithArguments = (function () { // Safari 5.0 bug return (Object.keys(arguments) || '').length === 2; }(1, 2)); if (!keysWorksWithArguments) { var originalKeys = Object.keys; Object.keys = function keys(object) { if (isArgs(object)) { return originalKeys(slice.call(object)); } else { return originalKeys(object); } }; } } else { Object.keys = keysShim; } return Object.keys || keysShim; }; module.exports = keysShim; /***/ }, /* 19 */ /***/ function(module, exports) { 'use strict'; var toStr = Object.prototype.toString; module.exports = function isArguments(value) { var str = toStr.call(value); var isArgs = str === '[object Arguments]'; if (!isArgs) { isArgs = str !== '[object Array]' && value !== null && typeof value === 'object' && typeof value.length === 'number' && value.length >= 0 && toStr.call(value.callee) === '[object Function]'; } return isArgs; }; /***/ }, /* 20 */ /***/ function(module, exports) { var hasOwn = Object.prototype.hasOwnProperty; var toString = Object.prototype.toString; module.exports = function forEach (obj, fn, ctx) { if (toString.call(fn) !== '[object Function]') { throw new TypeError('iterator must be a function'); } var l = obj.length; if (l === +l) { for (var i = 0; i < l; i++) { fn.call(ctx, obj[i], i, obj); } } else { for (var k in obj) { if (hasOwn.call(obj, k)) { fn.call(ctx, obj[k], k, obj); } } } }; /***/ }, /* 21 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.stringContains = exports.objectContains = exports.arrayContains = exports.functionThrows = exports.isA = exports.isObject = exports.isArray = exports.isFunction = exports.isEqual = exports.whyNotEqual = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; var _isRegex = __webpack_require__(22); var _isRegex2 = _interopRequireDefault(_isRegex); var _why = __webpack_require__(23); var _why2 = _interopRequireDefault(_why); var _objectKeys = __webpack_require__(18); var _objectKeys2 = _interopRequireDefault(_objectKeys); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Returns the reason why the given arguments are not *conceptually* * equal, if any; the empty string otherwise. */ var whyNotEqual = exports.whyNotEqual = function whyNotEqual(a, b) { return a == b ? '' : (0, _why2.default)(a, b); }; /** * Returns true if the given arguments are *conceptually* equal. */ var isEqual = exports.isEqual = function isEqual(a, b) { return whyNotEqual(a, b) === ''; }; /** * Returns true if the given object is a function. */ var isFunction = exports.isFunction = function isFunction(object) { return typeof object === 'function'; }; /** * Returns true if the given object is an array. */ var isArray = exports.isArray = function isArray(object) { return Array.isArray(object); }; /** * Returns true if the given object is an object. */ var isObject = exports.isObject = function isObject(object) { return object && !isArray(object) && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object'; }; /** * Returns true if the given object is an instanceof value * or its typeof is the given value. */ var isA = exports.isA = function isA(object, value) { if (isFunction(value)) return object instanceof value; if (value === 'array') return Array.isArray(object); return (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === value; }; /** * Returns true if the given function throws the given value * when invoked. The value may be: * * - undefined, to merely assert there was a throw * - a constructor function, for comparing using instanceof * - a regular expression, to compare with the error message * - a string, to find in the error message */ var functionThrows = exports.functionThrows = function functionThrows(fn, context, args, value) { try { fn.apply(context, args); } catch (error) { if (value == null) return true; if (isFunction(value) && error instanceof value) return true; var message = error.message || error; if (typeof message === 'string') { if ((0, _isRegex2.default)(value) && value.test(error.message)) return true; if (typeof value === 'string' && message.indexOf(value) !== -1) return true; } } return false; }; /** * Returns true if the given array contains the value, false * otherwise. The compareValues function must return false to * indicate a non-match. */ var arrayContains = exports.arrayContains = function arrayContains(array, value, compareValues) { return array.some(function (item) { return compareValues(item, value) !== false; }); }; var ownEnumerableKeys = function ownEnumerableKeys(object) { if ((typeof Reflect === 'undefined' ? 'undefined' : _typeof(Reflect)) === 'object' && typeof Reflect.ownKeys === 'function') { return Reflect.ownKeys(object).filter(function (key) { return Object.getOwnPropertyDescriptor(object, key).enumerable; }); } if (typeof Object.getOwnPropertySymbols === 'function') { return Object.getOwnPropertySymbols(object).filter(function (key) { return Object.getOwnPropertyDescriptor(object, key).enumerable; }).concat((0, _objectKeys2.default)(object)); } return (0, _objectKeys2.default)(object); }; /** * Returns true if the given object contains the value, false * otherwise. The compareValues function must return false to * indicate a non-match. */ var objectContains = exports.objectContains = function objectContains(object, value, compareValues) { return ownEnumerableKeys(value).every(function (k) { if (isObject(object[k]) && isObject(value[k])) return objectContains(object[k], value[k], compareValues); return compareValues(object[k], value[k]); }); }; /** * Returns true if the given string contains the value, false otherwise. */ var stringContains = exports.stringContains = function stringContains(string, value) { return string.indexOf(value) !== -1; }; /***/ }, /* 22 */ /***/ function(module, exports) { 'use strict'; var regexExec = RegExp.prototype.exec; var tryRegexExec = function tryRegexExec(value) { try { regexExec.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var regexClass = '[object RegExp]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isRegex(value) { if (typeof value !== 'object') { return false; } return hasToStringTag ? tryRegexExec(value) : toStr.call(value) === regexClass; }; /***/ }, /* 23 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var ObjectPrototype = Object.prototype; var toStr = ObjectPrototype.toString; var booleanValue = Boolean.prototype.valueOf; var has = __webpack_require__(5); var isArrowFunction = __webpack_require__(24); var isBoolean = __webpack_require__(26); var isDate = __webpack_require__(27); var isGenerator = __webpack_require__(28); var isNumber = __webpack_require__(29); var isRegex = __webpack_require__(22); var isString = __webpack_require__(30); var isSymbol = __webpack_require__(31); var isCallable = __webpack_require__(25); var isProto = Object.prototype.isPrototypeOf; var foo = function foo() {}; var functionsHaveNames = foo.name === 'foo'; var symbolValue = typeof Symbol === 'function' ? Symbol.prototype.valueOf : null; var symbolIterator = __webpack_require__(32)(); var collectionsForEach = __webpack_require__(33)(); var getPrototypeOf = Object.getPrototypeOf; if (!getPrototypeOf) { /* eslint-disable no-proto */ if (typeof 'test'.__proto__ === 'object') { getPrototypeOf = function (obj) { return obj.__proto__; }; } else { getPrototypeOf = function (obj) { var constructor = obj.constructor, oldConstructor; if (has(obj, 'constructor')) { oldConstructor = constructor; if (!(delete obj.constructor)) { // reset constructor return null; // can't delete obj.constructor, return null } constructor = obj.constructor; // get real constructor obj.constructor = oldConstructor; // restore constructor } return constructor ? constructor.prototype : ObjectPrototype; // needed for IE }; } /* eslint-enable no-proto */ } var isArray = Array.isArray || function (value) { return toStr.call(value) === '[object Array]'; }; var normalizeFnWhitespace = function normalizeFnWhitespace(fnStr) { // this is needed in IE 9, at least, which has inconsistencies here. return fnStr.replace(/^function ?\(/, 'function (').replace('){', ') {'); }; var tryMapSetEntries = function tryMapSetEntries(collection) { var foundEntries = []; try { collectionsForEach.Map.call(collection, function (key, value) { foundEntries.push([key, value]); }); } catch (notMap) { try { collectionsForEach.Set.call(collection, function (value) { foundEntries.push([value]); }); } catch (notSet) { return false; } } return foundEntries; }; module.exports = function whyNotEqual(value, other) { if (value === other) { return ''; } if (value == null || other == null) { return value === other ? '' : String(value) + ' !== ' + String(other); } var valToStr = toStr.call(value); var otherToStr = toStr.call(other); if (valToStr !== otherToStr) { return 'toStringTag is not the same: ' + valToStr + ' !== ' + otherToStr; } var valIsBool = isBoolean(value); var otherIsBool = isBoolean(other); if (valIsBool || otherIsBool) { if (!valIsBool) { return 'first argument is not a boolean; second argument is'; } if (!otherIsBool) { return 'second argument is not a boolean; first argument is'; } var valBoolVal = booleanValue.call(value); var otherBoolVal = booleanValue.call(other); if (valBoolVal === otherBoolVal) { return ''; } return 'primitive value of boolean arguments do not match: ' + valBoolVal + ' !== ' + otherBoolVal; } var valIsNumber = isNumber(value); var otherIsNumber = isNumber(value); if (valIsNumber || otherIsNumber) { if (!valIsNumber) { return 'first argument is not a number; second argument is'; } if (!otherIsNumber) { return 'second argument is not a number; first argument is'; } var valNum = Number(value); var otherNum = Number(other); if (valNum === otherNum) { return ''; } var valIsNaN = isNaN(value); var otherIsNaN = isNaN(other); if (valIsNaN && !otherIsNaN) { return 'first argument is NaN; second is not'; } else if (!valIsNaN && otherIsNaN) { return 'second argument is NaN; first is not'; } else if (valIsNaN && otherIsNaN) { return ''; } return 'numbers are different: ' + value + ' !== ' + other; } var valIsString = isString(value); var otherIsString = isString(other); if (valIsString || otherIsString) { if (!valIsString) { return 'second argument is string; first is not'; } if (!otherIsString) { return 'first argument is string; second is not'; } var stringVal = String(value); var otherVal = String(other); if (stringVal === otherVal) { return ''; } return 'string values are different: "' + stringVal + '" !== "' + otherVal + '"'; } var valIsDate = isDate(value); var otherIsDate = isDate(other); if (valIsDate || otherIsDate) { if (!valIsDate) { return 'second argument is Date, first is not'; } if (!otherIsDate) { return 'first argument is Date, second is not'; } var valTime = +value; var otherTime = +other; if (valTime === otherTime) { return ''; } return 'Dates have different time values: ' + valTime + ' !== ' + otherTime; } var valIsRegex = isRegex(value); var otherIsRegex = isRegex(other); if (valIsRegex || otherIsRegex) { if (!valIsRegex) { return 'second argument is RegExp, first is not'; } if (!otherIsRegex) { return 'first argument is RegExp, second is not'; } var regexStringVal = String(value); var regexStringOther = String(other); if (regexStringVal === regexStringOther) { return ''; } return 'regular expressions differ: ' + regexStringVal + ' !== ' + regexStringOther; } var valIsArray = isArray(value); var otherIsArray = isArray(other); if (valIsArray || otherIsArray) { if (!valIsArray) { return 'second argument is an Array, first is not'; } if (!otherIsArray) { return 'first argument is an Array, second is not'; } if (value.length !== other.length) { return 'arrays have different length: ' + value.length + ' !== ' + other.length; } if (String(value) !== String(other)) { return 'stringified Arrays differ'; } var index = value.length - 1; var equal = ''; var valHasIndex, otherHasIndex; while (equal === '' && index >= 0) { valHasIndex = has(value, index); otherHasIndex = has(other, index); if (!valHasIndex && otherHasIndex) { return 'second argument has index ' + index + '; first does not'; } if (valHasIndex && !otherHasIndex) { return 'first argument has index ' + index + '; second does not'; } equal = whyNotEqual(value[index], other[index]); index -= 1; } return equal; } var valueIsSym = isSymbol(value); var otherIsSym = isSymbol(other); if (valueIsSym !== otherIsSym) { if (valueIsSym) { return 'first argument is Symbol; second is not'; } return 'second argument is Symbol; first is not'; } if (valueIsSym && otherIsSym) { return symbolValue.call(value) === symbolValue.call(other) ? '' : 'first Symbol value !== second Symbol value'; } var valueIsGen = isGenerator(value); var otherIsGen = isGenerator(other); if (valueIsGen !== otherIsGen) { if (valueIsGen) { return 'first argument is a Generator; second is not'; } return 'second argument is a Generator; first is not'; } var valueIsArrow = isArrowFunction(value); var otherIsArrow = isArrowFunction(other); if (valueIsArrow !== otherIsArrow) { if (valueIsArrow) { return 'first argument is an Arrow function; second is not'; } return 'second argument is an Arrow function; first is not'; } if (isCallable(value) || isCallable(other)) { if (functionsHaveNames && whyNotEqual(value.name, other.name) !== '') { return 'Function names differ: "' + value.name + '" !== "' + other.name + '"'; } if (whyNotEqual(value.length, other.length) !== '') { return 'Function lengths differ: ' + value.length + ' !== ' + other.length; } var valueStr = normalizeFnWhitespace(String(value)); var otherStr = normalizeFnWhitespace(String(other)); if (whyNotEqual(valueStr, otherStr) === '') { return ''; } if (!valueIsGen && !valueIsArrow) { return whyNotEqual(valueStr.replace(/\)\s*\{/, '){'), otherStr.replace(/\)\s*\{/, '){')) === '' ? '' : 'Function string representations differ'; } return whyNotEqual(valueStr, otherStr) === '' ? '' : 'Function string representations differ'; } if (typeof value === 'object' || typeof other === 'object') { if (typeof value !== typeof other) { return 'arguments have a different typeof: ' + typeof value + ' !== ' + typeof other; } if (isProto.call(value, other)) { return 'first argument is the [[Prototype]] of the second'; } if (isProto.call(other, value)) { return 'second argument is the [[Prototype]] of the first'; } if (getPrototypeOf(value) !== getPrototypeOf(other)) { return 'arguments have a different [[Prototype]]'; } if (symbolIterator) { var valueIteratorFn = value[symbolIterator]; var valueIsIterable = isCallable(valueIteratorFn); var otherIteratorFn = other[symbolIterator]; var otherIsIterable = isCallable(otherIteratorFn); if (valueIsIterable !== otherIsIterable) { if (valueIsIterable) { return 'first argument is iterable; second is not'; } return 'second argument is iterable; first is not'; } if (valueIsIterable && otherIsIterable) { var valueIterator = valueIteratorFn.call(value); var otherIterator = otherIteratorFn.call(other); var valueNext, otherNext, nextWhy; do { valueNext = valueIterator.next(); otherNext = otherIterator.next(); if (!valueNext.done && !otherNext.done) { nextWhy = whyNotEqual(valueNext, otherNext); if (nextWhy !== '') { return 'iteration results are not equal: ' + nextWhy; } } } while (!valueNext.done && !otherNext.done); if (valueNext.done && !otherNext.done) { return 'first argument finished iterating before second'; } if (!valueNext.done && otherNext.done) { return 'second argument finished iterating before first'; } return ''; } } else if (collectionsForEach.Map || collectionsForEach.Set) { var valueEntries = tryMapSetEntries(value); var otherEntries = tryMapSetEntries(other); var valueEntriesIsArray = isArray(valueEntries); var otherEntriesIsArray = isArray(otherEntries); if (valueEntriesIsArray && !otherEntriesIsArray) { return 'first argument has Collection entries, second does not'; } if (!valueEntriesIsArray && otherEntriesIsArray) { return 'second argument has Collection entries, first does not'; } if (valueEntriesIsArray && otherEntriesIsArray) { var entriesWhy = whyNotEqual(valueEntries, otherEntries); return entriesWhy === '' ? '' : 'Collection entries differ: ' + entriesWhy; } } var key, valueKeyIsRecursive, otherKeyIsRecursive, keyWhy; for (key in value) { if (has(value, key)) { if (!has(other, key)) { return 'first argument has key "' + key + '"; second does not'; } valueKeyIsRecursive = !!value[key] && value[key][key] === value; otherKeyIsRecursive = !!other[key] && other[key][key] === other; if (valueKeyIsRecursive !== otherKeyIsRecursive) { if (valueKeyIsRecursive) { return 'first argument has a circular reference at key "' + key + '"; second does not'; } return 'second argument has a circular reference at key "' + key + '"; first does not'; } if (!valueKeyIsRecursive && !otherKeyIsRecursive) { keyWhy = whyNotEqual(value[key], other[key]); if (keyWhy !== '') { return 'value at key "' + key + '" differs: ' + keyWhy; } } } } for (key in other) { if (has(other, key) && !has(value, key)) { return 'second argument has key "' + key + '"; first does not'; } } return ''; } return false; }; /***/ }, /* 24 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isCallable = __webpack_require__(25); var fnToStr = Function.prototype.toString; var isNonArrowFnRegex = /^\s*function/; var isArrowFnWithParensRegex = /^\([^\)]*\) *=>/; var isArrowFnWithoutParensRegex = /^[^=]*=>/; module.exports = function isArrowFunction(fn) { if (!isCallable(fn)) { return false; } var fnStr = fnToStr.call(fn); return fnStr.length > 0 && !isNonArrowFnRegex.test(fnStr) && (isArrowFnWithParensRegex.test(fnStr) || isArrowFnWithoutParensRegex.test(fnStr)); }; /***/ }, /* 25 */ /***/ function(module, exports) { 'use strict'; var fnToStr = Function.prototype.toString; var constructorRegex = /^\s*class /; var isES6ClassFn = function isES6ClassFn(value) { try { var fnStr = fnToStr.call(value); var singleStripped = fnStr.replace(/\/\/.*\n/g, ''); var multiStripped = singleStripped.replace(/\/\*[.\s\S]*\*\//g, ''); var spaceStripped = multiStripped.replace(/\n/mg, ' ').replace(/ {2}/g, ' '); return constructorRegex.test(spaceStripped); } catch (e) { return false; // not a function } }; var tryFunctionObject = function tryFunctionObject(value) { try { if (isES6ClassFn(value)) { return false; } fnToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var fnClass = '[object Function]'; var genClass = '[object GeneratorFunction]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isCallable(value) { if (!value) { return false; } if (typeof value !== 'function' && typeof value !== 'object') { return false; } if (hasToStringTag) { return tryFunctionObject(value); } if (isES6ClassFn(value)) { return false; } var strClass = toStr.call(value); return strClass === fnClass || strClass === genClass; }; /***/ }, /* 26 */ /***/ function(module, exports) { 'use strict'; var boolToStr = Boolean.prototype.toString; var tryBooleanObject = function tryBooleanObject(value) { try { boolToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var boolClass = '[object Boolean]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isBoolean(value) { if (typeof value === 'boolean') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryBooleanObject(value) : toStr.call(value) === boolClass; }; /***/ }, /* 27 */ /***/ function(module, exports) { 'use strict'; var getDay = Date.prototype.getDay; var tryDateObject = function tryDateObject(value) { try { getDay.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var dateClass = '[object Date]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isDateObject(value) { if (typeof value !== 'object' || value === null) { return false; } return hasToStringTag ? tryDateObject(value) : toStr.call(value) === dateClass; }; /***/ }, /* 28 */ /***/ function(module, exports) { 'use strict'; var toStr = Object.prototype.toString; var fnToStr = Function.prototype.toString; var isFnRegex = /^\s*(?:function)?\*/; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; var getProto = Object.getPrototypeOf; var getGeneratorFunc = function () { // eslint-disable-line consistent-return if (!hasToStringTag) { return false; } try { return Function('return function*() {}')(); } catch (e) { } }; var generatorFunc = getGeneratorFunc(); var GeneratorFunction = generatorFunc ? getProto(generatorFunc) : {}; module.exports = function isGeneratorFunction(fn) { if (typeof fn !== 'function') { return false; } if (isFnRegex.test(fnToStr.call(fn))) { return true; } if (!hasToStringTag) { var str = toStr.call(fn); return str === '[object GeneratorFunction]'; } return getProto(fn) === GeneratorFunction; }; /***/ }, /* 29 */ /***/ function(module, exports) { 'use strict'; var numToStr = Number.prototype.toString; var tryNumberObject = function tryNumberObject(value) { try { numToStr.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var numClass = '[object Number]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isNumberObject(value) { if (typeof value === 'number') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryNumberObject(value) : toStr.call(value) === numClass; }; /***/ }, /* 30 */ /***/ function(module, exports) { 'use strict'; var strValue = String.prototype.valueOf; var tryStringObject = function tryStringObject(value) { try { strValue.call(value); return true; } catch (e) { return false; } }; var toStr = Object.prototype.toString; var strClass = '[object String]'; var hasToStringTag = typeof Symbol === 'function' && typeof Symbol.toStringTag === 'symbol'; module.exports = function isString(value) { if (typeof value === 'string') { return true; } if (typeof value !== 'object') { return false; } return hasToStringTag ? tryStringObject(value) : toStr.call(value) === strClass; }; /***/ }, /* 31 */ /***/ function(module, exports) { 'use strict'; var toStr = Object.prototype.toString; var hasSymbols = typeof Symbol === 'function' && typeof Symbol() === 'symbol'; if (hasSymbols) { var symToStr = Symbol.prototype.toString; var symStringRegex = /^Symbol\(.*\)$/; var isSymbolObject = function isSymbolObject(value) { if (typeof value.valueOf() !== 'symbol') { return false; } return symStringRegex.test(symToStr.call(value)); }; module.exports = function isSymbol(value) { if (typeof value === 'symbol') { return true; } if (toStr.call(value) !== '[object Symbol]') { return false; } try { return isSymbolObject(value); } catch (e) { return false; } }; } else { module.exports = function isSymbol(value) { // this environment does not support Symbols. return false; }; } /***/ }, /* 32 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; var isSymbol = __webpack_require__(31); module.exports = function getSymbolIterator() { var symbolIterator = typeof Symbol === 'function' && isSymbol(Symbol.iterator) ? Symbol.iterator : null; if (typeof Object.getOwnPropertyNames === 'function' && typeof Map === 'function' && typeof Map.prototype.entries === 'function') { Object.getOwnPropertyNames(Map.prototype).forEach(function (name) { if (name !== 'entries' && name !== 'size' && Map.prototype[name] === Map.prototype.entries) { symbolIterator = name; } }); } return symbolIterator; }; /***/ }, /* 33 */ /***/ function(module, exports) { 'use strict'; module.exports = function () { var mapForEach = (function () { if (typeof Map !== 'function') { return null; } try { Map.prototype.forEach.call({}, function () {}); } catch (e) { return Map.prototype.forEach; } return null; }()); var setForEach = (function () { if (typeof Set !== 'function') { return null; } try { Set.prototype.forEach.call({}, function () {}); } catch (e) { return Set.prototype.forEach; } return null; }()); return { Map: mapForEach, Set: setForEach }; }; /***/ }, /* 34 */ /***/ function(module, exports, __webpack_require__) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _Expectation = __webpack_require__(4); var _Expectation2 = _interopRequireDefault(_Expectation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var Extensions = []; function extend(extension) { if (Extensions.indexOf(extension) === -1) { Extensions.push(extension); for (var p in extension) { if (extension.hasOwnProperty(p)) _Expectation2.default.prototype[p] = extension[p]; } } } exports.default = extend; /***/ } /******/ ]); //# sourceMappingURL=test.js.map
mit
hydrogen-music/hydrogen-music
feeds/drumkit_list.php
20357
<?xml version='1.0' encoding='UTF-8'?><drumkit_list> <drumkit> <name>Audiophob</name> <url>http://hydro.smoors.de/Audiophob.h2drumkit</url> <info>Cheap sounds from freesound.org with no copyright</info> <author>soundcloud.com/audiophobdubstep</author> <license>This work is licensed under the Creative Commons 0 License.</license> </drumkit> <drumkit> <name>belofilms.com - AC-Guitar-Strums (flac)</name> <url>http://hydro.smoors.de/belofilms_GuitarStrums.h2drumkit</url> <info> &lt;!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> &lt;html>&lt;head>&lt;meta name="qrichtext" content="1" />&lt;style type="text/css"> p, li { white-space: pre-wrap; } &lt;/style>&lt;/head>&lt;body style=" font-family:'Lucida Grande'; font-size:10pt; font-weight:400; font-style:normal;"> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Part of &amp;quot;the one man movie proyect&amp;quot;, please visit www.belofilms.com for more info.&lt;/p> &lt;p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Made with my own samples, 4 layers - 96khz - 24bit - Stereo&lt;/p> &lt;p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">*Feel free to use it for commercial music, as long as you give the proper noticeable credit: Gabriel Verdugo Soto (www.belofilms.com)&lt;/p> &lt;p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">******* Please read the drumkit guidelines up and below *******&lt;/p> &lt;p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Order example: Gminor / F2&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">Gminor: Chord name.&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">/: Slide up (/), down (\) or no slide ().&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">F2: Major key and position inside that scale.&lt;/p> &lt;p style="-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">&lt;/p> &lt;p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">**If you want to have scales different than C you have to rearranged the order of the instruments according to the major keys information available in each instrument.&lt;/p>&lt;/body>&lt;/html></info> <author>Gabriel Verdugo Soto (belo@belofilms.com)</author> <license>CC-BY 3.0 Unported</license> </drumkit> <drumkit> <name>BJA_Pacific</name> <url>http://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/BJA_Pacific.h2drumkit</url> <info>Multi-layered drumkit, based on samples from Bransin Anderson </info> <author>Luc Tunguay</author> <license>Attribution-Share Alike 3.0 United States</license> </drumkit> <drumkit> <name>JazzFunkKit</name> <info> Low Kick 20x14 Gretsch - Aquarian modern vintage on both sides; felt strips on both sides. Medium DW felt beater. Kick 15x15 Ludwig - 30's era mahogany marching snare with its original calf-skin head on the resonant side; Remo pin stripe on the batter side. Medium DW felt beater. Snare 14x5.5 Ludwig - 20's era (rare; with no badge) chrome over brass 8-lug. Fiberskyn Ambassador head on top; Diplomat snare-side bottom. Rack Tom 12x8 Gretsch - 6-ply maple/gum satin pink flame wrap; stop-sign badge. Fiberskyn Diplomat head on top; clear Diplomat head on bottom. Floor Tom 14x14 Gretsch - Coated ambassador head on top; Aquarian Classic Clear on bottom. Hi-hat Top: 13.75'' K. Zildjian - Istanbul 60's era. Bottom: 14'' A. Zildjian - Istanbul 70's era top hat used as a bottom hat. Ride 1 22'' Istanbul Agop - Jazz ride special edition TW prototype. Ride 2 21'' Bosphorus - Flat ride Master's series. WAV samples, Kontakt and SFZ format available at: www.orangetreesamples.com/blog/free-jazz-funk-drum-sample-library Hydrogen drumkit format by Oddtime. License Agreement: Orange Tree Samples produced all of these sounds and retains all rights to these sounds. You may use the samples included for commercial or non-commercial music productions. You do not need to credit Orange Tree Samples. This license to use the sounds granted to the original purchaser of the sounds and is not transferable without the consent of Orange Tree Samples. You may not create any other sample-based product that uses sounds from Orange Tree Samples. This includes making other sample libraries that use Orange Tree Samples sounds as source material. You may not copy, edit, distribute or sell the original soundsets without the written permission of Orange Tree Samples. The software is provided to the user "as is". Orange Tree Samples makes no warranties, either express or implied, with respect to the software and associated materials provided to the user, including but not limited to any warranty of fitness for a particular purpose. Orange Tree Samples does not warrant that the functions contained in the software will meet your requirements, or that the operation of the software will be uninterrupted or error-free, or that defects in the software will be corrected. Orange Tree Samples does not warrant or make any representations regarding the use or the results of the use of the software or any documentation provided therewith in terms of their correctness, accuracy, reliability, or otherwise. No information or advice given by Orange Tree Samples shall create a warranty or in any way increase the scope of this warranty. Orange Tree Samples is not liable for any claims or damages whatsoever, including property damage, personal injury, intellectual property infringement, loss of profits, or interruption of business, or for any special, consequential or incidental damages, however caused. Copyright 2008 Orange Tree Samples, All Rights Reserved Website: http://www.orangetreesamples.com Email: admin@orangetreesamples.com </info> <license>Copyright 2008 Orange Tree Samples, All Rights Reserved</license> <author>Orange Tree Samples / Oddtime</author> <url>https://www.orangetreesamples.com/download/JazzFunkKit.h2drumkit</url> </drumkit> <drumkit><name>Boss DR-110 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Boss_DR-110.h2drumkit</url><info>A compact programmable drum machine, DR-110 is one of the last fully-analog computer-controlled boxes made by Roland/Boss. It's ever-fresh sounds lie somewhere between TR-808 and TR-606.</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>Classic 3355606 (sf)</name><url>http://prdownloads.sf.net/hydrogen/3355606kit.h2drumkit</url><info>Based on sounds from famous and classic beatboxes of 1970s and 1980s</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>Classic 626 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Classic-626.h2drumkit</url><info>One of the very last drum boxes of the TR series. TR-626 featured 30 12-bit PCM samples of classic drum and percussion sounds, as well as latin percussion.</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit> <name>circAfrique v4</name> <url>http://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/circAfrique v4.h2drumkit</url> <info>A collection of african instruments from www.circAfrique.com. Includes djembe, sangban, dununba and kenkeni.</info> <author>Jim Harney</author> <license>Creative Commons - Attribution-ShareAlike 3.0 Unported</license> </drumkit> <drumkit><name>ColomboAcousticDrumkit (sf)</name><url>http://prdownloads.sf.net/hydrogen/ColomboAcousticDrumkit.h2drumkit</url><info>Based on "Colombo Percussion", handmade in Argentina circa 1970 to 1980. * Wooden toms, snare and bassdrum * Toms: 12X8 13X9 16X16 (hi, mid, low-foor) * Bassdrum: 21X14 * Snare "piccolo" 14X4 * Aquarian patch set * Crash 16'' Sabian "B8 Pro, Thin Crash" * Crash 20'' Paiste 1000 "Power Crash 20''", made in Switzerland * Hihat Paiste 1000 14'' "Rude", made in Switzerland</info><author>(c)2006 by Marcos Guglielmetti</author><license></license></drumkit><drumkit><name>YamahaVintageKit (sf)</name><url>http://prdownloads.sf.net/hydrogen/YamahaVintageKit.h2drumkit</url><info>Pristine-quality, stereo multi-layered kit based on samples of a 1970's Yamaha drum kit.</info><author>Artemiy Pavlov</author><license></license> </drumkit> <drumkit><name>DeathMetal (sf)</name><url>http://prdownloads.sf.net/hydrogen/DeathMetal.h2drumkit</url><info>This drumkit was created and published for all the people who want to make some metal drum patterns to sound more natural.</info><author>Archman</author><license>CC-Attribution</license></drumkit> <drumkit> <name>Denon CRB-90</name> <url>http://hydro.smoors.de/Denon CRB-90.h2drumkit</url> <info>This drumkit was created with samples from the original Denon CRB-90 Rhythm Box. More info can be found on http://audio-and-linux.blogspot.com/2012/06/denon-rhythm-box-for-hydrogen.htm</info> <author>Thijs Van Severen</author> <license>CC-BY-SA</license> </drumkit> <drumkit> <name>Drumkit excepcional</name> <url>http://hydro.smoors.de/Drumkit excepcional.h2drumkit</url> <info>Sons gravados de maneira caseira</info> <author>Pedro Maurício</author> <license>creative commons</license> </drumkit> <drumkit><name>EasternHop (sf)</name><url>http://prdownloads.sf.net/hydrogen/EasternHop-1.h2drumkit</url><info>A perfect kit for ethnic hip-hop: contains groovy kicks, snares and hats along with indian tabla drums</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>Electric Empire (sf)</name><url>http://prdownloads.sf.net/hydrogen/ElectricEmpireKit.h2drumkit</url><info>World-class original synth drum and percussion sounds, all painstakingly synthesised from noise and sine waves. Perfect for any sort of electro, old-school hip hop and break beat.</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>Erny's percussions (sf)</name><url>http://prdownloads.sf.net/hydrogen/ErnysPercussion.h2drumkit</url><info>A nice contributed drumkit with 32 percussion instruments.</info><author>Erny</author><license></license></drumkit> <drumkit> <name>Forzee Stereo Drumkit</name> <url>https://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/ForzeeStereo.h2drumkit</url> <info> This drumkit includes: - TAMA Superstar Drum set (Kick, Tom Low, Tom Mid, Tom High) - Pearl Snare, Tambourine, Agogo - Paiste Cymbals - Custom Ride (Hand-made tuning) All drums were recorded with 4 microphones: - Kick drum: Shure BETA 52 A, Shure SM 57, 2 x MXL 606 - All others: 2 x Shure SM 57, 2 x MXL 606 All recorded data combined into stereo tracks. No equalization was applied for better use. Please enjoy them. Please visit http://forzee.org/ for contacts. </info> <author>Vladimir Sadovnikov, Alexander Belokurov</author> <license>This drumkit is distributed under the GPL version 2 license.</license> </drumkit> <drumkit> <name>Gimme A Hand 1.0</name> <url>https://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/Gimme A Hand 1.0.h2drumkit</url> <info>An Assortment of Hand Percussion Instruments Including Cajon, Bongos, Maracas and Much More...</info> <author>Glen MacArthur</author> <license>GPL</license> </drumkit> <drumkit> <name>GSCW Kit 1 (Flac edition)</name> <url>http://hydro.smoors.de/Flac_GSCW-1.h2drumkit</url> <info> The flac edition of the famous GSCW drumkit. Some layers were removed to reduce the size. Based on samples from Salvador Pelaez</info> <author>Stefano Carbonelli</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>GSCW Kit 2 (Flac edition)</name> <url>http://hydro.smoors.de/Flac_GSCW-2.h2drumkit</url> <info> The flac edition of the famous GSCW drumkit. Some layers were removed to reduce the size. Based on samples from Salvador Pelaez</info> <author>Stefano Carbonelli</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit><name>HardElectro (sf)</name><url>http://prdownloads.sf.net/hydrogen/HardElectro1.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>HipHop-1 (sf)</name><url>http://prdownloads.sf.net/hydrogen/HipHop-1.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>HipHop-2 (sf)</name><url>http://prdownloads.sf.net/hydrogen/HipHop-2.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit> <name>K-27 Trash Kit</name> <url>https://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/K-27_Trash_Kit.h2drumkit</url> <info>The K-27 Trash Kit is a cool set to compose punk and garage musik</info> <author>Wolke</author> </drumkit> <drumkit> <name>Lightning1024</name> <url>http://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/Lightning1024.h2drumkit</url> <info>An small library made by me to get a clear sound in the most posible lightweight bank. Una pequeña libreria hecha por mi para obtener un sonido claro en un banco lo mas livianamente posible.</info> <author>Esteban Mariano Romanelli</author> <license>Free!!!</license> </drumkit> <drumkit><name>Millo drums 1 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Millo-Drums_v.1.h2drumkit</url><info>A nice kit from Emillo (Cricket studio)</info><author>Emiliano Grilli</author><license></license></drumkit> <drumkit><name>Millo's MultiLayered 2 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Millo_MultiLayered2.h2drumkit</url><info>Nice and multilayered drumkit from Emillo.net</info><author>Emiliano Grilli</author><license></license></drumkit> <drumkit><name>Millo's MultiLayered 3 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Millo_MultiLayered3.h2drumkit</url><info>This is the third version of a ludwig drumkit. Recorded at cricketstudios.it, released under the GPL. Feel free to modify it and integrate it with other sounds. If you end up with good sounding demos with it, please mail them to emillo@emillo.net</info><author>Emiliano Grilli</author><license></license></drumkit> <!-- Links seem to be dead by now.. <drumkit> <name>Roland TR-909</name> <url>http://www.hydrogen-music.org/download/drumkits/Roland TR-909.h2drumkit</url> <info></info> <author>Artemiy Pavlov</author> </drumkit> <drumkit> <name>Roland TR-808</name> <url>http://www.hydrogen-music.org/download/drumkits/Roland TR-808.h2drumkit</url> <info></info> <author>Artemiy Pavlov</author> </drumkit> <drumkit> <name>Roland TR-707</name> <url>http://www.hydrogen-music.org/download/drumkits/Roland TR-707.h2drumkit</url> <info></info> <author>Artemiy Pavlov</author> </drumkit> <drumkit> <name>Roland TR-606</name> <url>http://www.hydrogen-music.org/download/drumkits/Roland TR-606.h2drumkit</url> <info></info> <author>Artemiy Pavlov</author> </drumkit> --> <drumkit> <name>Roland_MC-307_CR78&amp;Cheaps</name> <url>http://hydro.smoors.de/Roland_MC-307_CR78&amp;Cheaps.h2drumkit</url> <info> An CR78&amp;Cheaps MC-307 groovebox clone</info> <author>Michael Wolkstein</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>Roland_MC-307_TR-606</name> <url>http://hydro.smoors.de/Roland_MC-307_TR-606.h2drumkit</url> <info> An TR-606 MC-307 groovebox clone</info> <author>Michael Wolkstein</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>Roland_MC-307_TR-808_</name> <url>http://hydro.smoors.de/Roland_MC-307_TR-808.h2drumkit</url> <info> An TR-808 MC-307 groovebox clone</info> <author>Michael Wolkstein</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>Roland_MC-307_TR-909</name> <url>http://hydro.smoors.de/Roland_MC-307_TR-909.h2drumkit</url> <info> An TR-909 MC-307 groovebox clone</info> <author>Michael Wolkstein</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>Roland_MC-307_Techno1</name> <url>http://hydro.smoors.de/Roland_MC-307_Techno1.h2drumkit</url> <info> An Techno1 MC-307 groovebox clone</info> <author>Michael Wolkstein</author> <license>Do not redistribute or publish the inluded samples.</license> </drumkit> <drumkit> <name>rumpf_kit_z01_gm</name> <url>http://hydro.smoors.de/rumpf_kit_z01_h2.h2drumkit</url> <info>Drum kit from analog samples. Partly GM-drum compatible. Format:48000Hz,24Bit,flac</info> <author>Emanuel Rumpf</author> <license>cc-by ==> http://creativecommons.org/licenses/by/3.0/</license> </drumkit> <drumkit> <name>SF3007-2011-Set-03</name> <url>https://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/SF3007-2011-Set-03.h2drumkit</url> <author>Rainer Steffen Hain, Germany</author> <info>Acoustic Drum made of samples from a huge Sonor Force 3007 Drumset. Recorded with the Phonic Helix Board MKII and Audacity in 2011 under Muppy Linux</info> <license>What the Fuck Public License (WTFPL)</license> </drumkit> <drumkit><name>Synthie-1 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Synthie-1.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>TD-7 (sf)</name><url>http://prdownloads.sf.net/hydrogen/TD-7kit.h2drumkit</url><info>A kit based on samples from Roland TD-7 percussion sound module of middle 1990s</info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>Techno-1 (sf)</name><url>http://prdownloads.sf.net/hydrogen/Techno-1.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit> <name>The Black Pearl 1.0</name> <url>https://sourceforge.net/projects/hydrogen/files/Sound%20Libraries/Main%20sound%20libraries/The Black Pearl 1.0.h2drumkit</url> <info>A Sampled 5pc Pearl DX Series Drumkit.</info> <author>Glen MacArthur</author> <license>GPL</license> </drumkit> <drumkit><name>TR808909 (sf)</name><url>http://prdownloads.sf.net/hydrogen/TR808909.h2drumkit</url><info></info><author>Artemiy Pavlov</author><license></license></drumkit> <drumkit><name>VariBreaks (sf)</name><url>http://prdownloads.sf.net/hydrogen/VariBreaks.h2drumkit</url><info>All sounds in this kit have been created from scratch using Roland V-Synth. The source material were samples of sounds based on sine and noise waveforms processed with COSM blocks, which were then re-synthesized multiple times using VariPhrase and COSM technologies.</info><author>Artemiy Pavlov</author><license></license></drumkit> <pattern> <name>JazzRockFast</name> <author>Benoit Rouits</author> <license>Public Domain</license> <url>http://hydro.smoors.de/songs_pattern/Patterns/unknown/JazzRockFast.h2pattern</url> </pattern> </drumkit_list>
mit
naelstrof/PugBot-Discord-Django
pugbot/cogs/pug.py
47354
import asyncio import collections import collections.abc import contextlib import functools import heapq import itertools import random import re import shelve import os from discord.ext import commands import discord import pendulum PICKMODES = [ [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 1, 0], [0, 1, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1], [0, 1, 1, 0, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 1, 0]] MAXPLAYERS = len(PICKMODES[0]) + 2 MAXTAGLENGTH = 10 PLASEP = '\N{SMALL ORANGE DIAMOND}' MODSEP = '\N{SMALL BLUE DIAMOND}' OKMSG = '\N{OK HAND SIGN}' DISCORD_MD_CHARS = '*~_`' DISCORD_MD_ESCAPE_RE = re.compile('[{}]'.format(DISCORD_MD_CHARS)) DISCORD_MD_ESCAPE_DICT = {c: '\\' + c for c in DISCORD_MD_CHARS} def discord_md_escape(value): return DISCORD_MD_ESCAPE_RE.sub(lambda match: DISCORD_MD_ESCAPE_DICT[match.group(0)], value) def display_name(member): return discord_md_escape(member.display_name) class Mod(collections.abc.MutableSet): """Maintains the state for players in a PUG""" def __init__(self, name, desc, maxplayers): self.name = name self.desc = desc self.maxplayers = maxplayers self.players = [] self.maps = set() def __contains__(self, member): return member in self.players def __iter__(self): return iter(self.players) def __len__(self): return len(self.players) def __getstate__(self): state = self.__dict__.copy() del state['players'] return state def __setstate__(self, state): self.__dict__ = state self.players = [] @property def brief(self): return '**{}** [{}/{}]'.format(self.name, len(self), self.maxplayers) @property def full(self): return len(self) == self.maxplayers @property def needed(self): return self.maxplayers - len(self) @property def teamgame(self): return False def add(self, member): if member not in self and not self.full: self.players.append(member) return True def discard(self, member): if member in self: self.players.remove(member) return True def fullreset(self): self.players = [] class Team(list): def __init__(self): super().__init__() @property def captain(self): return self[0] class TeamMod(Mod): def __init__(self, name, desc, maxplayers, pickmode): super().__init__(name, desc, maxplayers) self.teams = (Team(), Team()) self.pickmode = pickmode self.task = None self.here = [True, True] def __getstate__(self): state = super().__getstate__() del state['teams'] del state['task'] del state['here'] return state def __setstate__(self, state): super().__setstate__(state) self.teams = (Team(), Team()) self.task = None self.here = [True, True] @property def teamgame(self): return True @property def hascaptains(self): return self.red and self.blue @property def team(self): return PICKMODES[self.pickmode][len(self.red) + len(self.blue) - 2] @property def captain(self): return self.teams[self.team].captain if self.hascaptains else None @property def teamsready(self): return len(self.red) + len(self.blue) == self.maxplayers @property def red(self): return self.teams[0] @property def blue(self): return self.teams[1] def __contains__(self, member): return member in (self.players + self.red + self.blue) def discard(self, member): if member in self: if self.red: self.reset() if self.task: self.task.cancel() self.players.remove(member) return True def reset(self): if self.red: self.players += self.red + self.blue self.players = list(filter(None, self.players)) self.red.clear() self.blue.clear() self.here = [True, True] if self.task: self.task.cancel() return True return False def fullreset(self): self.players = [] self.red.clear() self.blue.clear() self.here = [True, True] if self.task: self.task.cancel() def setcaptain(self, player): if player in self.players and self.full: index = self.players.index(player) if not self.red: self.red.append(player) elif not self.blue: self.blue.append(player) else: return False self.players[index] = None return True return False def pick(self, captain, index): if captain == self.captain: self.here[self.team] = True if all(self.here) and self.task: self.task.cancel() if index < 0 or index >= len(self) or not self.players[index]: return False player = self.players[index] self.teams[self.team].append(player) self.players[index] = None # check to see if next team has any choice and move them index = len(self.red) + len(self.blue) - 2 remaining = PICKMODES[self.pickmode][index:self.maxplayers - 2] if len(set(remaining)) == 1: self.teams[remaining[0]].extend(p for p in self.players if p) return True class PUGChannel(collections.abc.MutableMapping): def __init__(self): self.active = True self.server_name = '' self.randcaptaintimer = 20 self.idlecaptaintimer = 60 self.mods = collections.OrderedDict() def __setitem__(self, key: str, mod: Mod): self.mods[key.lower()] = mod def __getitem__(self, key: str): return self.mods[key.lower()] def __delitem__(self, key: str): del self.mods[key.lower()] def __iter__(self): return iter(self.mods) def __len__(self): return len(self.mods) @property def team_mods(self): return (mod for mod in self.values() if mod.teamgame) class ModStats: def __init__(self): self.total = 0 self.timestamp = pendulum.now().timestamp self.last_timestamp = self.timestamp @property def last(self): return HistoryItem(self.last_timestamp) @property def daily(self): days = (pendulum.now() - pendulum.from_timestamp(self.timestamp)).days return self.total / (days + 1) def update(self, timestamp): self.total += 1 self.last_timestamp = timestamp return self class TeamStats(ModStats): def __init__(self): super().__init__() self.picks = 0 self.captain = 0 @property def average_pick(self): total = self.total - self.captain return 0 if total == 0 else self.picks / total def update(self, timestamp, pick): self.picks += pick self.captain += 0 if pick else 1 return super().update(timestamp) class HistoryItem: def __init__(self, timestamp, players=None, modid=None): self.timestamp = timestamp self.players = '\n' + players if players else '' self.modid = modid def __str__(self): name = '**{}** '.format(self.modid) if self.modid else '' when = (pendulum.now() - pendulum.from_timestamp(self.timestamp)).in_words() return '{}[{} ago]{}'.format(name, when, self.players) def __lt__(self, other): return self.timestamp < other.timestamp class PUGStats: def __init__(self): self.total = 0 self.timestamp = pendulum.now().timestamp self.history = collections.deque(maxlen=3) @property def daily(self): days = (pendulum.now() - pendulum.from_timestamp(self.timestamp)).days return self.total / (days + 1) @property def last_timestamp(self): return self.last.timestamp @property def last(self): return HistoryItem(*self.history[-1]) @property def lastt(self): return HistoryItem(*self.history[min(0, len(self.history) - 1)]) @property def lasttt(self): return HistoryItem(*self.history[0]) def update(self, timestamp, players): self.total += 1 self.history.append((timestamp, players)) return self class Stats(collections.abc.MutableMapping): def __init__(self): self.data = dict() def __getitem__(self, mod): return self.data[mod.name] def __setitem__(self, mod, value): self.data[mod.name] = value def __delitem__(self, mod): del self.data[mod.name] def __iter__(self): return iter(self.data) def __len__(self): return len(self.data) def items(self): return self.data.items() def values(self): return self.data.values() @property def timestamp(self): return min(self.values(), key=lambda x: x.timestamp).timestamp @property def total(self): return sum(mod.total for mod in self.values()) @property def daily(self): days = (pendulum.now() - pendulum.from_timestamp(self.timestamp)).days return self.total / (days + 1) @property def last(self): modid, stats = max(self.items(), key=lambda x: x[1].last) last = stats.last last.modid = modid return last class ChannelStats(Stats): """Stores the PUG stats for the channel""" @property def history(self): for mod, stats in self.items(): for timestamp, players in stats.history: yield HistoryItem(timestamp, players, modid=mod) @property def lastt(self): history = sorted(self.history, reverse=True) return history[min(1, len(history) - 1)] @property def lasttt(self): history = sorted(self.history, reverse=True) return history[min(2, len(history) - 1)] class MemberStats(Stats): """Stores the member's stats for a channel""" @property def team_stats(self): return (mod for mod in self.values() if isinstance(mod, TeamStats)) @property def captain(self): return sum(mod.captain for mod in self.team_stats) @property def average_pick(self): total, picks = 0, 0 for mod in self.team_stats: total += mod.total - mod.captain picks += mod.picks return 0 if total == 0 else picks / total class ChannelStatsView: def __init__(self, db, channel): self.db = db self.channel = channel def __iter__(self): for member_id, stats in self.db.items(): member = self.channel.server.get_member(member_id) if member and not member.bot and self.channel.id in stats: yield member, stats[self.channel.id] class ModStatsView(ChannelStatsView): def __init__(self, db, channel, mod): super().__init__(db, channel) self.mod = mod def __iter__(self): return ((member, stats[self.mod]) for member, stats in super().__iter__() if self.mod in stats) class StatsDB(collections.abc.MutableMapping): def __init__(self, db, channel, mod): self.db = db self.channel = channel self.mod = mod def __getitem__(self, member): stats = self.db[member.id] if self.channel.id in stats: if self.mod is None: return stats[self.channel.id] elif self.mod in stats[self.channel.id]: return stats[self.channel.id][self.mod] raise KeyError def __setitem__(self, member, value): stats = self.db.get(member.id, dict()) cls = ChannelStats if member.bot else MemberStats channel_stats = stats.setdefault(self.channel.id, cls()) channel_stats[self.mod] = value self.db[member.id] = stats def __delitem__(self, member): del self.db[member.id] def __len__(self): return len(self.db) def __iter__(self): if self.mod is None: return iter(ChannelStatsView(self.db, self.channel)) return iter(ModStatsView(self.db, self.channel, self.mod)) @contextlib.contextmanager def stats_open(channel, mod, flag='c', writeback=False): with shelve.open('data/stats', flag=flag, writeback=writeback) as db: yield StatsDB(db, channel, mod) def clamp(n, low, high): return max(low, min(n, high)) def ispugchannel(ctx): pugchannel = ctx.bot.get_cog('PUG').channels.get(ctx.message.channel) return pugchannel is not None and pugchannel.active class ModConverter(commands.Converter): def convert(self): mod = self.ctx.cog.channels[self.ctx.message.channel].get(self.argument) if mod is None: raise commands.errors.BadArgument('PUG "{}" not found'.format(self.argument)) return mod class TeamModConverter(ModConverter): def convert(self): mod = super().convert() if not mod.teamgame: raise commands.errors.BadArgument('"{}" is not a team PUG'.format(mod.name)) return mod class PUG: """PUG related commands""" def __init__(self, bot): self.bot = bot self.last_teams = dict() self.tags = collections.defaultdict(lambda: collections.defaultdict(str)) self.nocaptains = collections.defaultdict(set) self.channels = dict() async def on_ready(self): """Load PUGChannels""" with shelve.open('data/pug') as db: for (channel_id, pugchannel) in list(db.items()): channel = self.bot.get_channel(channel_id) if channel is not None: self.channels[channel] = pugchannel else: del db[channel_id] @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) async def pugbot(self, ctx, enable: bool): """Enables/Disables PUG commands in the channel""" pugchannel = self.channels.get(ctx.message.channel) if pugchannel is None: if not enable: return self.channels[ctx.message.channel] = PUGChannel() else: if pugchannel.active == enable: return pugchannel.active = enable status = ' enabled' if enable else ' disabled' await self.bot.say('PUG commands have been' + status) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = self.channels[ctx.message.channel] @commands.command(no_pm=True, aliases=['pickorders']) @commands.check(ispugchannel) async def pickmodes(self): """Displays the available pickmodes""" await self.bot.say('```{}```'.format( '\n'.join('{}) {}'.format(i, ', '.join(map(str, pm))) for i, pm in enumerate(PICKMODES)))) @commands.command(pass_context=True, no_pm=True, aliases=['setpickorder']) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setpickmode(self, ctx, mod: TeamModConverter, pickmode: int): """Set pickmode for mod""" if 0 <= pickmode < len(PICKMODES): mod.pickmode = pickmode await self.bot.say(OKMSG) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = self.channels[ctx.message.channel] @commands.command(no_pm=True, aliases=['pickorder']) @commands.check(ispugchannel) async def pickmode(self, mod: TeamModConverter): """Displays the pickmode for mod""" pickmode = PICKMODES[mod.pickmode][:mod.maxplayers - 2] await self.bot.say('```[{}]```'.format(', '.join(map(str, pickmode)))) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setlimit(self, ctx, mod: ModConverter, limit: int): """Sets number of players required to fill mod""" if limt > 1 and not mod.full and (not mod.teamgame or limit <= MAXPLAYERS): mod.maxplayers = limit await self.bot.say(OKMSG) with shelve.open('data/pug') as db: db[ctx.message.channel.id] = self.channels[ctx.message.channel] @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setrandcaptaintimer(self, ctx, duration: int): """Set the amount of time bot waits before setting random captains""" pugchannel = self.channels[ctx.message.channel] pugchannel.randcaptaintimer = clamp(duration, 10, 99) await self.bot.say(OKMSG) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = pugchannel @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setidlecaptaintimer(self, ctx, duration: int): """Set the amount of time bot waits before kicking idle captains""" pugchannel = self.channels[ctx.message.channel] pugchannel.idlecaptaintimer = clamp(duration, 10, 99) await self.bot.say(OKMSG) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = pugchannel @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setserver(self, ctx, *, server: str): """Set the channel's PUG server""" pugchannel = self.channels[ctx.message.channel] pugchannel.server_name = server await self.bot.say(OKMSG) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = pugchannel @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def server(self, ctx): """Displays channel's PUG server""" pugchannel = self.channels[ctx.message.channel] if pugchannel.server_name: await self.bot.say(pugchannel.server_name) else: await self.bot.say('No server set, use `.setserver` to set the server') @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def addmod(self, ctx, mod: str, name: str, n: int, teams: bool=True, pickmode: int=1): """Adds new mod to the channel""" pugchannel = self.channels[ctx.message.channel] if n < 2 or mod in pugchannel: return if n == 2: teams = False if teams: if 4 > n > MAXPLAYERS or n % 2 == 1 or 0 > pickmode >= len(PICKMODES): return pickmode = 0 if n == 4 else pickmode pugchannel[mod] = TeamMod(mod, name, n, pickmode) else: pugchannel[mod] = Mod(mod, name, n) await self.bot.say(OKMSG) with shelve.open('data/pug') as db: db[ctx.message.channel.id] = pugchannel @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def delmod(self, ctx, mod: ModConverter): """Deletes mod from the channel""" pugchannel = self.channels[ctx.message.channel] del pugchannel[mod.name] await self.bot.say(OKMSG) with shelve.open('data/pug', 'w') as db: db[ctx.message.channel.id] = pugchannel async def on_command_error(self, error, ctx): """If a PUG command is used in a channel that doesn't have active PUGs send a message display the active channels on the server """ cmds = {'join', 'list', 'last', 'liast', 'lastt', 'liastt', 'lasttt', 'liasttt'} if isinstance(error, commands.errors.CheckFailure) and ctx.command.name in cmds: server = ctx.message.server active_channels = (channel for channel in self.channels if channel.server == server and self.channels[channel].active) channel_mentions = [channel.mention for channel in active_channels] if channel_mentions: await self.bot.send_message(ctx.message.channel, '**Active Channels:** {}'.format(' '.join(channel_mentions))) def get_tag(self, member): return self.tags[member.server][member] def format_players(self, ps, number=False, mention=False, tags=True): def name(p): return p.mention if mention else display_name(p) xs = ((i, name(p), self.get_tag(p)) for i, p in enumerate(ps, 1) if p) fmt = '**{0})** {1}' if number else '{1}' fmt += '{2}' if tags else '' return PLASEP.join(fmt.format(*x) for x in xs) def format_mod(self, mod): fmt = '**__{0.desc} [{1}/{0.maxplayers}]:__**\n{2}' return fmt.format(mod, len(mod), self.format_players(mod, number=mod.full)) def format_teams(self, mod, mention=False, tags=False): teams = '**Red Team:** {}\n**Blue Team:** {}' red = self.format_players(mod.red, mention=mention, tags=tags) blue = self.format_players(mod.blue, mention=mention, tags=tags) return teams.format(red, blue) def format_last(self, channel, mod, attr='last'): with stats_open(channel, mod, flag='r') as db: pugstats = db.get(self.bot.user, None) if pugstats is not None: history_item = getattr(pugstats, attr) return '**{}:** {}'.format(attr.title(), history_item) return 'No PUGs recorded' def format_list(self, channel, mod): if mod is None: pugchannel = self.channels[channel] return MODSEP.join(mod.brief for mod in pugchannel.values()) else: return self.format_mod(mod) def format_liast(self, channel, mod, attr='last'): ls = self.format_list(channel, mod) la = self.format_last(channel, mod, attr) return '{}\n{}'.format(ls, la) @commands.command(name='list', pass_context=True, no_pm=True, aliases=['ls']) @commands.check(ispugchannel) async def _list(self, ctx, mod: ModConverter=None): """Displays mods/players in the channel""" await self.bot.say(self.format_list(ctx.message.channel, mod)) @commands.command(pass_context=True, no_pm=True, aliases=['la']) @commands.check(ispugchannel) async def last(self, ctx, mod: ModConverter=None): """Displays players from last PUG""" await self.bot.say(self.format_last(ctx.message.channel, mod)) @commands.command(pass_context=True, no_pm=True, aliases=['lia']) @commands.check(ispugchannel) async def liast(self, ctx, mod: ModConverter=None): """Display mods/players and last PUG""" await self.bot.say(self.format_liast(ctx.message.channel, mod)) @commands.command(pass_context=True, no_pm=True, hidden=True) @commands.check(ispugchannel) async def lastt(self, ctx, mod: ModConverter=None): await self.bot.say(self.format_last(ctx.message.channel, mod, 'lastt')) @commands.command(pass_context=True, no_pm=True, hidden=True) @commands.check(ispugchannel) async def liastt(self, ctx, mod: ModConverter=None): await self.bot.say(self.format_liast(ctx.message.channel, mod, 'lastt')) @commands.command(pass_context=True, no_pm=True, hidden=True) @commands.check(ispugchannel) async def lasttt(self, ctx, mod: ModConverter=None): await self.bot.say(self.format_last(ctx.message.channel, mod, 'lasttt')) @commands.command(pass_context=True, no_pm=True, hidden=True) @commands.check(ispugchannel) async def liasttt(self, ctx, mod: ModConverter=None): await self.bot.say(self.format_liast(ctx.message.channel, mod, 'lasttt')) async def addplayers_impl(self, channel, mod, members): if not any(list(mod.add(m) for m in members)): return if not mod.full: return await self.bot.say(self.format_mod(mod)) msg = ['**{}** has been filled'.format(mod.name)] msg.append(self.format_players(mod, mention=True, tags=False)) mods = (other for other in self.channels[channel].values() if other is not mod) for other in mods: wasfull = other.full if any(list(other.discard(p) for p in mod)) and wasfull: msg.append('**{}** was reset'.format(other.name)) await self.bot.say('\n'.join(msg)) if mod.teamgame: mod.task = self.bot.loop.create_task(self.randcaptains(channel, mod)) else: timestamp = pendulum.now().timestamp with stats_open(channel, mod) as db: for member in mod: db[member] = db.get(member, ModStats()).update(timestamp) self.remove_tags(member) players = self.format_players(mod, mention=False, tags=False) db[self.bot.user] = db.get(self.bot.user, PUGStats()).update(timestamp, players) mod.fullreset() @commands.command(pass_context=True, no_pm=True, aliases=['addplayer']) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def addplayers(self, ctx, mod: ModConverter, *members: discord.Member): """Adds players to mod""" await self.addplayers_impl(ctx.message.channel, mod, (m for m in members if not m.bot)) @commands.command(pass_context=True, no_pm=True, aliases=['j']) @commands.check(ispugchannel) async def join(self, ctx, mod: ModConverter): """Joins mod""" await self.addplayers_impl(ctx.message.channel, mod, [ctx.message.author]) async def randcaptains(self, channel, mod): """Waits for n seconds before selecting random captains""" content = '`Random captains in {:2d} seconds`' seconds = self.channels[channel].randcaptaintimer message = await self.bot.send_message(channel, content.format(seconds)) mod.here = [False, False] for i in range(seconds - 1, -1, -1): try: await asyncio.sleep(1) if i % 5 == 0 or i < 10: message = await self.bot.edit_message(message, content.format(i)) except asyncio.CancelledError: return await self.bot.edit_message(message, '`Random captains cancelled`') if not mod.full or mod.hascaptains: return candidates = [p for p in mod if p and p not in self.nocaptains[channel.server]] if len(candidates) < 2: candidates = list(mod) random.shuffle(candidates) msg, redset = [], False if not mod.red: redset = mod.setcaptain(candidates.pop(0)) msg.append(mod.red.captain.mention + ' is captain for the **Red Team**') blue_captain = candidates.pop(0) mod.setcaptain(blue_captain) mod.here = [not redset, False] await self.bot.edit_message(message, '`Random captains selected`') msg.append(blue_captain.mention + ' is captain for the **Blue Team**') msg.append('Type .here to prevent being kicked') msg.append('{} to pick'.format(mod.captain.mention)) msg.append(self.format_players(mod, number=True)) await self.bot.send_message(channel, '\n'.join(msg)) mod.task = self.bot.loop.create_task(self.kick_idle(channel, mod)) async def kick_idle(self, channel, mod): """Removes captains if they did not pick or type .here""" try: await asyncio.sleep(self.channels[channel].idlecaptaintimer) except asyncio.CancelledError: return if mod.hascaptains and not all(mod.here): msg = ['**{}** was reset'.format(mod.name)] kick = [] for i in range(2): if not mod.here[i]: captain = mod.teams[i].captain kick.append(captain) msg.append('{} was removed for being idle'.format(captain.mention)) # Send the message before we kick the players, otherwise the task will be cancelled await self.bot.send_message(channel, '\n'.join(msg)) [mod.discard(p) for p in kick] @commands.command(pass_context=True, no_pm=True, aliases=['pro']) @commands.cooldown(2, 5.0, type=commands.BucketType.channel) @commands.check(ispugchannel) async def promote(self, ctx, mod: ModConverter): """Notify other members in the channel""" await self.bot.say('@here Only **{0.needed}** more needed for **{0.name}**'.format(mod)) async def remove_player(self, channel, mod, player, reason): wasfull = mod.full name = player.mention if reason == 'was removed' else display_name(player) if mod.discard(player): if wasfull: await self.bot.say('**{}** was reset because **{}** {}'.format(mod.name, name, reason)) else: await self.bot.say('**{}** was removed from **{}** because they {}'.format(name, mod.name, reason)) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def delplayer(self, ctx, mod: ModConverter, member: discord.Member): """Removes player from mod""" await self.remove_player(ctx.message.channel, mod, member, 'was removed') @commands.command(pass_context=True, no_pm=True, aliases=['l']) @commands.check(ispugchannel) async def leave(self, ctx, mod: ModConverter): """Leave mod""" await self.remove_player(ctx.message.channel, mod, ctx.message.author, 'left') @commands.command(pass_context=True, no_pm=True, aliases=['lva']) @commands.check(ispugchannel) async def leaveall(self, ctx): """Leaves all mods you have joined, including other channels""" for channel in self.channels: await self.remove_from_channel(ctx.message.author, channel, 'left') async def on_member_update(self, before, after): """Remove member from all mods if they go offline""" if after.status is discord.Status.offline: await self.remove_from_server(before, 'quit') def removed_from(self, member, channel): pugchannel = self.channels[channel] mods = (mod for mod in pugchannel.values() if member in mod) for mod in mods: yield mod mod.discard(member) async def remove_from_channel(self, member, channel, reason): reset, removed = None, [] for mod in self.removed_from(member, channel): if mod.full: reset = mod.name else: removed.append(mod.name) msg, name = [], display_name(member) if reset: fmt = '**{}** was reset because **{}** {}' msg.append(fmt.format(reset, name, reason)) if removed: fmt = '**{}** was removed from **{}** because they {}' if len(removed) > 1: mods = ', '.join(removed[:-1]) + ' & ' + removed[-1] else: mods = removed[0] msg.append(fmt.format(name, mods, reason)) if msg: await self.bot.send_message(channel, '\n'.join(msg)) async def remove_from_server(self, member, reason): """Removes the member from the server""" self.remove_tags(member) for channel in self.channels: if channel.server == member.server: await self.remove_from_channel(member, channel, reason) async def on_member_remove(self, member): """Remove member from all mods in the server""" await self.remove_from_server(member, 'left the server') async def on_member_ban(self, member): """Remove member from all mods in the server""" with shelve.open('data/bans') as db: bans = db.get(member.server.id, collections.Counter()) bans[member.id] += 1 db[server.id] = bans await self.remove_from_server(member, 'was banned') async def on_channel_delete(self, channel): """Remove PUGChannel if the associated channel was deleted""" if channel in self.channels: del self.channels[channel] with shelve.open('data/pug', 'w') as db: del db[channel.id] async def on_server_remove(self, server): """Remove server tags when server is removed from the bot""" self.tags.pop(server) self.nocaptains.pop(server) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def reset(self, ctx, mod: TeamModConverter=None): """Resets teams""" if mod is None: pugchannel = self.channels[ctx.message.channel] mods = [mod for mod in pugchannel.team_mods if mod.red] if len(mods) == 1: mod = mods[0] if mod is not None and mod.reset(): await self.bot.say('**{}** was reset'.format(mod.name)) mod.task = self.bot.loop.create_task(self.randcaptains(ctx.message.channel, mod)) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def fullreset(self, ctx, mod: ModConverter): """Resets players in the mod""" mod.fullreset() await self.bot.say('**{}** was reset'.format(mod.name)) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def here(self, ctx): """Prevent being kicked when set as random captain""" channel = ctx.message.channel pugchannel = self.channels[channel] captain = ctx.message.author for mod in pugchannel.team_mods: if mod.red: if mod.red.captain == captain: mod.here[0] = True return elif mod.blue and mod.blue.captain == captain: if not mod.here[1]: mod.here[1] = True if all(mod.here) and mod.task: mod.task.cancel() return async def setcaptain_impl(self, channel, member, mention=False): pugchannel = self.channels[channel] mod = next((mod for mod in pugchannel.team_mods if mod.setcaptain(member)), None) name = member.mention if mention else '**{}**'.format(display_name(member)) if mod is not None: if mod.hascaptains: if mod.task is not None: mod.task.cancel() msg = [name + ' is captain for the **Blue Team**'] msg.append('{} to pick'.format(mod.captain.mention)) msg.append(self.format_players(mod, number=True)) await self.bot.say('\n'.join(msg)) else: await self.bot.say('**{}** is captain for the **Red Team**'.format(name)) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def setcaptain(self, ctx, member: discord.Member): """Set player as captain""" await self.setcaptain_impl(ctx.message.channel, member, mention=True) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def captain(self, ctx): """Become captain for mod""" await self.setcaptain_impl(ctx.message.channel, ctx.message.author) @commands.command(pass_context=True, no_pm=True, aliases=['p']) @commands.check(ispugchannel) async def pick(self, ctx, *players: int): """Pick player by number""" channel = ctx.message.channel pugchannel = self.channels[channel] captain = ctx.message.author mod = next((mod for mod in pugchannel.team_mods if mod.captain == captain), None) if mod is None: return picks = list(itertools.takewhile(functools.partial(mod.pick, captain), (x - 1 for x in players))) if picks: teams = self.format_teams(mod) if mod.teamsready: self.last_teams[channel] = '**{}**\n{}'.format(mod.desc, teams) msg = 'Teams have been selected:\n{}'.format(self.format_teams(mod, mention=True)) await self.bot.say(msg) timestamp = pendulum.now().timestamp with stats_open(channel, mod) as db: members = mod.red + mod.blue xs = PICKMODES[mod.pickmode][:mod.maxplayers - 2] picks = [0] + [i + 1 for i, x in enumerate(xs) if x == 0] picks += [0] + [i + 1 for i, x in enumerate(xs) if x == 1] for i in range(mod.maxplayers): member = members[i] db[member] = db.get(member, TeamStats()).update(timestamp, picks[i]) self.remove_tags(member) db[self.bot.user] = db.get(self.bot.user, PUGStats()).update(timestamp, teams) mod.fullreset() else: msg = '\n'.join([ self.format_players(mod, number=True, tags=True), teams, '{} to pick'.format(mod.captain.mention)]) await self.bot.say(msg) @pick.error async def pick_error(self, error, ctx): if isinstance(error, commands.errors.BadArgument) and ctx.invoked_with == 'p': modid = ctx.message.content.split()[1] mod = self.channels[ctx.message.channel].get(modid, None) if mod is not None: await self.bot.say('@here Only **{0.needed}** more needed for **{0.name}**'.format(mod)) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def teams(self, ctx): """Displays current teams, or teams from last PUG""" pugchannel = self.channels[ctx.message.channel] mods = [(mod.desc, self.format_teams(mod, tags=True)) for mod in pugchannel.team_mods if mod.red] if mods: await self.bot.say('\n'.join('**__{}:__**\n{}'.format(*mod) for mod in mods)) elif ctx.message.channel in self.last_teams: await self.bot.say(self.last_teams[ctx.message.channel]) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def turn(self, ctx): """Displays captain whose turn it is to pick and current teams""" pugchannel = self.channels[ctx.message.channel] mods = [(display_name(mod.captain), mod.desc) for mod in pugchannel.team_mods if mod.hascaptains] if mods: await self.bot.say('\n'.join('**{}** to pick for **{}**'.format(*mod) for mod in mods)) async def display_stats(self, member, channel, mod): with stats_open(channel, mod, flag='r') as db: stats = db.get(member) if stats is None: return await self.bot.say('No stats available') out = [] out.append('**Total:** [{}]'.format(stats.total)) out.append('**Daily:** [{:.2f}]'.format(stats.daily)) if hasattr(stats, 'captain') and not member.bot: out.append('**Captain:** [{}]'.format(stats.captain)) mp = '/' + str(mod.maxplayers - 2) if mod is not None else '' out.append('**Avg. Pick:** [{:.2f}{}]'.format(stats.average_pick, mp)) if not member.bot: try: db = shelve.open('data/bans', 'r') except: out.append('**Bans:** [0]') else: bans = db.get(member.server.id, collections.Counter()) db.close() out.append('**Bans:** [{}]'.format(bans[member.id])) out.append('**Last:** {}'.format(stats.last)) await self.bot.say(MODSEP.join(out)) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def stats(self, ctx, member: discord.Member, mod: ModConverter=None): """Display PUG stats for player""" await self.display_stats(member, ctx.message.channel, mod) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def mystats(self, ctx, mod: ModConverter=None): """Display your PUG stats""" await self.display_stats(ctx.message.author, ctx.message.channel, mod) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def pugstats(self, ctx, mod: ModConverter=None): """Display channel PUG stats""" await self.display_stats(self.bot.user, ctx.message.channel, mod) @commands.command(pass_context=True, no_pm=True, aliases=['nocapt']) @commands.check(ispugchannel) async def nocaptain(self, ctx): """Prevent being made captain for next PUG, resets after next PUG""" self.nocaptains[ctx.message.server].add(ctx.message.author) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def nomic(self, ctx): """Sets tag to 'nomic'""" self.tags[ctx.message.server][ctx.message.author] = ' [nomic]' @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def tag(self, ctx, *, tag: str): """Sets custom tag for all mods""" if tag == 'nocapt' or tag == 'nocaptain': self.nocaptains[ctx.message.server].add(ctx.message.author) else: self.tags[ctx.message.server][ctx.message.author] = ' [{}]'.format(discord_md_escape(tag[:MAXTAGLENGTH])) def remove_tags(self, member): self.nocaptains[member.server].discard(member) self.tags[member.server].pop(member, None) @commands.command(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def deltag(self, ctx): """Deletes tags""" self.remove_tags(ctx.message.author) @commands.command(pass_context=True, no_pm=True, hidden=True) @commands.has_permissions(manage_server=True) async def cleartags(self, ctx): """Clear current tags for the server""" self.nocaptains.pop(ctx.message.server) self.tags.pop(ctx.message.server) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_server=True) async def numtags(self, ctx): """Displays the number tags in use on the server""" server = ctx.message.server await self.bot.whisper('tags: {}\nnocaptains: {}'.format(len(self.tags[server]), len(self.nocaptains[server]))) @commands.group(pass_context=True, no_pm=True) @commands.check(ispugchannel) async def top(self, ctx, n: int): """Displays a top n list for the channel""" if ctx.invoked_subcommand is not None: self.count = n @top.command(pass_context=True, no_pm=True) async def picks(self, ctx, mod: TeamModConverter=None): """Displays top average picks""" with stats_open(ctx.message.channel, mod, flag='r') as db: ps = ((display_name(p[0]), p[1].average_pick) for p in db if p[1].average_pick) topn = heapq.nsmallest(self.count, ps, key=lambda p: p[1]) if topn: entries = ('**{})** {} [{:.2f}]'.format(i, *p) for i, p in enumerate(topn, 1)) await self.bot.say(PLASEP.join(entries)) @top.command(pass_context=True, no_pm=True) async def puggers(self, ctx, mod: ModConverter=None): """Displays top puggers""" with stats_open(ctx.message.channel, mod, flag='r') as db: ps = ((display_name(p[0]), p[1].total) for p in db) topn = heapq.nlargest(self.count, ps, key=lambda p: p[1]) if topn: entries = ('**{})** {} [{}]'.format(i, *p) for i, p in enumerate(topn, 1)) await self.bot.say(PLASEP.join(entries)) @top.command(pass_context=True, no_pm=True) async def lamers(self, ctx, mod: ModConverter=None): """Displays top lamers""" with stats_open(ctx.message.channel, mod, flag='r') as db: ps = ((display_name(p[0]), p[1].total) for p in db) topn = heapq.nsmallest(self.count, ps, key=lambda p: p[1]) if topn: entries = ('**{})** {} [{}]'.format(i, *p) for i, p in enumerate(topn, 1)) await self.bot.say(PLASEP.join(entries)) @top.command(pass_context=True, no_pm=True) async def captains(self, ctx, mod: TeamModConverter=None): """Display top captains""" with stats_open(ctx.message.channel, mod, flag='r') as db: ps = ((display_name(p[0]), p[1].captain) for p in db if p[1].captain) topn = heapq.nlargest(self.count, ps, key=lambda p: p[1]) if topn: entries = ('**{})** {} [{}]'.format(i, *p) for i, p in enumerate(topn, 1)) await self.bot.say(PLASEP.join(entries)) @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def addmaps(self, ctx, mod: ModConverter, *maps: str): """Adds maps to mod""" if maps: mod.maps.update(maps) await self.bot.say(OKMSG) with shelve.open('data/pug') as db: db[ctx.message.channel.id] = self.channels[ctx.message.channel] @commands.command(pass_context=True, no_pm=True) @commands.has_permissions(manage_channels=True) @commands.check(ispugchannel) async def delmaps(self, ctx, mod: ModConverter, *maps: str): """Removes maps from mod""" if maps: mod.maps -= set(maps) await self.bot.say(OKMSG) with shelve.open('data/pug') as db: db[ctx.message.channel.id] = self.channels[ctx.message.channel] @commands.command(pass_context=True, no_pm=True, aliases=['maps']) @commands.check(ispugchannel) async def maplist(self, ctx, mod: ModConverter=None): """Displays maps for mod""" if mod is not None and mod.maps: await self.bot.say('**__{}__:**\n{}'.format(mod.desc, MODSEP.join(sorted(mod.maps)))) elif mod is None: pugchannel = self.channels[ctx.message.channel] mods = [mod for mod in pugchannel.values() if mod.maps] if mods: await self.bot.say('\n'.join('**__{}__:** {}'.format(mod.desc, MODSEP.join(sorted(mod.maps))) for mod in mods)) def setup(bot): if not os.path.exists('data'): os.makedirs('data') shelve.open('data/stats', 'c').close() bot.add_cog(PUG(bot))
mit
bccaddress/bccaddress.org
src/ninja.qrcode.js
2631
(function (ninja) { var qrC = ninja.qrCode = { // determine which type number is big enough for the input text length getTypeNumber: function (text) { var lengthCalculation = text.length * 8 + 12; // length as calculated by the QRCode if (lengthCalculation < 72) { return 1; } else if (lengthCalculation < 128) { return 2; } else if (lengthCalculation < 208) { return 3; } else if (lengthCalculation < 288) { return 4; } else if (lengthCalculation < 368) { return 5; } else if (lengthCalculation < 480) { return 6; } else if (lengthCalculation < 528) { return 7; } else if (lengthCalculation < 688) { return 8; } else if (lengthCalculation < 800) { return 9; } else if (lengthCalculation < 976) { return 10; } return null; }, createCanvas: function (text, sizeMultiplier) { sizeMultiplier = (sizeMultiplier == undefined) ? 2 : sizeMultiplier; // default 2 // create the qrcode itself var typeNumber = qrC.getTypeNumber(text); var qrcode = new QRCode(typeNumber, QRCode.ErrorCorrectLevel.H); qrcode.addData(text); qrcode.make(); var width = qrcode.getModuleCount() * sizeMultiplier; var height = qrcode.getModuleCount() * sizeMultiplier; // create canvas element var canvas = document.createElement('canvas'); var scale = 10.0; canvas.width = width * scale; canvas.height = height * scale; canvas.style.width = width + 'px'; canvas.style.height = height + 'px'; var ctx = canvas.getContext('2d'); ctx.scale(scale, scale); // compute tileW/tileH based on width/height var tileW = width / qrcode.getModuleCount(); var tileH = height / qrcode.getModuleCount(); // draw in the canvas for (var row = 0; row < qrcode.getModuleCount() ; row++) { for (var col = 0; col < qrcode.getModuleCount() ; col++) { ctx.fillStyle = qrcode.isDark(row, col) ? "#000000" : "#ffffff"; ctx.fillRect(col * tileW, row * tileH, tileW, tileH); } } // return just built canvas return canvas; }, // show QRCodes with canvas // parameter: keyValuePair // example: { "id1": "string1", "id2": "string2"} // "id1" is the id of a div element where you want a QRCode inserted. // "string1" is the string you want encoded into the QRCode. showQrCode: function (keyValuePair, sizeMultiplier) { for (var key in keyValuePair) { var value = keyValuePair[key]; try { if (document.getElementById(key)) { document.getElementById(key).innerHTML = ""; document.getElementById(key).appendChild(qrC.createCanvas(value, sizeMultiplier)); } } catch (e) { } } } }; })(ninja);
mit
m-enochroot/websync
client/app/admin/admin.controller.ts
350
'use strict'; (function() { class AdminController { constructor(User) { // Use the User $resource to fetch all users this.users = User.query(); } delete(user) { user.$remove(); this.users.splice(this.users.indexOf(user), 1); } } angular.module('gatewayApp.admin') .controller('AdminController', AdminController); })();
mit
workshare/swaggable
spec/swaggable/rack_response_adapter_spec.rb
1331
require_relative '../spec_helper' RSpec.describe Swaggable::RackResponseAdapter do let(:subject_class) { Swaggable::RackResponseAdapter } subject { subject_class.new rack_request } let(:rack_request) { [200, {}, []] } describe '#content_type' do it 'returns CONTENT_TYPE' do rack_request[1]['Content-Type'] = 'application/xml' expect(subject.content_type).to eq 'application/xml' end it 'can be set' do subject.content_type = 'application/xml' expect(subject.content_type).to eq 'application/xml' end end describe '#code' do it 'returns the request status code' do rack_request[0] = 418 expect(subject.code).to eq 418 end it 'can be set' do subject.code = 418 expect(subject.code).to eq 418 end end describe '#==' do it 'equals by rack request' do subject_1 = subject_class.new([418, {some: :header}, ['some body']]) subject_2 = subject_class.new([418, {some: :header}, ['some body']]) subject_3 = subject_class.new([418, {some: :header}, ['different body']]) expect(subject_1 == subject_2).to be true expect(subject_1 == subject_3).to be false end it 'doesn\'t throw error if comparing with any random object' do expect{ subject == double }.not_to raise_error end end end
mit
elize1979/AzureKeyVaultExplorer
Vault/Explorer/SettingsDialog.Designer.cs
16213
namespace Microsoft.Vault.Explorer { partial class SettingsDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.TabControl uxTabControl; this.uxTabPageOptions = new System.Windows.Forms.TabPage(); this.uxPropertyGrid = new System.Windows.Forms.PropertyGrid(); this.uxTabPageAbout = new System.Windows.Forms.TabPage(); this.uxTextBoxLicense = new System.Windows.Forms.TextBox(); this.uxLinkLabelUserSettingsLocation = new System.Windows.Forms.LinkLabel(); this.uxTextBoxVersions = new System.Windows.Forms.TextBox(); this.uxLinkLabelInstallLocation = new System.Windows.Forms.LinkLabel(); this.uxLinkLabelClearTokenCache = new System.Windows.Forms.LinkLabel(); this.uxLinkLabelSendFeedback = new System.Windows.Forms.LinkLabel(); this.label2 = new System.Windows.Forms.Label(); this.uxLinkLabelTitle = new System.Windows.Forms.LinkLabel(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.uxButtonCancel = new System.Windows.Forms.Button(); this.uxButtonOK = new System.Windows.Forms.Button(); uxTabControl = new System.Windows.Forms.TabControl(); uxTabControl.SuspendLayout(); this.uxTabPageOptions.SuspendLayout(); this.uxTabPageAbout.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // uxTabControl // uxTabControl.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); uxTabControl.Controls.Add(this.uxTabPageOptions); uxTabControl.Controls.Add(this.uxTabPageAbout); uxTabControl.Location = new System.Drawing.Point(12, 12); uxTabControl.Name = "uxTabControl"; uxTabControl.SelectedIndex = 0; uxTabControl.Size = new System.Drawing.Size(521, 566); uxTabControl.TabIndex = 0; // // uxTabPageOptions // this.uxTabPageOptions.Controls.Add(this.uxPropertyGrid); this.uxTabPageOptions.Location = new System.Drawing.Point(4, 25); this.uxTabPageOptions.Name = "uxTabPageOptions"; this.uxTabPageOptions.Padding = new System.Windows.Forms.Padding(3); this.uxTabPageOptions.Size = new System.Drawing.Size(513, 537); this.uxTabPageOptions.TabIndex = 0; this.uxTabPageOptions.Text = "Options"; this.uxTabPageOptions.UseVisualStyleBackColor = true; // // uxPropertyGrid // this.uxPropertyGrid.Dock = System.Windows.Forms.DockStyle.Fill; this.uxPropertyGrid.Location = new System.Drawing.Point(3, 3); this.uxPropertyGrid.Name = "uxPropertyGrid"; this.uxPropertyGrid.PropertySort = System.Windows.Forms.PropertySort.Categorized; this.uxPropertyGrid.Size = new System.Drawing.Size(507, 531); this.uxPropertyGrid.TabIndex = 0; this.uxPropertyGrid.ToolbarVisible = false; // // uxTabPageAbout // this.uxTabPageAbout.BackColor = System.Drawing.SystemColors.Window; this.uxTabPageAbout.Controls.Add(this.uxTextBoxLicense); this.uxTabPageAbout.Controls.Add(this.uxLinkLabelUserSettingsLocation); this.uxTabPageAbout.Controls.Add(this.uxTextBoxVersions); this.uxTabPageAbout.Controls.Add(this.uxLinkLabelInstallLocation); this.uxTabPageAbout.Controls.Add(this.uxLinkLabelClearTokenCache); this.uxTabPageAbout.Controls.Add(this.uxLinkLabelSendFeedback); this.uxTabPageAbout.Controls.Add(this.label2); this.uxTabPageAbout.Controls.Add(this.uxLinkLabelTitle); this.uxTabPageAbout.Controls.Add(this.pictureBox1); this.uxTabPageAbout.Location = new System.Drawing.Point(4, 25); this.uxTabPageAbout.Name = "uxTabPageAbout"; this.uxTabPageAbout.Padding = new System.Windows.Forms.Padding(3); this.uxTabPageAbout.Size = new System.Drawing.Size(513, 537); this.uxTabPageAbout.TabIndex = 1; this.uxTabPageAbout.Text = "About"; // // uxTextBoxLicense // this.uxTextBoxLicense.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.uxTextBoxLicense.Location = new System.Drawing.Point(6, 386); this.uxTextBoxLicense.Multiline = true; this.uxTextBoxLicense.Name = "uxTextBoxLicense"; this.uxTextBoxLicense.ReadOnly = true; this.uxTextBoxLicense.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.uxTextBoxLicense.Size = new System.Drawing.Size(501, 145); this.uxTextBoxLicense.TabIndex = 7; // // uxLinkLabelUserSettingsLocation // this.uxLinkLabelUserSettingsLocation.AutoSize = true; this.uxLinkLabelUserSettingsLocation.Location = new System.Drawing.Point(6, 205); this.uxLinkLabelUserSettingsLocation.Name = "uxLinkLabelUserSettingsLocation"; this.uxLinkLabelUserSettingsLocation.Size = new System.Drawing.Size(156, 17); this.uxLinkLabelUserSettingsLocation.TabIndex = 4; this.uxLinkLabelUserSettingsLocation.TabStop = true; this.uxLinkLabelUserSettingsLocation.Text = "User settings location..."; this.uxLinkLabelUserSettingsLocation.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.uxLinkLabelUserSettingsLocation_LinkClicked); // // uxTextBoxVersions // this.uxTextBoxVersions.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.uxTextBoxVersions.BackColor = System.Drawing.SystemColors.Window; this.uxTextBoxVersions.BorderStyle = System.Windows.Forms.BorderStyle.None; this.uxTextBoxVersions.Location = new System.Drawing.Point(9, 264); this.uxTextBoxVersions.Multiline = true; this.uxTextBoxVersions.Name = "uxTextBoxVersions"; this.uxTextBoxVersions.ReadOnly = true; this.uxTextBoxVersions.Size = new System.Drawing.Size(498, 116); this.uxTextBoxVersions.TabIndex = 6; this.uxTextBoxVersions.Text = "Version: x.x.x.x"; // // uxLinkLabelInstallLocation // this.uxLinkLabelInstallLocation.AutoSize = true; this.uxLinkLabelInstallLocation.Location = new System.Drawing.Point(6, 182); this.uxLinkLabelInstallLocation.Name = "uxLinkLabelInstallLocation"; this.uxLinkLabelInstallLocation.Size = new System.Drawing.Size(109, 17); this.uxLinkLabelInstallLocation.TabIndex = 3; this.uxLinkLabelInstallLocation.TabStop = true; this.uxLinkLabelInstallLocation.Text = "Install location..."; this.uxLinkLabelInstallLocation.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.uxLinkLabelInstallLocation_LinkClicked); // // uxLinkLabelClearTokenCache // this.uxLinkLabelClearTokenCache.AutoSize = true; this.uxLinkLabelClearTokenCache.Location = new System.Drawing.Point(6, 229); this.uxLinkLabelClearTokenCache.Name = "uxLinkLabelClearTokenCache"; this.uxLinkLabelClearTokenCache.Size = new System.Drawing.Size(170, 17); this.uxLinkLabelClearTokenCache.TabIndex = 5; this.uxLinkLabelClearTokenCache.TabStop = true; this.uxLinkLabelClearTokenCache.Text = "Clear access token cache"; this.uxLinkLabelClearTokenCache.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.uxLinkLabelClearTokenCache_LinkClicked); // // uxLinkLabelSendFeedback // this.uxLinkLabelSendFeedback.AutoSize = true; this.uxLinkLabelSendFeedback.Location = new System.Drawing.Point(6, 145); this.uxLinkLabelSendFeedback.Name = "uxLinkLabelSendFeedback"; this.uxLinkLabelSendFeedback.Size = new System.Drawing.Size(342, 17); this.uxLinkLabelSendFeedback.TabIndex = 2; this.uxLinkLabelSendFeedback.TabStop = true; this.uxLinkLabelSendFeedback.Text = "Like it, Questions or Comments? Send us feedback..."; this.uxLinkLabelSendFeedback.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.uxLinkLabelSendFeedback_LinkClicked); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(6, 83); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(290, 51); this.label2.TabIndex = 1; this.label2.Text = "Copyright (c) 2018 Microsoft Corporation\r\n\r\n"; // // uxLinkLabelTitle // this.uxLinkLabelTitle.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.uxLinkLabelTitle.Font = new System.Drawing.Font("Segoe UI", 13.8F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.uxLinkLabelTitle.Location = new System.Drawing.Point(76, 6); this.uxLinkLabelTitle.Name = "uxLinkLabelTitle"; this.uxLinkLabelTitle.Size = new System.Drawing.Size(380, 64); this.uxLinkLabelTitle.TabIndex = 0; this.uxLinkLabelTitle.TabStop = true; this.uxLinkLabelTitle.Text = "Azure Key Vault Explorer"; this.uxLinkLabelTitle.TextAlign = System.Drawing.ContentAlignment.MiddleCenter; this.uxLinkLabelTitle.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.uxLinkLabelTitle_LinkClicked); // // pictureBox1 // this.pictureBox1.Image = global::Microsoft.Vault.Explorer.Properties.Resources.BigKey; this.pictureBox1.Location = new System.Drawing.Point(6, 6); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(64, 64); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.pictureBox1.TabIndex = 0; this.pictureBox1.TabStop = false; // // uxButtonCancel // this.uxButtonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.uxButtonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.uxButtonCancel.Location = new System.Drawing.Point(432, 585); this.uxButtonCancel.Margin = new System.Windows.Forms.Padding(4); this.uxButtonCancel.Name = "uxButtonCancel"; this.uxButtonCancel.Size = new System.Drawing.Size(100, 28); this.uxButtonCancel.TabIndex = 3; this.uxButtonCancel.Text = "Cancel"; this.uxButtonCancel.UseVisualStyleBackColor = true; // // uxButtonOK // this.uxButtonOK.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Right))); this.uxButtonOK.DialogResult = System.Windows.Forms.DialogResult.OK; this.uxButtonOK.Enabled = false; this.uxButtonOK.Location = new System.Drawing.Point(324, 585); this.uxButtonOK.Margin = new System.Windows.Forms.Padding(4); this.uxButtonOK.Name = "uxButtonOK"; this.uxButtonOK.Size = new System.Drawing.Size(100, 28); this.uxButtonOK.TabIndex = 2; this.uxButtonOK.Text = "OK"; this.uxButtonOK.UseVisualStyleBackColor = true; this.uxButtonOK.Click += new System.EventHandler(this.uxButtonOK_Click); // // SettingsDialog // this.AcceptButton = this.uxButtonOK; this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.uxButtonCancel; this.ClientSize = new System.Drawing.Size(545, 626); this.Controls.Add(uxTabControl); this.Controls.Add(this.uxButtonCancel); this.Controls.Add(this.uxButtonOK); this.MinimizeBox = false; this.MinimumSize = new System.Drawing.Size(500, 550); this.Name = "SettingsDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Show; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Settings"; uxTabControl.ResumeLayout(false); this.uxTabPageOptions.ResumeLayout(false); this.uxTabPageAbout.ResumeLayout(false); this.uxTabPageAbout.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.Button uxButtonCancel; private System.Windows.Forms.Button uxButtonOK; private System.Windows.Forms.PropertyGrid uxPropertyGrid; private System.Windows.Forms.TabPage uxTabPageOptions; private System.Windows.Forms.TabPage uxTabPageAbout; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.LinkLabel uxLinkLabelTitle; private System.Windows.Forms.TextBox uxTextBoxVersions; private System.Windows.Forms.LinkLabel uxLinkLabelInstallLocation; private System.Windows.Forms.LinkLabel uxLinkLabelClearTokenCache; private System.Windows.Forms.LinkLabel uxLinkLabelSendFeedback; private System.Windows.Forms.Label label2; private System.Windows.Forms.LinkLabel uxLinkLabelUserSettingsLocation; private System.Windows.Forms.TextBox uxTextBoxLicense; } }
mit
JoostvanPinxten/tsplib-parser
parser/location.hh
5367
// A Bison parser, made by GNU Bison 3.0. // Locations for Bison parsers in C++ // Copyright (C) 2002-2013 Free Software Foundation, Inc. // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. // As a special exception, you may create a larger work that contains // part or all of the Bison parser skeleton and distribute that work // under terms of your choice, so long as that work isn't itself a // parser generator using the skeleton or a modified version thereof // as a parser skeleton. Alternatively, if you modify or redistribute // the parser skeleton itself, you may (at your option) remove this // special exception, which will cause the skeleton and the resulting // Bison output files to be licensed under the GNU General Public // License without this special exception. // This special exception was added by the Free Software Foundation in // version 2.2 of Bison. /** ** \file ..\..\..\cph-tsp\parser\parser/location.hh ** Define the TSPLIB::location class. */ #ifndef YY_YY_CPH_TSP_PARSER_PARSER_LOCATION_HH_INCLUDED # define YY_YY_CPH_TSP_PARSER_PARSER_LOCATION_HH_INCLUDED # include "position.hh" #line 38 "..\\..\\..\\cph-tsp\\parser\\parser\\tsplib.y" // location.cc:291 namespace TSPLIB { #line 46 "..\\..\\..\\cph-tsp\\parser\\parser/location.hh" // location.cc:291 /// Abstract a location. class location { public: /// Construct a location from \a b to \a e. location (const position& b, const position& e) : begin (b) , end (e) { } /// Construct a 0-width location in \a p. explicit location (const position& p = position ()) : begin (p) , end (p) { } /// Construct a 0-width location in \a f, \a l, \a c. explicit location (std::string* f, unsigned int l = 1u, unsigned int c = 1u) : begin (f, l, c) , end (f, l, c) { } /// Initialization. void initialize (std::string* f = YY_NULL, unsigned int l = 1u, unsigned int c = 1u) { begin.initialize (f, l, c); end = begin; } /** \name Line and Column related manipulators ** \{ */ public: /// Reset initial location to final location. void step () { begin = end; } /// Extend the current location to the COUNT next columns. void columns (int count = 1) { end += count; } /// Extend the current location to the COUNT next lines. void lines (int count = 1) { end.lines (count); } /** \} */ public: /// Beginning of the located region. position begin; /// End of the located region. position end; }; /// Join two location objects to create a location. inline location operator+ (location res, const location& end) { res.end = end.end; return res; } /// Change end position in place. inline location& operator+= (location& res, int width) { res.columns (width); return res; } /// Change end position. inline location operator+ (location res, int width) { return res += width; } /// Change end position in place. inline location& operator-= (location& res, int width) { return res += -width; } /// Change end position. inline location operator- (const location& begin, int width) { return begin + -width; } /// Compare two location objects. inline bool operator== (const location& loc1, const location& loc2) { return loc1.begin == loc2.begin && loc1.end == loc2.end; } /// Compare two location objects. inline bool operator!= (const location& loc1, const location& loc2) { return !(loc1 == loc2); } /** \brief Intercept output stream redirection. ** \param ostr the destination output stream ** \param loc a reference to the location to redirect ** ** Avoid duplicate information. */ template <typename YYChar> inline std::basic_ostream<YYChar>& operator<< (std::basic_ostream<YYChar>& ostr, const location& loc) { unsigned int end_col = 0 < loc.end.column ? loc.end.column - 1 : 0; ostr << loc.begin// << "(" << loc.end << ") " ; if (loc.end.filename && (!loc.begin.filename || *loc.begin.filename != *loc.end.filename)) ostr << '-' << loc.end.filename << ':' << loc.end.line << '.' << end_col; else if (loc.begin.line < loc.end.line) ostr << '-' << loc.end.line << '.' << end_col; else if (loc.begin.column < end_col) ostr << '-' << end_col; return ostr; } #line 38 "..\\..\\..\\cph-tsp\\parser\\parser\\tsplib.y" // location.cc:291 } // TSPLIB #line 187 "..\\..\\..\\cph-tsp\\parser\\parser/location.hh" // location.cc:291 #endif // !YY_YY_CPH_TSP_PARSER_PARSER_LOCATION_HH_INCLUDED
mit
jerimum-bug-tracker/jerimum
features/screens/favorites_screen.rb
2229
class FavoritesScreen def initialize(browser) @browser = browser @home_favorites = @browser.a(text: "Favorites") @add_favorites = @browser.is(text: "star_border") @remove_favorites = @browser.is(text: "grade") #PROJECT #@project_title_home = @browser.ul(index: 0).li.div(class: "collapsible-header").span(index: 0).text @project_title_favorites = @browser.table(index: 1).tbody.tr(index: 0).td(index: 0).a @project_remove_favorites = @browser.table(index: 1).tbody.tr(index: 0).td(index: 1).a #BUG #@bug_title_home = @browser.div(class: "index_bug").tbody.tr(index: 0).td(index: 1).text @bug_title_favorites = @browser.table(index: 0).tbody.tr(index: 0).td(index: 0).a @bug_remove_favorites = @browser.table(index: 0).tbody.tr(index: 0).td(index: 1).a end def home_favorites @home_favorites.click end #BUG def add_bug_favorites @add_favorites.first.click end def verify_add_bug_favorites added = @browser.text.include?('Bug has been added to the Favorites') title_home = @browser.div(class: "index_bug").tbody.tr(index: 0).td(index: 1).text home_favorites title_favorites = @bug_title_favorites.text [added, title_home == title_favorites] end def remove_bug_favorites @bug_remove_favorites.click @browser.alert.ok end def verify_remove_bug_favorites @browser.text.include?('Bug has been removed from Favorites') end #PROJECT def add_project_favorites @add_favorites.first.click end def verify_add_project_favorites added = @browser.text.include?('Project has been added to the Favorites') title_home = @browser.ul(index: 0).li.div(class: "collapsible-header").span(index: 0).text home_favorites title_favorites = @project_title_favorites.text [added, title_home == title_favorites] end def remove_project_favorites @project_remove_favorites.click @browser.alert.ok end def verify_remove_project_favorites @browser.text.include?('Project has been removed from Favorites') end end
mit
couchbaselabs/mini-hacks
android-rating-app/android/app/src/main/java/com/couchbase/ratingapp/StorageManager.java
4469
package com.couchbase.ratingapp; import android.content.Context; import android.util.Log; import com.couchbase.lite.CouchbaseLiteException; import com.couchbase.lite.Database; import com.couchbase.lite.Emitter; import com.couchbase.lite.Manager; import com.couchbase.lite.Mapper; import com.couchbase.lite.Reducer; import com.couchbase.lite.View; import com.couchbase.lite.android.AndroidContext; import com.couchbase.lite.listener.Credentials; import com.couchbase.lite.listener.LiteListener; import com.couchbase.lite.replicator.Replication; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import Acme.Serve.Main; public class StorageManager { static private String stringURL = "http://178.62.162.87:4984/ratingapp"; static public String UNIQUE_RATINGS_VIEW = "byUniqueRating"; static public String USER_RATINGS_VIEW = "byUserRating"; int LISTENER_PORT = 55000; Manager manager; Database database; Replication syncGatewayPull; Replication syncGatewayPush; Replication peerPull; Replication peerPush; URL url; public StorageManager(Context context) { try { /** Enable logging in the application for all tags */ Manager.enableLogging("RatingApp", Log.VERBOSE); manager = new Manager(new AndroidContext(context), Manager.DEFAULT_OPTIONS); } catch (IOException e) { e.printStackTrace(); } try { database = manager.getDatabase("ratingapp"); } catch (CouchbaseLiteException e) { e.printStackTrace(); } registerViews(); continuousReplications(); startListener(); } /** * Register the views when the database is fist opened. */ private void registerViews() { View ratingsView = database.getView(UNIQUE_RATINGS_VIEW); ratingsView.setMapReduce(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { if (document.get("type").equals("unique")) { emitter.emit(document.get("rating").toString(), null); } } }, new Reducer() { @Override public Object reduce(List<Object> keys, List<Object> values, boolean rereduce) { return new Integer(values.size()); } }, "16"); View userRatingsView = database.getView(USER_RATINGS_VIEW); userRatingsView.setMap(new Mapper() { @Override public void map(Map<String, Object> document, Emitter emitter) { if (document.get("type").equals("conflict")) { emitter.emit((String) document.get("_id"), null); } } }, "4"); } /** * Start push/pull replications with Sync Gateway. */ private void continuousReplications() { try { url = new URL(stringURL); } catch (MalformedURLException e) { e.printStackTrace(); } syncGatewayPush = database.createPushReplication(url); syncGatewayPush.setContinuous(true); syncGatewayPush.start(); syncGatewayPull = database.createPullReplication(url); syncGatewayPull.setContinuous(true); syncGatewayPull.start(); } public void stopSyncGatewayReplications() { syncGatewayPull.stop(); syncGatewayPush.stop(); } public void startSyncGatewayReplications() { syncGatewayPull.start(); syncGatewayPush.start(); } /** * Perform one shot pull and push replications. * @param targetStringURL The string URL of the remote database */ public void oneShotReplication(String targetStringURL) { try { url = new URL(targetStringURL); } catch (MalformedURLException e) { e.printStackTrace(); } peerPush = database.createPushReplication(url); peerPull = database.createPullReplication(url); peerPush.start(); peerPull.start(); } /** * Start the Couchbase Lite Listener without any credentials for this demo. */ private void startListener() { LiteListener listener = new LiteListener(manager, LISTENER_PORT, new Credentials("", "")); listener.start(); } }
mit
reinforced/Reinforced.Lattice.Samples
Reinforced.Lattice.CaseStudies.Formwatcher/doc/loading-overlap.cs
184
// Configure loading overlap to overlap all table layout // and also elements having filterColumn class conf.LoadingOverlap(ui => ui.Overlap(OverlapMode.All).Overlap(".filterColumn"));
mit
rheoli/SDX
lib/goliath/rack/validation/required_param.rb
1858
require 'goliath/rack/validator' module Goliath module Rack module Validation # A middleware to validate that a given parameter is provided. # # @example # use Goliath::Rack::Validation::RequiredParam, {:key => 'mode', :type => 'Mode'} # class RequiredParam include Goliath::Rack::Validator attr_reader :type, :key, :message # Creates the Goliath::Rack::Validation::RequiredParam validator # # @param app The app object # @param opts [Hash] The validator options # @option opts [String] :key The key to look for in params (default: id) # @option opts [String] :type The type string to put in the error message. (default: :key) # @option opts [String] :message The message string to display after the type string. (default: 'identifier missing') # @return [Goliath::Rack::Validation::RequiredParam] The validator def initialize(app, opts = {}) @app = app @key = opts[:key] || 'id' @type = opts[:type] || @key.capitalize @message = opts[:message] || 'identifier missing' end def call(env) return validation_error(400, "#{@type} #{@message}") unless key_valid?(env['params']) @app.call(env) end def key_valid?(params) if !params.has_key?(key) || params[key].nil? || (params[key].is_a?(String) && params[key] =~ /^\s*$/) return false end if params[key].is_a?(Array) unless params[key].compact.empty? params[key].each do |k| return true unless k.is_a?(String) return true unless k =~ /^\s*$/ end end return false end true end end end end end
mit
VIPShare/VIPShare
src/screens/RecommendScreen/RecommendScreen/index.style.js
508
import { width, size, colors } from '../../../theme'; export default { banner: { container: { flexDirection: 'row', }, image: { width, height: 220, resizeMode: 'contain', }, }, content: { container: { paddingTop: 20, paddingLeft: 20, paddingRight: 20, }, title: { fontSize: size.xlg, color: colors.normal, paddingBottom: 20, }, info: { fontSize: size.md, color: colors.secFonts, }, }, }
mit
internsaccount/ovfwrapper
Properties/Settings.Designer.cs
1098
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GUI_OVFTOOL.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
mit
MalucoMarinero/react-wastage-monitor
npm/index.js
3212
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.default = function (React, ReactDOM) { var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {}; var WastageTesterMounting = function (_React$Component) { _inherits(WastageTesterMounting, _React$Component); function WastageTesterMounting() { _classCallCheck(this, WastageTesterMounting); return _possibleConstructorReturn(this, (WastageTesterMounting.__proto__ || Object.getPrototypeOf(WastageTesterMounting)).apply(this, arguments)); } _createClass(WastageTesterMounting, [{ key: 'componentDidMount', value: function componentDidMount() { (0, _htmlChecker2.default)(this._reactInternalInstance.constructor.prototype, this.props.options); (0, _reuseChecker2.default)(this._reactInternalInstance.constructor.prototype, this.props.options); } }, { key: 'render', value: function render() { return React.createElement('div', { className: 'WastageTesterMounting' }); } }]); return WastageTesterMounting; }(React.Component); console.log('%cReact Wastage Tester Mounting', 'font-weight: bold;'); var div = document.createElement('div'); document.body.appendChild(div); var out = ReactDOM.render(React.createElement(WastageTesterMounting, { options: options }), div); ReactDOM.unmountComponentAtNode(div); }; var _htmlChecker = require('./htmlChecker'); var _htmlChecker2 = _interopRequireDefault(_htmlChecker); var _reuseChecker = require('./reuseChecker'); var _reuseChecker2 = _interopRequireDefault(_reuseChecker); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
mit
tiagoamaro/sapos
db/migrate/20131118160144_add_workload_to_courses.rb
262
# Copyright (c) Universidade Federal Fluminense (UFF). # This file is part of SAPOS. Please, consult the license terms in the LICENSE file. class AddWorkloadToCourses < ActiveRecord::Migration def change add_column :courses, :workload, :integer end end
mit
neyko5/mtgslo
config/admin/formats.php
846
<?php return array( 'form'=>array( 'fields' => array( array( 'type' => 'text', 'name' => 'name', 'label' => 'Name' ), ), 'controls' => array( 'save', ) ), "list"=>array( 'fields' => array( 'id' => array( 'title' => '#' ), 'name' => array( 'title' => 'Name' ), ), 'options' => array( 'edit', 'delete' ), 'order'=>array( array( "column"=>0, "direction"=>"desc" ) ) ), );
mit
griffithsh/sqlite-squish
cmd/sqlite-squish/doc.go
530
/* command sqlite-squish provides an interface to convert between SQL statements in plain-text *.sql files and sqlite databases. Given a sqlite database called `database.sqlite3`, it is possible to decompose it to a series of text files like this: sqlite3 database.sqlite3 .dump | sqlite-squish -v -out-dir ./database.sql Given a directory of .sql files called `database.sql`, it is possible to compose those files into a sqlite database like this: sqlite-squish -in database.sql | sqlite3 database.sqlite3 */ package main
mit
eemebarbe/schemeBeam
public/js/vendors.js
757
!function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={exports:{},id:n,loaded:!1};return e[n].call(a.exports,a,a.exports,t),a.loaded=!0,a.exports}var n=window.webpackJsonp;window.webpackJsonp=function(o,p){for(var l,c,s=0,i=[];s<o.length;s++)c=o[s],a[c]&&i.push.apply(i,a[c]),a[c]=0;for(l in p)Object.prototype.hasOwnProperty.call(p,l)&&(e[l]=p[l]);for(n&&n(o,p);i.length;)i.shift().call(null,t);if(p[0])return r[0]=0,t(0)};var r={},a={1:0};t.e=function(e,n){if(0===a[e])return n.call(null,t);if(void 0!==a[e])a[e].push(n);else{a[e]=[n];var r=document.getElementsByTagName("head")[0],o=document.createElement("script");o.type="text/javascript",o.charset="utf-8",o.async=!0,o.src=t.p+""+e+".bundle.js",r.appendChild(o)}},t.m=e,t.c=r,t.p="/"}([]);
mit
datasift/served
src/served/mux/matchers.test.cpp
3416
/* * Copyright (C) MediaSift Ltd. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <test/catch.hpp> #include <served/mux/matchers.hpp> TEST_CASE("segment matchers compile and parsing", "[matchers]") { SECTION("compile_to_matcher") { served::mux::segment_matcher_ptr matcher; matcher = served::mux::compile_to_matcher(""); CHECK(dynamic_cast<served::mux::empty_matcher *>(matcher.get())); matcher = served::mux::compile_to_matcher("text"); CHECK(dynamic_cast<served::mux::static_matcher *>(matcher.get())); matcher = served::mux::compile_to_matcher("{variable}"); CHECK(dynamic_cast<served::mux::variable_matcher *>(matcher.get())); matcher = served::mux::compile_to_matcher("{variable:regex}"); CHECK(dynamic_cast<served::mux::regex_matcher *>(matcher.get())); } SECTION("empty_matcher") { std::string segment = ""; auto matcher = served::mux::compile_to_matcher(segment); CHECK(dynamic_cast<served::mux::empty_matcher *>(matcher.get())); CHECK(matcher->check_match("")); CHECK(matcher->check_match("notempty")); CHECK(matcher->check_match(" ")); CHECK(matcher->check_match("things.html")); } SECTION("static_matcher") { std::string segment = "static_text_123"; auto matcher = served::mux::compile_to_matcher(segment); CHECK(dynamic_cast<served::mux::static_matcher *>(matcher.get())); CHECK( matcher->check_match("static_text_123")); CHECK(!matcher->check_match("not_the_same")); CHECK(!matcher->check_match(" ")); CHECK(!matcher->check_match("static_text_321")); CHECK(!matcher->check_match("")); CHECK( matcher->check_match("static_text_123")); } SECTION("variable_matcher") { std::string segment = "{value}"; auto matcher = served::mux::compile_to_matcher(segment); CHECK(dynamic_cast<served::mux::variable_matcher *>(matcher.get())); CHECK( matcher->check_match("static_text_123")); CHECK( matcher->check_match("another_text")); CHECK( matcher->check_match("this_is_also")); CHECK(!matcher->check_match("")); } SECTION("regex_matcher") { std::string segment = "{value:[0-9]*}"; auto matcher = served::mux::compile_to_matcher(segment); CHECK(dynamic_cast<served::mux::regex_matcher *>(matcher.get())); CHECK( matcher->check_match("1337")); CHECK( matcher->check_match("1969")); CHECK(!matcher->check_match("11!!oneone")); CHECK(!matcher->check_match(" 11 ")); } }
mit
DaanHaaz/TypeFighter
ending.js
1878
Ending = Class.extend("Ending"); Ending.init = function () { baa.graphics.setBackgroundColor(0,0,0); this.keys = Object.keys(WORDS); this.start = 0; this.otherStart = 0; this.percentage = (Game.listOfWords.length/this.keys.length)*100; this.percentage = Math.floor(this.percentage*10000)/10000; } Ending.update = function () { if (!baa.keyboard.isDown(" ")) { this.start += 10; this.start = Math.min(this.start,this.keys.length-19); this.otherStart += dt; this.otherStart = Math.min(this.otherStart,Math.max(0,Game.listOfWords.length-19)); } // a += dt; } Ending.draw = function () { baa.graphics.setFont(Game.fonts.typeSmall); baa.graphics.print("THE END","center",250,125,10); for (var i = this.start; i < this.start + 19; i++) { if (WORDS[this.keys[i]]) { baa.graphics.setColor(255,255,255); } else { baa.graphics.setColor(255,0,0); } baa.graphics.print(this.keys[i],2,5+(i-this.start)*7); } for (var i = Math.floor(this.otherStart); i < Math.floor(this.otherStart) + 21; i++) { if (Game.listOfWords[i]) { baa.graphics.print(Game.listOfWords[i],"right",250,248,2+(i-this.otherStart)*7); } } baa.graphics.print("You used","center",250,125,30); baa.graphics.print(this.percentage + "%" ,"center",250,125,40); baa.graphics.print("of the dictionary","center",250,125,50); baa.graphics.print('Made by Daniël "Sheepolution" Haazen',"center",250,125,80); baa.graphics.print('For Ludum Dare #32',"center",250,125,90); baa.graphics.print('Theme: An Unconventional Weapon',"center",250,125,100); baa.graphics.print('Thanks for playing!',"center",250,125,115); baa.graphics.print("@sheepolution | www.sheepolution.com","center",250,125,130); baa.graphics.setColor(255,255,255); // baa.graphics.circle("fill",a); } Ending.keypressed = function (key) { if (key == "return") { game.state = Menu.new(); } }
mit
qoomon/domain-value
src/main/java/com/qoomon/domainvalue/type/BigDecimalDV.java
767
package com.qoomon.domainvalue.type; import java.math.BigDecimal; public abstract class BigDecimalDV extends ComparableDV<BigDecimal> { protected BigDecimalDV(final BigDecimal value) { super(value); } protected BigDecimalDV(final String stringValue) { this(new BigDecimal(stringValue)); } protected static boolean isValid(final BigDecimal value) { return ComparableDV.isValid(value); } /** * @param stringValue * to parse * @return true if valid, else false */ public static boolean isValid(final String stringValue) { try { return isValid(new BigDecimal(stringValue)); } catch (Exception exception) { return false; } } }
mit
vihoangson/LearningEnglish
application/config/autoload.php
3902
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array(); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in system/libraries/ or your | application/libraries/ directory, with the addition of the | 'database' library, which is somewhat of a special case. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array("database"); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in system/libraries/ or in your | application/libraries/ directory, but are also placed inside their | own subdirectory and they extend the CI_Driver_Library class. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array("url","le"); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array(); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array();
mit
staabm/After
lib/Promisor.php
2211
<?php namespace After; /** * A Promisor is a contract to resolve a value at some point in the future * * The After\Promisor is NOT the same as the common JavaScript "promise" idiom. Instead, * After defines a "Promise" as an internal agreement made by producers of asynchronous * results to fulfill a placeholder "Future" value at some point in the future. In this * regard an After\Promise has more in common with the Scala promise API than JavaScript * implementations. * * A Promisor resolves its associated Future placeholder with a value using the succeed() * method. Conversely, a Promisor reports Future failure by passing an Exception to its * Promisor::failure() method. * * Example: * * function myAsyncProducer() { * // Create a new promise that needs to be resolved * $promise = new After\Promise; * * // When we eventually finish non-blocking value resolution we * // simply call the relevant Promise method to notify any code * // with references to the Future: * // $promise->succeed($value) -or- $promise->fail($error) * * return $promise->getFuture(); * } * */ interface Promisor { /** * Retrieve the Future value bound to this Promisor * * @return After\Future */ public function getFuture(); /** * Resolve the Promisor's bound Future as a success * * @param mixed $value */ public function succeed($value = NULL); /** * Resolve the Promisor's bound Future as a failure * * @param \Exception $error * @return void */ public function fail(\Exception $error); /** * Resolve the Promisor's bound Future * * @param \Exception $error * @param mixed $value */ public function resolve(\Exception $error = NULL, $value = NULL); /** * Resolve the Promisor's Future but only if it has not already resolved * * This method allows promise holders to resolve the bound Future without throwing an exception * if the Future has previously resolved. * * @param \Exception $error * @param mixed $value */ public function resolveSafely(\Exception $error = NULL, $value = NULL); }
mit
webcaetano/phaser-boilerplate
src/scripts/preload.js
577
var utils = require('utils'); var _ = require('lodash'); var Phaser = require('phaser'); var {scope,game,craft} = require('./main'); var assets = { images:{ phaser:'images/phaser-dude.png' }, sprites:{}, audio:{}, atlas:{} } var scope = {}; module.exports = function(){ var state = {}; state.init = function(){ } state.preload = function(){ game.stage.disableVisibilityChange = false; game.stage.backgroundColor = '#fff'; utils.loadAssets(game,assets); game.load.start(); } state.create = function(){ game.state.start('game'); } return state; }
mit
zyphrus/Akaro
Engine/graphics/drawable.cpp
1239
/* * drawable.cpp * * Created on: 15/10/2013 * Author: drb */ #include "drawable.h" namespace graphics { drawable::drawable() { //Set the rectangle to be (0,0,0,0) this->pos.x = 0; this->pos.y = 0; this->area.x = 0; this->area.y = 0; this->area.w = 0; this->area.h = 0; this->adjust_camera = false; } void drawable::setPosition ( SDL_Point pos ) { this->pos.x = pos.x; this->pos.y = pos.y; this->area.x = pos.x; this->area.y = pos.y; } void drawable::setPosition ( maths::Point pos ) { this->pos.x = pos.x; this->pos.y = pos.y; this->area.x = ( int )pos.x; this->area.y = ( int )pos.y; } void drawable::changePosition ( Ldouble x , Ldouble y ) { this->pos.x += x; this->pos.y += y; this->area.x = ( int )pos.x; this->area.y = ( int )pos.y; } void drawable::setPosition ( Ldouble x , Ldouble y ) { this->pos.x = x; this->pos.y = y; this->area.x = ( int )pos.x; this->area.y = ( int )pos.y; } SDL_Rect drawable::getRect () { return this->area; } maths::Point drawable::getPosition () { return this->pos; } void drawable::setAdjustCamera( bool var ) { this->adjust_camera = var; } drawable::~drawable() { } } /* namespace graphics */
mit
vrezin/bookcase-test
src/main/java/com/hc/bookcase/book/tmp/repository/TMPRepository.java
504
package com.hc.bookcase.book.tmp.repository; import com.hc.bookcase.book.tmp.model.TMPBookEntity; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.repository.NoRepositoryBean; @NoRepositoryBean public interface TMPRepository<T extends TMPBookEntity> extends JpaRepository<T, Long> { //Iterable<T> findAllOrderByName(); //@Query("select t from #{#entityName} t where t.child is null order by name") Iterable<T> findByChildIsNullOrderByName(); }
mit
thcmc/th
app/controllers/api.server.controller.js
14995
'use strict'; var secrets = require('../../config/secrets'); var User = require('../models/User'); var querystring = require('querystring'); var validator = require('validator'); var async = require('async'); var cheerio = require('cheerio'); var request = require('request'); var _ = require('underscore'); var graph = require('fbgraph'); var LastFmNode = require('lastfm').LastFmNode; var tumblr = require('tumblr.js'); var foursquare = require('node-foursquare')({ secrets: secrets.foursquare }); /*var Github = require('github-api');*/ var Twit = require('twit'); var paypal = require('paypal-rest-sdk'); var twilio = require('twilio')(secrets.twilio.sid, secrets.twilio.token); var Linkedin = require('node-linkedin')(secrets.linkedin.clientID, secrets.linkedin.clientSecret, secrets.linkedin.callbackURL); var clockwork = require('clockwork')({key: secrets.clockwork.apiKey}); /** * GET /api * List of API examples. */ exports.getApi = function(req, res) { res.render('api/index', { title: 'API Browser' }); }; /** * GET /api/foursquare * Foursquare API example. */ /*exports.getFoursquare = function(req, res, next) { var token = _.findWhere(req.user.tokens, { kind: 'foursquare' }); async.parallel({ trendingVenues: function(callback) { foursquare.Venues.getTrending('40.7222756', '-74.0022724', { limit: 50 }, token.accessToken, function(err, results) { callback(err, results); }); }, venueDetail: function(callback) { foursquare.Venues.getVenue('49da74aef964a5208b5e1fe3', token.accessToken, function(err, results) { callback(err, results); }); }, userCheckins: function(callback) { foursquare.Users.getCheckins('self', null, token.accessToken, function(err, results) { callback(err, results); }); } }, function(err, results) { if (err) return next(err); res.render('api/foursquare', { title: 'Foursquare API', trendingVenues: results.trendingVenues, venueDetail: results.venueDetail, userCheckins: results.userCheckins }); }); };*/ /** * GET /api/tumblr * Tumblr API example. */ exports.getTumblr = function(req, res) { var token = _.findWhere(req.user.tokens, { kind: 'tumblr' }); var client = tumblr.createClient({ consumer_key: secrets.tumblr.consumerKey, consumer_secret: secrets.tumblr.consumerSecret, token: token.accessToken, token_secret: token.tokenSecret }); client.posts('goddess-of-imaginary-light.tumblr.com', { type: 'photo' }, function(err, data) { res.render('api/tumblr', { title: 'Tumblr API', blog: data.blog, photoset: data.posts[0].photos }); }); }; /** * GET /api/facebook * Facebook API example. */ /*exports.getFacebook = function(req, res, next) { var token = _.findWhere(req.user.tokens, { kind: 'facebook' }); graph.setAccessToken(token.accessToken); async.parallel({ getMe: function(done) { graph.get(req.user.facebook, function(err, me) { done(err, me); }); }, getMyFriends: function(done) { graph.get(req.user.facebook + '/friends', function(err, friends) { done(err, friends.data); }); } }, function(err, results) { if (err) return next(err); res.render('api/facebook', { title: 'Facebook API', me: results.getMe, friends: results.getMyFriends }); }); };*/ /** * GET /api/scraping * Web scraping example using Cheerio library. */ exports.getScraping = function(req, res, next) { request.get('https://news.ycombinator.com/', function(err, request, body) { if (err) return next(err); var $ = cheerio.load(body); var links = []; $(".title a[href^='http'], a[href^='https']").each(function() { links.push($(this)); }); res.render('api/scraping', { title: 'Web Scraping', links: links }); }); }; exports.getNHLScrape = function(req, res, next) { request.get('http://www.nhl.com/scores/htmlreports/20132014/GS021140.HTM', function(err, request, body) { if (err) return next(err); var $ = cheerio.load(body); var goalies = []; $("h4:contains(GOALIES:) div[class='scoringInfo'], div[class='scoringInfo']").each(function() { goalies.push($(this)); }); res.render('api/NHLscrape', { title: 'NHL Scraping', goalies: goalies }); }); }; /** * GET /api/github * GitHub API Example. */ /*exports.getGithub = function(req, res) { var token = _.findWhere(req.user.tokens, { kind: 'github' }); var github = new Github({ token: token.accessToken }); var repo = github.getRepo('sahat', 'requirejs-library'); repo.show(function(err, repo) { res.render('api/github', { title: 'GitHub API', repo: repo }); }); };*/ /** * GET /api/aviary * Aviary image processing example. */ exports.getAviary = function(req, res) { res.render('api/aviary', { title: 'Aviary API' }); }; /** * GET /api/nyt * New York Times API example. */ exports.getNewYorkTimes = function(req, res, next) { var query = querystring.stringify({ 'api-key': secrets.nyt.key, 'list-name': 'young-adult' }); var url = 'http://api.nytimes.com/svc/books/v2/lists?' + query; request.get(url, function(error, request, body) { if (request.statusCode === 403) return next(Error('Missing or Invalid New York Times API Key')); var bestsellers = JSON.parse(body); res.render('api/nyt', { title: 'New York Times API', books: bestsellers.results }); }); }; /** * GET /api/lastfm * Last.fm API example. */ exports.getLastfm = function(req, res, next) { var lastfm = new LastFmNode(secrets.lastfm); async.parallel({ artistInfo: function(done) { lastfm.request("artist.getInfo", { artist: 'Epica', handlers: { success: function(data) { done(null, data); }, error: function(err) { done(err); } } }); }, artistTopAlbums: function(done) { lastfm.request("artist.getTopAlbums", { artist: 'Epica', handlers: { success: function(data) { var albums = []; _.each(data.topalbums.album, function(album) { albums.push(album.image.slice(-1)[0]['#text']); }); done(null, albums.slice(0, 4)); }, error: function(err) { done(err); } } }); } }, function(err, results) { if (err) return next(err.message); var artist = { name: results.artistInfo.artist.name, image: results.artistInfo.artist.image.slice(-1)[0]['#text'], tags: results.artistInfo.artist.tags.tag, bio: results.artistInfo.artist.bio.summary, stats: results.artistInfo.artist.stats, similar: results.artistInfo.artist.similar.artist, topAlbums: results.artistTopAlbums }; res.render('api/lastfm', { title: 'Last.fm API', artist: artist }); }); }; /** * GET /api/twitter * Twiter API example. */ /*exports.getTwitter = function(req, res, next) { var token = _.findWhere(req.user.tokens, { kind: 'twitter' }); var T = new Twit({ consumer_key: secrets.twitter.consumerKey, consumer_secret: secrets.twitter.consumerSecret, access_token: token.accessToken, access_token_secret: token.tokenSecret }); T.get('search/tweets', { q: 'hackathon since:2013-01-01', geocode: '40.71448,-74.00598,5mi', count: 50 }, function(err, reply) { if (err) return next(err); res.render('api/twitter', { title: 'Twitter API', tweets: reply.statuses }); }); };*/ /** * GET /api/paypal * PayPal SDK example. */ exports.getPayPal = function(req, res, next) { paypal.configure(secrets.paypal); var paymentDetails = { intent: 'sale', payer: { payment_method: 'paypal' }, redirect_urls: { return_url: secrets.paypal.returnUrl, cancel_url: secrets.paypal.cancelUrl }, transactions: [ { description: 'Node.js Boilerplate', amount: { currency: 'USD', total: '2.99' } } ] }; paypal.payment.create(paymentDetails, function(err, payment) { if (err) return next(err); req.session.paymentId = payment.id; var links = payment.links; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'approval_url') { res.render('api/paypal', { approval_url: links[i].href }); } } }); }; /** * GET /api/paypal/success * PayPal SDK example. */ exports.getPayPalSuccess = function(req, res, next) { var paymentId = req.session.paymentId; var paymentDetails = { 'payer_id': req.query.PayerID }; paypal.payment.execute(paymentId, paymentDetails, function(err, payment) { if (err) { res.render('api/paypal', { result: true, success: false }); } else { res.render('api/paypal', { result: true, success: true }); } }); }; /** * GET /api/paypal/cancel * PayPal SDK example. */ exports.getPayPalCancel = function(req, res, next) { req.session.payment_id = null; res.render('api/paypal', { result: true, canceled: true }); }; /** * GET /api/steam * Steam API example. */ exports.getSteam = function(req, res, next) { var steamId = '76561197982488301'; var query = { l: 'english', steamid: steamId, key: secrets.steam.apiKey }; async.parallel({ playerAchievements: function(done) { query.appid = '49520'; var qs = querystring.stringify(query); request.get({ url: 'http://api.steampowered.com/ISteamUserStats/GetPlayerAchievements/v0001/?' + qs, json: true }, function(error, request, body) { if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key')); done(error, body); }); }, playerSummaries: function(done) { query.steamids = steamId; var qs = querystring.stringify(query); request.get({ url: 'http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?' + qs, json: true }, function(error, request, body) { if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key')); done(error, body); }); }, ownedGames: function(done) { query.include_appinfo = 1; query.include_played_free_games = 1; var qs = querystring.stringify(query); request.get({ url: 'http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?' + qs, json: true }, function(error, request, body) { if (request.statusCode === 401) return done(new Error('Missing or Invalid Steam API Key')); done(error, body); }); } }, function(err, results) { if (err) return next(err); res.render('api/steam', { title: 'Steam Web API', ownedGames: results.ownedGames.response.games, playerAchievemments: results.playerAchievements.playerstats, playerSummary: results.playerSummaries.response.players[0] }); }); }; /** * GET /api/twilio * Twilio API example. */ exports.getTwilio = function(req, res, next) { res.render('api/twilio', { title: 'Twilio API' }); }; /** * POST /api/twilio * Twilio API example. * @param telephone */ exports.postTwilio = function(req, res, next) { var message = { to: req.body.telephone, from: '+13472235148', body: 'Hello from the Hackathon Starter' }; twilio.sendMessage(message, function(err, responseData) { if (err) return next(err.message); req.flash('success', { msg: 'Text sent to ' + responseData.to + '.'}) res.redirect('/api/twilio'); }); }; /** * GET /api/clockwork * Clockwork SMS API example. */ exports.getClockwork = function(req, res) { res.render('api/clockwork', { title: 'Clockwork SMS API' }); }; /** * POST /api/clockwork * Clockwork SMS API example. * @param telephone */ exports.postClockwork = function(req, res, next) { var message = { To: req.body.telephone, From: 'Hackathon', Content: 'Hello from the Hackathon Starter' }; clockwork.sendSms(message, function(err, responseData) { if (err) return next(err.errDesc); req.flash('success', { msg: 'Text sent to ' + responseData.responses[0].to }); res.redirect('/api/clockwork'); }); }; /** * GET /api/venmo * Venmo API example. */ exports.getVenmo = function(req, res, next) { var token = _.findWhere(req.user.tokens, { kind: 'venmo' }); var query = querystring.stringify({ access_token: token.accessToken }); async.parallel({ getProfile: function(done) { request.get({ url: 'https://api.venmo.com/v1/me?' + query, json: true }, function(err, request, body) { done(err, body); }); }, getRecentPayments: function(done) { request.get({ url: 'https://api.venmo.com/v1/payments?' + query, json: true }, function(err, request, body) { done(err, body); }); } }, function(err, results) { if (err) return next(err); res.render('api/venmo', { title: 'Venmo API', profile: results.getProfile.data, recentPayments: results.getRecentPayments.data }); }); }; /** * POST /api/venmo * @param user * @param note * @param amount * Send money. */ exports.postVenmo = function(req, res, next) { req.assert('user', 'Phone, Email or Venmo User ID cannot be blank').notEmpty(); req.assert('note', 'Please enter a message to accompany the payment').notEmpty(); req.assert('amount', 'The amount you want to pay cannot be blank').notEmpty(); var errors = req.validationErrors(); if (errors) { req.flash('errors', errors); return res.redirect('/api/venmo'); } var token = _.findWhere(req.user.tokens, { kind: 'venmo' }); var formData = { access_token: token.accessToken, note: req.body.note, amount: req.body.amount }; if (validator.isEmail(req.body.user)) { formData.email = req.body.user; } else if (validator.isNumeric(req.body.user) && validator.isLength(req.body.user, 10, 11)) { formData.phone = req.body.user; } else { formData.user_id = req.body.user; } request.post('https://api.venmo.com/v1/payments', { form: formData }, function(err, request, body) { if (err) return next(err); if (request.statusCode !== 200) { req.flash('errors', { msg: JSON.parse(body).error.message }); return res.redirect('/api/venmo'); } req.flash('success', { msg: 'Venmo money transfer complete' }); res.redirect('/api/venmo'); }); }; /** * GET /api/linkedin * LinkedIn API example. */ /*exports.getLinkedin = function(req, res, next) { var token = _.findWhere(req.user.tokens, { kind: 'linkedin' }); var linkedin = Linkedin.init(token.accessToken); linkedin.people.me(function(err, $in) { if (err) return next(err); res.render('api/linkedin', { title: 'LinkedIn API', profile: $in }); }); };*/
mit
mr-uuid/snippets
python/sockets/clients/async_client.py
688
import errno import socket def asyn_client(ip='localhost', port=8080): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect(ip, port) sock.setblocking(0) try: new_data = sock.recv(1024) except socket.error, e: if e.args[0] == errno.EWOULDBLOCK: # This error code means we would have blocked if the socket was # blocking. Instead of blocking, we would atempt to itterate # through all the sockets we have. break else: if not new_data: break else: data += new_data return data print asyn_client() print asyn_client() print asyn_client()
mit
mk-prg-net/mk-prg-net.lib
ATMO.mko.Logging/Monitoring/JobMonitoringConsole.cs
6182
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections.Concurrent; using TechTerms = ATMO.mko.Logging.PNDocuTerms.DocuEntities.Composer.TechTerms; using static ATMO.mko.Logging.PNDocuTerms.DocuEntities.ComposerSubTrees; namespace ATMO.mko.Logging.Monitoring { /// <summary> /// Implementierung einer einfachen Jobverwaltung /// </summary> public class JobMonitoringConsole : IJobMonitoring, IJobMonitoringConsole { public JobMonitoringConsole(PNDocuTerms.DocuEntities.IComposer pnL) { this.pnL = pnL; } PNDocuTerms.DocuEntities.IComposer pnL; long _nextJobId = 1; ConcurrentQueue<Job> _newJobQueue = new ConcurrentQueue<Job>(); ConcurrentDictionary<long, Job> _Jobs = new ConcurrentDictionary<long, Job>(); public RCV3sV<IEnumerable<IJob>> Jobs => RCV3sV<IEnumerable<IJob>>.Ok(_Jobs.Select(r => r.Value)); public RCV3 abortJob(long JobId) { var ret = RCV3.Failed(pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3.Failed(JobIdNotFound(JobId)); } else { _Jobs[JobId].State = JobState.aborted; ret = RCV3.Ok(); } return ret; } public RCV3sV<JobState> continueJob(long JobId) { var ret = RCV3sV<JobState>.Failed(JobState.none, pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3sV<JobState>.Failed(JobState.aborted,JobIdNotFound(JobId)); } else if (_Jobs[JobId].State == JobState.aborted) { ret = RCV3sV<JobState>.Failed(JobState.aborted, JobAbortedMsg(JobId)); } else { _Jobs[JobId].State = JobState.running; ret = RCV3sV<JobState>.Ok(_Jobs[JobId].State); } return ret; } private PNDocuTerms.DocuEntities.IDocuEntity JobIdNotFound(long JobId) { return pnL.i("JobList", pnL.m("get", pnL.p("JobId", pnL.txt(JobId.ToString())), pnL.ret(pnL.eFails(pnL.txt("NotFound"))))); } public RCV3sV<JobState> deregisterJob(long JobId) { var ret = RCV3sV<JobState>.Failed(value: JobState.none, ErrorDescription: pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3sV<JobState>.Failed(JobState.aborted, JobIdNotFound(JobId)); } if(_Jobs[JobId].State == JobState.running) { ret = RCV3sV<JobState>.Failed(value: _Jobs[JobId].State, pnL.ReturnValidatePreconditionFailed( pnL.m(TechTerms.RelationalOperators.mNotEq, pnL.p(TechTerms.MetaData.Arg, TechTerms.StateMachine.State), pnL.p(TechTerms.MetaData.Val, JobState.running.ToString())))); } else { _Jobs.TryRemove(JobId, out Job job); job.State = JobState.completed; ret = RCV3sV<JobState>.Ok(job.State); } return ret; } public RCV3sV<long> registerJob(string title, long estimatedEffort) { var job = new Job(); job.JobId = System.Threading.Interlocked.Increment(ref _nextJobId); job.EstimatedEffort = estimatedEffort; job.Title = title; job.Created = DateTime.Now; _Jobs[job.JobId] = job; return RCV3sV<long>.Ok(job.JobId); } public RCV3sV<JobState> reportProgess(long JobId, long progress) { var ret = RCV3sV<JobState>.Failed(value: JobState.none, ErrorDescription: pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3sV<JobState>.Failed(JobState.aborted, JobIdNotFound(JobId)); } else if (_Jobs[JobId].State == JobState.aborted) { ret = RCV3sV<JobState>.Failed(JobState.aborted, JobAbortedMsg(JobId)); } else { var job = _Jobs[JobId]; job.CurrentProgress += progress; ret = RCV3sV<JobState>.Ok(job.State); } return ret; } public RCV3sV<JobState> stopJob(long JobId) { var ret = RCV3sV<JobState>.Failed(JobState.none, pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3sV<JobState>.Failed(JobState.none, JobIdNotFound(JobId)); } else if (_Jobs[JobId].State == JobState.aborted) { ret = RCV3sV<JobState>.Failed(_Jobs[JobId].State, JobAbortedMsg(JobId)); } else { _Jobs[JobId].State = JobState.stopped; ret = RCV3sV<JobState>.Ok(_Jobs[JobId].State); } return ret; } private PNDocuTerms.DocuEntities.IDocuEntity JobAbortedMsg(long JobId) { return pnL.i("Job", pnL.p("JobId", pnL.txt(JobId.ToString())), pnL.p("State", pnL.txt("aborted"))); } public RCV3sV<JobState> completeJob(long JobId) { var ret = RCV3sV<JobState>.Failed(value: JobState.none, pnL.eFails()); if (!_Jobs.ContainsKey(JobId)) { ret = RCV3sV<JobState>.Failed(JobState.none, JobIdNotFound(JobId)); } else if (_Jobs[JobId].State == JobState.aborted) { ret = RCV3sV<JobState>.Failed(_Jobs[JobId].State, JobAbortedMsg(JobId)); } else { _Jobs[JobId].State = JobState.completed; ret = RCV3sV<JobState>.Ok(_Jobs[JobId].State); } return ret; } } }
mit
Grizzlybeardesignltd/davidcullimore
page-templates/investment.php
5525
<?php /* Template Name: Investment Template */ get_header(); ?> <?php echo get_template_part('parts/content', 'banner'); ?> <section id="content" class="os-animation animated fadeIn"> <?php while (have_posts()) : the_post(); ?> <div class="row"> <div class="medium-5 columns rightCenter"> <h1><?php the_title();?></h1> <?php the_field('package_price');?> </div> <div class="medium-6 medium-offset-1 columns"> <?php the_field('package_information');?> </div> </div> <div class="row"> <div class="large-12 columns"> <svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" class="margTop90" width="100%" height="100%" viewBox="0 0 1581.96 410.873" enable-background="new 0 0 1581.96 410.873" xml:space="preserve"> <g> <g> <defs> <polygon id="SVGID_1_" points="275.86,0 507.106,411.479 734.947,0 "/> </defs> <clipPath id="SVGID_2_"> <use xlink:href="#SVGID_1_" overflow="visible"/> </clipPath> <g clip-path="url(#SVGID_2_)"> <defs> <rect id="SVGID_3_" x="221.538" y="-7.152" width="712.859" height="475.17"/> </defs> <clipPath id="SVGID_4_"> <use xlink:href="#SVGID_3_" overflow="visible"/> </clipPath> <g transform="matrix(1 0 0 1 0 9.536743e-007)" clip-path="url(#SVGID_4_)"> <?php $image = get_field('image_1'); $size = "large"; ?> <image xlink:href="<?php echo $image['sizes'][ $size ]; ?>" x="-13%" y="0" width="100%" height="100%"> </image> </g> </g> </g> <g> <defs> <polygon id="SVGID_5_" points="835.832,0 1067.078,411.479 1294.92,0 "/> </defs> <clipPath id="SVGID_6_"> <use xlink:href="#SVGID_5_" overflow="visible"/> </clipPath> <g clip-path="url(#SVGID_6_)"> <defs> <rect id="SVGID_7_" x="694.676" y="-56.754" width="710.197" height="473.398"/> </defs> <clipPath id="SVGID_8_"> <use xlink:href="#SVGID_7_" overflow="visible"/> </clipPath> <g transform="matrix(1 0 0 1 -6.103516e-005 0)" clip-path="url(#SVGID_8_)"> <?php $image = get_field('image_2'); $size = "large"; ?> <image xlink:href="<?php echo $image['sizes'][ $size ]; ?>" x="42%" y="-20%" width="786px" height="524px" > </image> </g> </g> </g> <polygon fill="#F47821" points="778.682,410.873 778.682,225.195 659.951,225.195 557.43,410.873 "/> <polygon fill="#161C34" points="1012.207,410.873 909.685,225.195 790.955,225.195 790.955,410.873 "/> <polygon fill="#8FD3D2" points="905.989,214.383 666.802,214.383 785.509,0 "/> <polygon fill="#161C34" points="458.387,410.852 0,410.852 227.493,0 "/> <polygon fill="#161C34" points="1581.96,410.852 1123.572,410.852 1351.065,0 "/> </g> </svg> <div class="clear"></div> <!-- <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg-triangle-big"> <defs> <pattern id="img2" patternUnits="userSpaceOnUse" width="400" height="400"> <image xlink:href="<?php the_field('image_2'); ?>" x="0" y="0" width="400" height="400" /> </pattern> </defs> <polygon points="200,330 0,0 400,0" fill="url(#img2)"/> </svg><div class="clear"></div> --> </div> </div> <?php endwhile; rewind_posts(); ?> </section> <?php echo get_template_part('parts/content', 'get-in-touch-cta'); ?> <?php get_footer(); ?>
mit
pbanaszkiewicz/amy
amy/trainings/filters.py
4915
import re from django.db.models import Q from django.forms import widgets import django_filters from workshops.fields import ModelSelect2Widget from workshops.filters import AMYFilterSet, NamesOrderingFilter from workshops.forms import SELECT2_SIDEBAR from workshops.models import Event, Person def filter_all_persons(queryset, name, all_persons): """Filter only trainees when all_persons==False.""" if all_persons: return queryset else: return queryset.filter( task__role__name="learner", task__event__tags__name="TTT" ).distinct() def filter_trainees_by_trainee_name_or_email(queryset, name, value): if value: # 'Harry Potter' -> ['Harry', 'Potter'] tokens = re.split(r"\s+", value) # Each token must match email address or github username or personal or # family name. for token in tokens: queryset = queryset.filter( Q(personal__icontains=token) | Q(family__icontains=token) | Q(email__icontains=token) ) return queryset else: return queryset def filter_trainees_by_unevaluated_homework_presence(queryset, name, flag): if flag: # return only trainees with an unevaluated homework return queryset.filter(trainingprogress__state="n").distinct() else: return queryset def filter_trainees_by_training_request_presence(queryset, name, flag): if flag is None: return queryset elif flag is True: # return only trainees who submitted training request return queryset.filter(trainingrequest__isnull=False).distinct() else: # return only trainees who did not submit training request return queryset.filter(trainingrequest__isnull=True) def filter_trainees_by_instructor_status(queryset, name, choice): if choice == "all": return queryset.filter( is_swc_instructor=True, is_dc_instructor=True, is_lc_instructor=True, ) elif choice == "any": return queryset.filter( Q(is_swc_instructor=True) | Q(is_dc_instructor=True) | Q(is_lc_instructor=True) ) elif choice == "swc": return queryset.filter(is_swc_instructor=True) elif choice == "dc": return queryset.filter(is_dc_instructor=True) elif choice == "lc": return queryset.filter(is_lc_instructor=True) elif choice == "eligible": # Instructor eligible but without any badge. # This code is kept in Q()-expressions to allow for fast condition # change. return queryset.filter(Q(instructor_eligible__gte=1) & Q(is_instructor=False)) elif choice == "no": return queryset.filter( is_instructor=False, ) else: return queryset def filter_trainees_by_training(queryset, name, training): if training is None: return queryset else: return queryset.filter( task__role__name="learner", task__event=training ).distinct() class TraineeFilter(AMYFilterSet): search = django_filters.CharFilter( method=filter_trainees_by_trainee_name_or_email, label="Name or Email" ) all_persons = django_filters.BooleanFilter( label="Include all people, not only trainees", method=filter_all_persons, widget=widgets.CheckboxInput, ) homework = django_filters.BooleanFilter( label="Only trainees with unevaluated homework", widget=widgets.CheckboxInput, method=filter_trainees_by_unevaluated_homework_presence, ) training_request = django_filters.BooleanFilter( label="Is training request present?", method=filter_trainees_by_training_request_presence, ) is_instructor = django_filters.ChoiceFilter( label="Is Instructor?", method=filter_trainees_by_instructor_status, choices=[ ("", "Unknown"), ("all", "All instructor badges"), ("any", "Any instructor badge "), ("swc", "SWC instructor"), ("dc", "DC instructor"), ("lc", "LC instructor"), ("eligible", "No, but eligible to be certified"), ("no", "No instructor badge"), ], ) training = django_filters.ModelChoiceFilter( queryset=Event.objects.ttt(), method=filter_trainees_by_training, label="Training", widget=ModelSelect2Widget( data_view="ttt-event-lookup", attrs=SELECT2_SIDEBAR, ), ) order_by = NamesOrderingFilter( fields=( "last_login", "email", ), ) class Meta: model = Person fields = [ "search", "all_persons", "homework", "is_instructor", "training", ]
mit
Pihta-Open-Data/TransportNocturnal
src/main/java/ru/pihta/nocturnaltransport/model/LocalTimePersistenceConverter.java
519
package ru.pihta.nocturnaltransport.model; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.sql.Time; import java.time.LocalTime; @Converter public class LocalTimePersistenceConverter implements AttributeConverter<LocalTime, Time> { @Override public Time convertToDatabaseColumn(LocalTime localTime) { return Time.valueOf(localTime); } @Override public LocalTime convertToEntityAttribute(Time time) { return time.toLocalTime(); } }
mit
katajakasa/Raidcal
raidcal/maincal/migrations/0004_auto_20151114_2029.py
2451
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import datetime from django.utils.timezone import utc import tinymce.models from django.conf import settings class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('maincal', '0003_auto_20151110_1008'), ] operations = [ migrations.CreateModel( name='Message', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('time', models.DateTimeField(default=datetime.datetime(2015, 11, 14, 18, 29, 55, 206000, tzinfo=utc), verbose_name='Sent')), ('description', tinymce.models.HTMLField(verbose_name='Event description')), ], options={ 'verbose_name': 'Message', 'verbose_name_plural': 'Messages', }, ), migrations.CreateModel( name='Topic', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('time', models.DateTimeField(verbose_name='Created')), ('title', models.CharField(max_length=32)), ('user', models.ForeignKey(verbose_name='Creator', to=settings.AUTH_USER_MODEL)), ], options={ 'verbose_name': 'Topic', 'verbose_name_plural': 'Topics', }, ), migrations.AlterModelOptions( name='event', options={'verbose_name': 'Event', 'verbose_name_plural': 'Events'}, ), migrations.AlterModelOptions( name='participation', options={'verbose_name': 'Participation', 'verbose_name_plural': 'Participations'}, ), migrations.AlterModelOptions( name='sitedecoration', options={'verbose_name': 'Site decoration', 'verbose_name_plural': 'Site decorations'}, ), migrations.AddField( model_name='message', name='topic', field=models.ForeignKey(to='maincal.Topic'), ), migrations.AddField( model_name='message', name='user', field=models.ForeignKey(verbose_name='User', to=settings.AUTH_USER_MODEL), ), ]
mit
adonisjs/adonis-sink
test/json-file.spec.ts
2297
/* * @adonisjs/sink * * (c) Harminder Virk <virk@adonisjs.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ import test from 'japa' import { join } from 'path' import { Filesystem } from '@poppinss/dev-utils' import { JsonFile } from '../src/Files/Formats/Json' const fs = new Filesystem(join(__dirname, '__app')) test.group('Json file', (group) => { group.afterEach(async () => { await fs.cleanup() }) group.beforeEach(async () => { await fs.ensureRoot() }) test('create json file', async (assert) => { const file = new JsonFile(fs.basePath, 'foo.json') file.set('appName', 'hello-world') file.commit() const contents = await fs.get('foo.json') assert.deepEqual(JSON.parse(contents), { appName: 'hello-world' }) }) test('update json file', async (assert) => { await fs.add('foo.json', JSON.stringify({ appName: 'hello-world', version: '1.0' })) const file = new JsonFile(fs.basePath, 'foo.json') file.set('appName', 'hello-universe') file.unset('version') file.commit() const contents = await fs.get('foo.json') assert.deepEqual(JSON.parse(contents), { appName: 'hello-universe' }) }) test('delete json file', async (assert) => { await fs.add('foo.json', JSON.stringify({ appName: 'hello-world', version: '1.0' })) const file = new JsonFile(fs.basePath, 'foo.json') file.delete() const hasFile = await fs.fsExtra.pathExists('foo.json') assert.isFalse(hasFile) }) test('undo constructive commits on rollback', async (assert) => { await fs.add('foo.json', JSON.stringify({ appName: 'hello-world' })) const file = new JsonFile(fs.basePath, 'foo.json') file.set('appName', 'hello-world') file.rollback() const contents = await fs.get('foo.json') assert.deepEqual(JSON.parse(contents), {}) }) test('do not touch destructive commits on rollbacks', async (assert) => { await fs.add('foo.json', JSON.stringify({ appName: 'hello-world' })) const file = new JsonFile(fs.basePath, 'foo.json') file.unset('appName') file.rollback() const contents = await fs.get('foo.json') assert.deepEqual(JSON.parse(contents), { appName: 'hello-world' }) }) })
mit
SlashGames/slash-framework
Source/Slash.Unity.Common/Source/Input/Handlers/IDragOverHandler.cs
278
namespace Slash.Unity.Common.Input.Handlers { using UnityEngine.EventSystems; public interface IDragOverHandler : IEventSystemHandler { #region Public Methods and Operators void OnDragOver(PointerEventData eventData); #endregion } }
mit
cinder14/echosign_sdk_csharp
Source/Cinder14.EchoSign/Endpoints/LibraryDocumentEndpoint.cs
998
using Cinder14.EchoSign.Models; using RestSharp; using System.Threading.Tasks; namespace Cinder14.EchoSign.Endpoints { public class LibraryDocumentEndpoint : EndpointBase { public LibraryDocumentEndpoint(EchoSignSDK api) : base(api) { } /// <summary> /// Retrieves library documents for a user /// </summary> public virtual DocumentLibraryItems GetAll() { var request = new RestRequest(Method.GET); request.Resource = "libraryDocuments"; return this.Sdk.Execute<DocumentLibraryItems>(request); } /// <summary> /// Retrieves library documents for a user /// </summary> public virtual Task<DocumentLibraryItems> GetAllAsync() { var request = new RestRequest(Method.GET); request.Resource = "libraryDocuments"; return this.Sdk.ExecuteAsync<DocumentLibraryItems>(request); } } }
mit
TheCheat/CTRev
include/classes/class.attachments.php
10493
<?php /** * Project: CTRev * @file include/classes/class.attachments.php * * @page http://ctrev.cyber-tm.ru/ * @copyright (c) 2008-2012, Cyber-Team * @author The Cheat <cybertmdev@gmail.com> * @name Реализация вложений * @version 1.00 */ if (!defined('INSITE')) die('Remote access denied!'); class attachments extends pluginable_object { /** * Префикс в имени файла вложений, хранимых на сервере */ const attach_prefix = "a"; /** * Статус системы вложений * @var bool $state */ protected $state = true; /** * ID последнего вложения * @var int $curid */ protected $curid = 0; /** * Данный тип вложений * @var type $type */ protected $type = "content"; /** * Допустимые типы вложений * @var array $allowed_types */ protected $allowed_types = array('content'); /** * Конструктор класса * @return null */ protected function plugin_construct() { $this->state = (bool) config::o()->mstate('attach_manage'); $this->access_var('allowed_types', PVAR_ADD); /** * @note Добавление вложений(add_attachments) * params: * int toid ID ресурса * string type тип ресурса */ tpl::o()->register_function("add_attachments", array( $this, "add")); /** * @note Отображение вложений(display_attachments) * params: * int toid ID ресурса * string type тип ресурса */ tpl::o()->register_function("display_attachments", array( $this, "display")); } /** * Изменение типа вложений * @param string $type имя типа * @return attachments $this */ public function change_type($type) { if (!in_array($type, $this->allowed_types)) return $this; $this->type = $type; return $this; } /** * Форма загрузки * @param int $toid ID ресурса * @return null */ public function add($toid = null) { if (!$this->state) return; if (is_array($toid)) { if ($toid ['type']) $this->change_type($toid ['type']); $toid = $toid['toid']; } try { users::o()->perm_exception()->check_perms('attach', 2); } catch (EngineException $e) { n("message")->stype('error')->info($e->getEMessage()); return; } $type = $this->type; $toid = (int) $toid; $postfix = self::attach_prefix . $this->curid . $type; if ($toid) { $rows = db::o()->p($toid, $type)->query("SELECT id, filename FROM attachments WHERE toid = ? AND type = ?"); tpl::o()->assign('attachments', db::o()->fetch2array($rows)); } tpl::o()->assign('postfix_att', $postfix); tpl::o()->display("attachments/list.tpl"); display::o()->uploadify($postfix, "", "", array( "module" => "attach_manage", "act" => "upload", "type" => $type, "toid" => $toid), "attach_add", true, false); $this->curid++; } /** * Присвоение вложению ресурса * @param array $data массив данных * @param int $toid ID ресурса * @return bool true, в случае успешного выполнения */ public function define_toid($data, $toid) { if (!$this->state) return; if (!users::o()->perm('attach', 2) || !users::o()->v()) return; $id = $data ["attachments"]; if (!$id) return; $toid = (int) $toid; $where = (!is_array($id) ? 'id = ?' : 'id IN (@' . count($id) . '?)'); $where .= ' AND toid = 0 AND user = ?'; return db::o()->p($id, users::o()->v("id"))->update(array( "toid" => $toid, "type" => $this->type), "attachments", 'WHERE ' . $where); } /** * Загрузка вложения * @param int $toid ID ресурса * @param string $files_var ключ для массива $_FILES * @return int ID вложения * @throws EngineException */ public function upload($toid = null, $files_var = "Filedata") { if (!$this->state) return; users::o()->check_perms('attach', 2); lang::o()->get("file"); if (!$files_var) $files_var = "Filedata"; $type = $this->type; /* @var $uploader uploader */ $uploader = n("uploader"); $toid = (int) $toid; $time = timer(true); $user = users::o()->v('id'); $new_name = self::attach_prefix . default_filename($time, $user); $filesize = @filesize($_FILES [$files_var] ['tmp_name']); $uploader->upload_preview(config::o()->v("attachpreview_folder"), "", true); $uploader->upload($_FILES [$files_var], config::o()->v("attachments_folder"), $filetype, $new_name, true); $preview = $uploader->get_preview(); $insert = array( "filename" => display::o()->html_encode($_FILES [$files_var] ['name']), // Автоматически не экранируется 'preview' => $preview, "size" => $filesize, "time" => $time, "ftype" => $filetype, "toid" => $toid, "type" => $type, "user" => $user); try { plugins::o()->pass_data(array("insert" => &$insert), true)->run_hook('attachments_upload'); } catch (PReturn $e) { return $e->r(); } $id = db::o()->insert($insert, "attachments"); return $id; } /** * Отображение вложений для данного ресурса * @param int $toid ID ресурса * @return null */ public function display($toid) { if (!$this->state) return; if (is_array($toid)) { if ($toid["type"]) $this->change_type($toid["type"]); $toid = $toid["toid"]; } if (!users::o()->perm('attach', 1, 2)) return; $type = $this->type; $toid = (int) $toid; $rows = db::o()->p($toid, $type)->query("SELECT a.*, aft.image AS ftimage FROM attachments AS a LEFT JOIN allowed_ft AS aft ON aft.name=a.ftype WHERE toid = ? AND type=?"); tpl::o()->assign('attach_rows', db::o()->fetch2array($rows)); tpl::o()->assign('slbox_mbinited', true); // Инициализовать SexyLightbox tpl::o()->display("attachments/show.tpl"); } /** * Удаление вложения * @param int|array $id ID вложения * @return bool true, в случае успешного выполнения */ public function delete($id) { if (!$this->state) return; users::o()->check_perms('attach', 2); if (!$id) return; $where = (!is_array($id) ? 'id = ?' : 'id IN(@' . count($id) . '?)'); $rows = db::o()->p($id)->query("SELECT * FROM attachments WHERE " . $where); $uf = ROOT . config::o()->v("attachments_folder") . "/" . self::attach_prefix; $ufp = ROOT . config::o()->v("attachpreview_folder") . "/"; while ($row = db::o()->fetch_assoc($rows)) { $type = $row['type']; if (($row ["user"] == users::o()->v("id") && users::o()->perm('edit_' . $type)) || users::o()->perm('edit_' . $type, 2)) { try { plugins::o()->pass_data(array("row" => &$row), true)->run_hook('attachments_delete'); } catch (PReturn $e) { if (!$e->r()) continue; return $e->r(); } $ids [] = $row ["id"]; @unlink($uf . default_filename($row['time'], $row['user'])); @unlink($ufp . $row ["preview"]); } } if ($ids) return db::o()->p($ids)->delete("attachments", 'WHERE id IN(@' . count($ids) . '?)'); } /** * Очистка вложений * @param int $toid ID ресурса * если не указано, то будут удалены все вложения без ресурсов * @param bool $all все? * @return bool true, в случае успешного выполнения */ public function clear($toid = 0, $all = false) { if (!$this->state) return; $toid = (int) $toid; $type = $this->type; $where = $toid ? "toid=? AND type=?" : 'toid=0'; $r = db::o()->p($toid, $type)->query('SELECT id FROM attachments' . (!$all ? ' WHERE ' . $where : '')); $ids = db::o()->fetch2array($r, "assoc", array("id")); return $this->delete($ids); } /** * Скачивание вложения * @param int $id ID вложения * @return null * @throws EngineException */ public function download($id) { if (!$this->state) return; users::o()->check_perms('attach', 1, 2); $id = (int) $id; $q = db::o()->p($id)->query("SELECT * FROM attachments WHERE id=? LIMIT 1"); $row = db::o()->fetch_assoc($q); if (!$row) throw new EngineException('file_not_exists'); $file = config::o()->v("attachments_folder") . "/" . self::attach_prefix . default_filename($row['time'], $row['user']); try { plugins::o()->pass_data(array("row" => &$row))->run_hook('attachments_download'); } catch (PReturn $e) { return $e->r(); } db::o()->p($id)->update(array( "_cb_downloaded" => 'downloaded+1'), "attachments", 'WHERE id = ? LIMIT 1'); /* @var $uploader uploader */ $uploader = n("uploader"); $uploader->download($file, display::o()->html_decode($row ["filename"])); } } ?>
mit
SpartaHack/SpartaHack2016-Windows
2016/SpartaHack/Parse/Public/ParsePushNotificationEventArgs.cs
1387
// Copyright (c) 2015-present, Parse, LLC. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. using System; using System.Collections.Generic; namespace Parse { /// <summary> /// A wrapper around Parse push notification payload. /// </summary> public class ParsePushNotificationEventArgs : EventArgs { internal ParsePushNotificationEventArgs(IDictionary<string, object> payload) { Payload = payload; #if !IOS StringPayload = ParseClient.SerializeJsonString(payload); #endif } // Obj-C type -> .NET type is impossible to do flawlessly (especially // on NSNumber). We can't transform NSDictionary into string because of this reason. #if !IOS internal ParsePushNotificationEventArgs(string stringPayload) { StringPayload = stringPayload; Payload = ParseClient.DeserializeJsonString(stringPayload); } #endif /// <summary> /// The payload of the push notification as <c>IDictionary</c>. /// </summary> public IDictionary<string, object> Payload { get; internal set; } /// <summary> /// The payload of the push notification as <c>string</c>. /// </summary> public string StringPayload { get; internal set; } } }
mit
sonicyang/chiphub
login/migrations/0005_auto_20151108_1213.py
768
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('login', '0004_auto_20151108_1139'), ] operations = [ migrations.AlterField( model_name='login_sessions', name='id', field=models.AutoField(serialize=False, primary_key=True), ), migrations.AlterField( model_name='user_profiles', name='id', field=models.AutoField(serialize=False, primary_key=True), ), migrations.AlterField( model_name='users', name='id', field=models.AutoField(serialize=False, primary_key=True), ), ]
mit
DocuWare/PlatformJavaClient
src/com/docuware/dev/schema/_public/services/platform/Notifications.java
4351
package com.docuware.dev.schema._public.services.platform; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import java.net.URI; import com.docuware.dev.Extensions.*; import java.util.concurrent.CompletableFuture; import java.util.*; import com.docuware.dev.schema._public.services.Link; import com.docuware.dev.schema._public.services.platform.Notifications; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; import com.docuware.dev.schema._public.services.Links; @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Notifications", propOrder = { "proxy", "notification", "links" }) public class Notifications implements IRelationsWithProxy { private HttpClientProxy proxy;//test @XmlElement(name = "Notification") protected List<Notification> notification; @XmlElement(name = "Links", namespace = "http://dev.docuware.com/schema/public/services", required = true) protected Links links; @XmlAttribute(name = "Timeout") protected Integer timeout; /**ArrayList is required for the XML-Marshalling */ public void setNotification(ArrayList<Notification> value) { notification=value; } /**Collection of notifications.*/ public List<Notification> getNotification() { if (notification == null) { notification = new ArrayList<Notification>(); } return this.notification; } public Links getLinks() { return links; } public void setLinks(Links value) { this.links = value; } /**Gets or sets the notifications timeout im milliseconds. A positive value lets the server wait for notifications for the specified amount of time. A value of 0 means that the server should respond immediately. A value of -1 indicates that the server should define the timeout.*/ public int getTimeout() { if (timeout == null) { return -1; } else { return timeout; } } public void setTimeout(Integer value) { this.timeout = value; } /** * Gets the proxy. * * @return The proxy */ @Extension public HttpClientProxy getProxy() { return this.proxy; } /** * Sets the HTTP Communication Proxy which is used in futher HTTP communication. * * @param proxy The new proxy */ @Extension public void setProxy(HttpClientProxy proxy) { this.proxy = proxy; } /** * Gets the base URI of the specified relations instance. * * @return The base URI of the specified relations instance. */ @Extension public URI getBaseUri() { return RelationsWithProxyExtensions.getBaseUri(this); } /** * Gets the Uri of the Link for the relation "Self". * Returns the Uri of the Link for the relation "Self", if this links exists, or null, if this link does not exists. The returned link can be relative or absolute. If it is a relative link you must set it in the right context yourself. * @return the requested URI */ public URI getSelfRelationLink() { return MethodInvocation.getLink(this, links, "self"); } /** * Calls the HTTP Get Method on the link for the relation "Self". */ public Notifications getNotificationsFromSelfRelation() { return MethodInvocation.<Notifications>get(this, links, "self", Notifications.class); } /** * Calls the HTTP Get Method on the link for the relation "Self" asynchronously. */ public CompletableFuture<DeserializedHttpResponseGen<Notifications>> getNotificationsFromSelfRelationAsync() { return MethodInvocation.<Notifications>getAsync(this, links, "self", Notifications.class); } /** * Calls the HTTP Get Method on the link for the relation "Self" asynchronously. */ public CompletableFuture<DeserializedHttpResponseGen<Notifications>> getNotificationsFromSelfRelationAsync(CancellationToken ct) { return MethodInvocation.<Notifications>getAsync(this, links, "self", Notifications.class, ct); } }
mit
Jeroen96/Project-Novus
Oculus/src/app/app-routing/auth-guard.service.ts
458
import { Router, CanActivate } from '@angular/router'; import { LoginService } from './../login/login.service'; import { Injectable } from '@angular/core'; @Injectable() export class AuthGuardService implements CanActivate { constructor(private loginService: LoginService, private router: Router) { } canActivate() { if (this.loginService.checkAccessTokenAvailable()) { return true; } this.router.navigate(['/login']); return false; } }
mit
louistin/fullstack
Python/module/base64_20161020.py
313
#!/usr/bin/python # _*_ coding: utf-8 _*_ import base64 print base64.b64encode('louis%20luna') print base64.b64decode('bG91aXMlMjBsdW5h') # urlsafe的base64 print base64.b64encode('i\xb7\x1d\xfb\xef\xff') print base64.urlsafe_b64encode('i\xb7\x1d\xfb\xef\xff') print repr(base64.urlsafe_b64decode('abcd--__'))
mit
hubrix/acs
db/migrate/20101223204622_add_completed_by_to_access_requests.rb
223
class AddCompletedByToAccessRequests < ActiveRecord::Migration def self.up add_column :access_requests, :completed_by_id, :integer end def self.down remove_column :access_requests, :completed_by_id end end
mit
dev-lucid/container
tests/NewConstructorTest.php
2995
<?php use Lucid\Container\InjectorFactoryContainer; use Lucid\Container\Constructor\Constructor; use Lucid\Container\Constructor\Parameter\Fixed; use Lucid\Container\Constructor\Parameter\Container; use Lucid\Container\Constructor\Parameter\Closure; class NewConstructorTest_class1 { public function testMethod1() { return 'NewConstructorTest_class1->testMethod1()'; } } class NewConstructorTest_class2 { protected $parameter1; public function __construct(string $parameter1) { $this->parameter1 = $parameter1; } public function testMethod2() { return 'parameter1='.$this->parameter1; } } class NewConstructorTest_prefix_class1 { public function testMethod1() { return 'value1'; } } class NewConstructorTest extends \PHPUnit_Framework_TestCase { public $container = null; public function setup() { $this->container = new InjectorFactoryContainer(); $constructor = new Constructor('class1', 'NewConstructorTest_class1'); $this->container->addConstructor($constructor); $constructor = new Constructor('class2', 'NewConstructorTest_class2'); $constructor->addParameter(new Fixed('parameter1', 'value1')); $this->container->addConstructor($constructor); $constructor = new Constructor('class2b', 'NewConstructorTest_class2'); $constructor->addParameter(new Container('parameter1', 'NewConstructorTest_class2b-parameter1')); $this->container->addConstructor($constructor); $this->container->set('NewConstructorTest_class2b-parameter1', 'value2'); $constructor = new Constructor('class2c', 'NewConstructorTest_class2'); $constructor->addParameter(new Closure('parameter1', function(){ return 'value3'; })); $this->container->addConstructor($constructor); $constructor = new Constructor('NewConstructorTest_prefix_'); $this->container->addConstructor($constructor); } public function testBasicConstruct() { $class1 = $this->container->construct('class1'); $this->assertEquals('NewConstructorTest_class1->testMethod1()', $class1->testMethod1()); } public function testFixedParameter() { $class2 = $this->container->construct('class2'); $this->assertEquals('parameter1=value1', $class2->testMethod2()); } public function testContainerParameter() { $class2b = $this->container->construct('class2b'); $this->assertEquals('parameter1=value2', $class2b->testMethod2()); } public function testClosureParameter() { $class2c = $this->container->construct('class2c'); $this->assertEquals('parameter1=value3', $class2c->testMethod2()); } public function testPrefixMatch1() { $prefixObj1= $this->container->construct('NewConstructorTest_prefix_class1'); $this->assertEquals('value1', $prefixObj1->testMethod1()); } }
mit
Ajroudi/behmanager
src/Manager/CommercialBundle/Controller/DefaultController.php
288
<?php namespace Manager\CommercialBundle\Controller; use Symfony\Bundle\FrameworkBundle\Controller\Controller; class DefaultController extends Controller { public function indexAction() { return $this->render('ManagerCommercialBundle:Default:index.html.twig'); } }
mit
ho-ri1991/genetic-programming
include/gp/utility/default_initializer.hpp
428
#ifndef GP_UTILITY_DEFAULT_INITIALIZER #define GP_UTILITY_DEFAULT_INITIALIZER #include <type_traits> namespace gp::utility { //(partial) specialize this class if you want to use other default value template <typename T> struct DefaultInitializer { static T getDefaultValue(){return T{};} }; template <typename T> T getDefaultValue(){return DefaultInitializer<T>::getDefaultValue();} } #endif
mit
mabotech/mabo.io
py/vision/test1/ocr_test.py
1130
import cv2.cv as cv import tesseract import time start = time.time() image=cv.LoadImage("app2.jpg", cv.CV_LOAD_IMAGE_GRAYSCALE) api = tesseract.TessBaseAPI() api.Init("E:\\Tesseract-OCR\\test-slim","eng",tesseract.OEM_DEFAULT) #api.SetPageSegMode(tesseract.PSM_SINGLE_WORD) api.SetPageSegMode(tesseract.PSM_AUTO) tesseract.SetCvImage(image,api) text=api.GetUTF8Text() conf=api.MeanTextConf() image=None print "text:",text print "conf:",conf #api.SetPageSegMode(tesseract.PSM_AUTO) mImgFile = "app3.jpg" result = tesseract.ProcessPagesWrapper(mImgFile,api) print "result(ProcessPagesWrapper)=",result print time.time() - start #api.ProcessPages(mImgFile,None, 0, result) #print "abc" result = tesseract.ProcessPagesFileStream(mImgFile,api) print "result(ProcessPagesFileStream)=",result print time.time() - start result = tesseract.ProcessPagesRaw(mImgFile,api) print "result(ProcessPagesRaw)",result print time.time() - start f=open(mImgFile,"rb") mBuffer=f.read() f.close() result = tesseract.ProcessPagesBuffer(mBuffer,len(mBuffer),api) mBuffer=None print "result(ProcessPagesBuffer)=",result print time.time() - start
mit
dbrumley/recfi
llvm-3.3/tools/clang/test/Analysis/derived-to-base.cpp
9826
// RUN: %clang_cc1 -analyze -analyzer-checker=core,debug.ExprInspection -verify %s // RUN: %clang_cc1 -analyze -analyzer-checker=core,debug.ExprInspection -DCONSTRUCTORS=1 -analyzer-config c++-inlining=constructors -verify %s void clang_analyzer_eval(bool); void clang_analyzer_checkInlined(bool); class A { protected: int x; }; class B : public A { public: void f(); }; void B::f() { x = 3; } class C : public B { public: void g() { // This used to crash because we are upcasting through two bases. x = 5; } }; namespace VirtualBaseClasses { class A { protected: int x; }; class B : public virtual A { public: int getX() { return x; } }; class C : public virtual A { public: void setX() { x = 42; } }; class D : public B, public C {}; class DV : virtual public B, public C {}; class DV2 : public B, virtual public C {}; void test() { D d; d.setX(); clang_analyzer_eval(d.getX() == 42); // expected-warning{{TRUE}} DV dv; dv.setX(); clang_analyzer_eval(dv.getX() == 42); // expected-warning{{TRUE}} DV2 dv2; dv2.setX(); clang_analyzer_eval(dv2.getX() == 42); // expected-warning{{TRUE}} } // Make sure we're consistent about the offset of the A subobject within an // Intermediate virtual base class. class Padding1 { int unused; }; class Padding2 { int unused; }; class Intermediate : public Padding1, public A, public Padding2 {}; class BI : public virtual Intermediate { public: int getX() { return x; } }; class CI : public virtual Intermediate { public: void setX() { x = 42; } }; class DI : public BI, public CI {}; void testIntermediate() { DI d; d.setX(); clang_analyzer_eval(d.getX() == 42); // expected-warning{{TRUE}} } } namespace DynamicVirtualUpcast { class A { public: virtual ~A(); }; class B : virtual public A {}; class C : virtual public B {}; class D : virtual public C {}; bool testCast(A *a) { return dynamic_cast<B*>(a) && dynamic_cast<C*>(a); } void test() { D d; clang_analyzer_eval(testCast(&d)); // expected-warning{{TRUE}} } } namespace DynamicMultipleInheritanceUpcast { class B { public: virtual ~B(); }; class C { public: virtual ~C(); }; class D : public B, public C {}; bool testCast(B *a) { return dynamic_cast<C*>(a); } void test() { D d; clang_analyzer_eval(testCast(&d)); // expected-warning{{TRUE}} } class DV : virtual public B, virtual public C {}; void testVirtual() { DV d; clang_analyzer_eval(testCast(&d)); // expected-warning{{TRUE}} } } namespace LazyBindings { struct Base { int x; }; struct Derived : public Base { int y; }; struct DoubleDerived : public Derived { int z; }; int getX(const Base &obj) { return obj.x; } int getY(const Derived &obj) { return obj.y; } void testDerived() { Derived d; d.x = 1; d.y = 2; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} Derived d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} } void testDoubleDerived() { DoubleDerived d; d.x = 1; d.y = 2; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} Derived d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} DoubleDerived d3(d); clang_analyzer_eval(getX(d3) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d3) == 2); // expected-warning{{TRUE}} } namespace WithOffset { struct Offset { int padding; }; struct OffsetDerived : private Offset, public Base { int y; }; struct DoubleOffsetDerived : public OffsetDerived { int z; }; int getY(const OffsetDerived &obj) { return obj.y; } void testDerived() { OffsetDerived d; d.x = 1; d.y = 2; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} OffsetDerived d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} } void testDoubleDerived() { DoubleOffsetDerived d; d.x = 1; d.y = 2; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} OffsetDerived d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} DoubleOffsetDerived d3(d); clang_analyzer_eval(getX(d3) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d3) == 2); // expected-warning{{TRUE}} } } namespace WithVTable { struct DerivedVTBL : public Base { int y; virtual void method(); }; struct DoubleDerivedVTBL : public DerivedVTBL { int z; }; int getY(const DerivedVTBL &obj) { return obj.y; } int getZ(const DoubleDerivedVTBL &obj) { return obj.z; } void testDerived() { DerivedVTBL d; d.x = 1; d.y = 2; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} #if CONSTRUCTORS DerivedVTBL d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} #endif } #if CONSTRUCTORS void testDoubleDerived() { DoubleDerivedVTBL d; d.x = 1; d.y = 2; d.z = 3; clang_analyzer_eval(getX(d) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d) == 2); // expected-warning{{TRUE}} clang_analyzer_eval(getZ(d) == 3); // expected-warning{{TRUE}} Base b(d); clang_analyzer_eval(getX(b) == 1); // expected-warning{{TRUE}} DerivedVTBL d2(d); clang_analyzer_eval(getX(d2) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d2) == 2); // expected-warning{{TRUE}} DoubleDerivedVTBL d3(d); clang_analyzer_eval(getX(d3) == 1); // expected-warning{{TRUE}} clang_analyzer_eval(getY(d3) == 2); // expected-warning{{TRUE}} clang_analyzer_eval(getZ(d3) == 3); // expected-warning{{TRUE}} } #endif } #if CONSTRUCTORS namespace Nested { struct NonTrivialCopy { int padding; NonTrivialCopy() {} NonTrivialCopy(const NonTrivialCopy &) {} }; struct FullyDerived : private NonTrivialCopy, public Derived { int z; }; struct Wrapper { FullyDerived d; int zz; Wrapper(const FullyDerived &d) : d(d), zz(0) {} }; void test5() { Wrapper w((FullyDerived())); w.d.x = 1; Wrapper w2(w); clang_analyzer_eval(getX(w2.d) == 1); // expected-warning{{TRUE}} } } #endif } namespace Redeclaration { class Base; class Base { public: virtual int foo(); int get() { return value; } int value; }; class Derived : public Base { public: virtual int bar(); }; void test(Derived d) { d.foo(); // don't crash d.bar(); // sanity check Base &b = d; b.foo(); // don't crash d.value = 42; // don't crash clang_analyzer_eval(d.get() == 42); // expected-warning{{TRUE}} clang_analyzer_eval(b.get() == 42); // expected-warning{{TRUE}} } }; namespace PR15394 { namespace Original { class Base { public: virtual int f() = 0; int i; }; class Derived1 : public Base { public: int j; }; class Derived2 : public Derived1 { public: virtual int f() { clang_analyzer_checkInlined(true); // expected-warning{{TRUE}} return i + j; } }; void testXXX() { Derived1 *d1p = reinterpret_cast<Derived1*>(new Derived2); d1p->i = 1; d1p->j = 2; clang_analyzer_eval(d1p->f() == 3); // expected-warning{{TRUE}} } } namespace VirtualInDerived { class Base { public: int i; }; class Derived1 : public Base { public: virtual int f() = 0; int j; }; class Derived2 : public Derived1 { public: virtual int f() { clang_analyzer_checkInlined(true); // expected-warning{{TRUE}} return i + j; } }; void test() { Derived1 *d1p = reinterpret_cast<Derived1*>(new Derived2); d1p->i = 1; d1p->j = 2; clang_analyzer_eval(d1p->f() == 3); // expected-warning{{TRUE}} } } namespace NoCast { class Base { public: int i; }; class Derived1 : public Base { public: virtual int f() = 0; int j; }; class Derived2 : public Derived1 { public: virtual int f() { clang_analyzer_checkInlined(true); // expected-warning{{TRUE}} return i + j; } }; void test() { Derived1 *d1p = new Derived2; d1p->i = 1; d1p->j = 2; clang_analyzer_eval(d1p->f() == 3); // expected-warning{{TRUE}} } } };
mit
edgcarmu/myproject.fcm
assets/libs/formvalidation-dist-v0.6.2/src/js/validator/isin.js
3199
/** * isin validator * * @link http://formvalidation.io/validators/isin/ * @author https://twitter.com/formvalidation * @copyright (c) 2013 - 2015 Nguyen Huu Phuoc * @license http://formvalidation.io/license/ */ (function($) { FormValidation.I18n = $.extend(true, FormValidation.I18n || {}, { 'en_US': { isin: { 'default': 'Please enter a valid ISIN number' } } }); FormValidation.Validator.isin = { // Available country codes // See http://isin.net/country-codes/ COUNTRY_CODES: 'AF|AX|AL|DZ|AS|AD|AO|AI|AQ|AG|AR|AM|AW|AU|AT|AZ|BS|BH|BD|BB|BY|BE|BZ|BJ|BM|BT|BO|BQ|BA|BW|BV|BR|IO|BN|BG|BF|BI|KH|CM|CA|CV|KY|CF|TD|CL|CN|CX|CC|CO|KM|CG|CD|CK|CR|CI|HR|CU|CW|CY|CZ|DK|DJ|DM|DO|EC|EG|SV|GQ|ER|EE|ET|FK|FO|FJ|FI|FR|GF|PF|TF|GA|GM|GE|DE|GH|GI|GR|GL|GD|GP|GU|GT|GG|GN|GW|GY|HT|HM|VA|HN|HK|HU|IS|IN|ID|IR|IQ|IE|IM|IL|IT|JM|JP|JE|JO|KZ|KE|KI|KP|KR|KW|KG|LA|LV|LB|LS|LR|LY|LI|LT|LU|MO|MK|MG|MW|MY|MV|ML|MT|MH|MQ|MR|MU|YT|MX|FM|MD|MC|MN|ME|MS|MA|MZ|MM|NA|NR|NP|NL|NC|NZ|NI|NE|NG|NU|NF|MP|NO|OM|PK|PW|PS|PA|PG|PY|PE|PH|PN|PL|PT|PR|QA|RE|RO|RU|RW|BL|SH|KN|LC|MF|PM|VC|WS|SM|ST|SA|SN|RS|SC|SL|SG|SX|SK|SI|SB|SO|ZA|GS|SS|ES|LK|SD|SR|SJ|SZ|SE|CH|SY|TW|TJ|TZ|TH|TL|TG|TK|TO|TT|TN|TR|TM|TC|TV|UG|UA|AE|GB|US|UM|UY|UZ|VU|VE|VN|VG|VI|WF|EH|YE|ZM|ZW', /** * Validate an ISIN (International Securities Identification Number) * Examples: * - Valid: US0378331005, AU0000XVGZA3, GB0002634946 * - Invalid: US0378331004, AA0000XVGZA3 * * @see http://en.wikipedia.org/wiki/International_Securities_Identifying_Number * @param {FormValidation.Base} validator The validator plugin instance * @param {jQuery} $field Field element * @param {Object} options Can consist of the following keys: * - message: The invalid message * @returns {Boolean} */ validate: function(validator, $field, options) { var value = validator.getFieldValue($field, 'isin'); if (value === '') { return true; } value = value.toUpperCase(); var regex = new RegExp('^(' + this.COUNTRY_CODES + ')[0-9A-Z]{10}$'); if (!regex.test(value)) { return false; } var converted = '', length = value.length; // Convert letters to number for (var i = 0; i < length - 1; i++) { var c = value.charCodeAt(i); converted += ((c > 57) ? (c - 55).toString() : value.charAt(i)); } var digits = '', n = converted.length, group = (n % 2 !== 0) ? 0 : 1; for (i = 0; i < n; i++) { digits += (parseInt(converted[i], 10) * ((i % 2) === group ? 2 : 1) + ''); } var sum = 0; for (i = 0; i < digits.length; i++) { sum += parseInt(digits.charAt(i), 10); } sum = (10 - (sum % 10)) % 10; return sum + '' === value.charAt(length - 1); } }; }(jQuery));
mit
Leko/node-nextengine
Entity/Entity.js
416
class Entity { /** * should convert 'search' to 'info' or not * * @return bool true:should convert, false:should not convert */ static get getAsInfo () { return false } /** * return request path of this API * * path must starts with spash * path must not contain trailing spash * * @return string */ static get path () { return '/' } } module.exports = Entity
mit
Mischa-Alff/cee
plugins/sfml/__init__.py
2336
import plugins.BasePlugin import plugins.CompilerPlugin class Plugin(plugins.CompilerPlugin.CompilerPlugin, object): name = None author = None description = None connection = None def curly_brace_snippet(self, data, extra_args): data["command"] = "int main()\n{" + data["command"] print data return self.snippet(data, extra_args) def stream_snippet(self, data, extra_args): data["command"] = " cout <<" + data["command"] + "; }" print data return self.curly_brace_snippet(data, extra_args) def __init__(self, **kwargs): self.name = "clang" self.author = "Mischa-Alff" self.description = "A C++ evaluation plugin using clang++ and SFML" self.compiler_command = [ "clang++", "-g", "-Wall", "-std=c++1y", "-fmessage-length=0", "-ftemplate-depth-128", "-fno-elide-constructors", "-fstrict-aliasing", "-fstack-protector-all", "-lsfml-graphics", "-lsfml-audio", "-lsfml-network", "-lsfml-window", "-lsfml-system" ] super(Plugin, self).__init__(**kwargs) self.commands.append( plugins.BasePlugin.Command( self.curly_brace_snippet, ["%%prefix%%"], ["sfml {", "sfml{"], { "prefix_files": ["files/template.cpp", "files/sfml.hpp"], "suffix_files": [], "lang_extension": "cpp" } ) ) self.commands.append( plugins.BasePlugin.Command( self.stream_snippet, ["%%prefix%%"], ["sfml<<", "sfml <<"], { "prefix_files": ["files/template.cpp", "files/sfml.hpp"], "suffix_files": [], "lang_extension": "cpp" } ) ) self.commands.append( plugins.BasePlugin.Command( self.snippet, ["%%prefix%%"], ["sfml"], { "prefix_files": ["files/template.cpp", "files/sfml.hpp"], "suffix_files": [], "lang_extension": "cpp" } ) )
mit
danielcaldas/react-d3-graph
src/components/node/node.helper.js
3663
/** * @module Node/helper * @description * Some methods that help no the process of rendering a node. */ import { symbolCircle as d3SymbolCircle, symbolCross as d3SymbolCross, symbolDiamond as d3SymbolDiamond, symbolSquare as d3SymbolSquare, symbolStar as d3SymbolStar, symbolTriangle as d3SymbolTriangle, symbolWye as d3SymbolWye, symbol as d3Symbol, } from "d3-shape"; import CONST from "./node.const"; /** * Converts a string that specifies a symbol into a concrete instance * of d3 symbol.<br/> * {@link https://github.com/d3/d3-shape/blob/master/README.md#symbol} * @param {string} typeName - the string that specifies the symbol type (should be one of {@link #node-symbol-type|node.symbolType}). * @returns {Object} concrete instance of d3 symbol (defaults to circle). * @memberof Node/helper */ function _convertTypeToD3Symbol(typeName) { switch (typeName) { case CONST.SYMBOLS.CIRCLE: return d3SymbolCircle; case CONST.SYMBOLS.CROSS: return d3SymbolCross; case CONST.SYMBOLS.DIAMOND: return d3SymbolDiamond; case CONST.SYMBOLS.SQUARE: return d3SymbolSquare; case CONST.SYMBOLS.STAR: return d3SymbolStar; case CONST.SYMBOLS.TRIANGLE: return d3SymbolTriangle; case CONST.SYMBOLS.WYE: return d3SymbolWye; default: return d3SymbolCircle; } } /** * Build a d3 svg symbol based on passed symbol and symbol type. * @param {number} [size=80] - the size of the symbol. * @param {string} [symbolTypeDesc='circle'] - the string containing the type of symbol that we want to build * (should be one of {@link #node-symbol-type|node.symbolType}). * @returns {Object} concrete instance of d3 symbol. * @memberof Node/helper */ function buildSvgSymbol(size = CONST.DEFAULT_NODE_SIZE, symbolTypeDesc = CONST.SYMBOLS.CIRCLE) { return d3Symbol() .size(() => size) .type(() => _convertTypeToD3Symbol(symbolTypeDesc))(); } /** * return dx, dy, and potentially alignmentBaseline and textAnchor props to put label in correct position relative to node * @param {number | undefined} dx - default computed offset of label * @param {'left' | 'right' | 'top' | 'bottom' | 'center' | undefined} labelPosition - user specified position of label relative to node * @returns {{dx: string, dy: string} | {dx: string, dy: string, textAnchor: string, dominantBaseline: string}} * props to put text svg for label in correct spot. default case returns just dx and dy, without textAnchor and dominantBaseline * @memberof Node/helper */ function getLabelPlacementProps(dx, labelPosition) { switch (labelPosition) { case "right": return { dx: dx ? `${dx}` : CONST.NODE_LABEL_DX, dy: "0", dominantBaseline: "middle", textAnchor: "start", }; case "left": return { dx: dx ? `${-dx}` : `-${CONST.NODE_LABEL_DX}`, dy: "0", dominantBaseline: "middle", textAnchor: "end", }; case "top": return { dx: "0", dy: dx ? `${-dx}` : `-${CONST.NODE_LABEL_DX}`, dominantBaseline: "baseline", textAnchor: "middle", }; case "bottom": return { dx: "0", dy: dx ? `${dx}` : CONST.NODE_LABEL_DX, dominantBaseline: "hanging", textAnchor: "middle", }; case "center": return { dx: "0", dy: "0", dominantBaseline: "middle", textAnchor: "middle", }; default: return { dx: dx ? `${dx}` : CONST.NODE_LABEL_DX, dy: CONST.NODE_LABEL_DY, }; } } export default { buildSvgSymbol, getLabelPlacementProps, };
mit
beckrob/Photo-z-SQL
Jhu.PhotoZ/PriorAbsMagLimitInFilter.cs
2859
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections.Concurrent; namespace Jhu.PhotoZ { public class PriorAbsMagLimitInFilter : PriorOnFluxInFilter { private double absMagLimit; private ConcurrentDictionary<double, double> redshiftDistanceModuluses; private double h, omega_m, omega_lambda; // This class implements an absolute magnitude limit in a filter, not allowing galaxies brighter than it // Hildebrandt (2010) used a limit of M(B)>-24 // The B filter could be the the WFC3 F438W (ID 92 in HSCFilterPortal) public PriorAbsMagLimitInFilter(double aAbsMagLimit, Filter aFilt, Template aTemp, double aH_0 = 0.7, double aOmega_m = 0.3, double aOmega_lambda = 0.7) : base(aFilt, aTemp) { absMagLimit = aAbsMagLimit; h = aH_0; omega_m = aOmega_m; omega_lambda = aOmega_lambda; } protected override void DoPreCalculationsFromTemplate(Template aTemp) { redshiftDistanceModuluses = new ConcurrentDictionary<double, double>(); List<double> redshifts = aTemp.GetParameterCoverage("Redshift"); foreach (double z in redshifts) { redshiftDistanceModuluses[z] = Cosmology.DistanceModulus(z, h, omega_m, omega_lambda); } base.DoPreCalculationsFromTemplate(aTemp); } public override bool VerifyParameterlist(List<TemplateParameter> aParams) { if (base.VerifyParameterlist(aParams)) { if (aParams.Count > 1) { if (aParams[1].Name == "Redshift" && aParams[0].Name == "Luminosity") { return true; } } } return false; } public override double Evaluate(List<TemplateParameter> parameters) { double currentLum = parameters[0].Value; double fluxAtUnitLum, distanceModulus; if (fluxesInFilter.TryGetValue(GetParameterDoubleArray(parameters), out fluxAtUnitLum) && redshiftDistanceModuluses.TryGetValue(parameters[1].Value, out distanceModulus)) { double apparentMag = MagnitudeSystem.GetMagnitudeFromCGSFlux(fluxAtUnitLum * currentLum, MagnitudeSystem.Type.AB); double absMag = apparentMag - distanceModulus; if (absMag > absMagLimit) { return 1.0; } else { return 0.0; } } return 0.0; } } }
mit
airpaca/pyair
tests/test.py
3308
#!/usr/bin/python # -*- coding: UTF-8 -*- """ Test de `pyair` avec une configuration spéficique. Un fichier de configuration au format JSON doit être préparer sur le modèle du fichier `config-test.json`. La variable d'environnement `CFG_PYAIR_TEST` peut être définit pour l'utilisation d'un fichier spécifique. """ import os import json import six import sys import unittest from pyair import xair from pyair.reg import excel_synthese, print_synthese import pandas as pd pd.set_option('display.width', 200) # Load configuration file fncfg = os.environ['CFG_PYAIR_TEST'] \ if 'CFG_PYAIR_TEST' \ else os.path.join(os.path.dirname(__file__), 'config-test.json') cfg = json.load(open(fncfg)) print("testing with %s configuration file..." % fncfg) class TestXAIR(unittest.TestCase): def get_stdout(self): """ Get Stdout. Returns: string. """ sys.stdout.seek(0) # rewind return sys.stdout.read() # return stdout def setUp(self): self.saved_stdout = sys.stdout # save stdout sys.stdout = six.StringIO() def tearDown(self): sys.stdout = self.saved_stdout # restore stdout def test_connexion(self): """ Test de la connexion au serveur. """ xr = xair.XAIR(user=cfg['xair']['user'], pwd=cfg['xair']['pwd'], adr=cfg['xair']['adr']) xr.disconnect() stdout = self.get_stdout() self.assertTrue('XAIR: Connexion établie' in stdout) self.assertTrue('XAIR: Connexion fermée' in stdout) def test_print_synthese(self): """ Test l'affichage des synthèses: vérification des informations statiques. """ # Traitement xr = xair.XAIR(user=cfg['xair']['user'], pwd=cfg['xair']['pwd'], adr=cfg['xair']['adr']) for mesures in cfg['mes']: pol, mes = list(mesures.items())[0] fct = getattr(__import__('pyair.reg', fromlist=[pol.lower()]), pol.lower()) # import function freq = 'D' if pol in ['PM10', ] else 'H' df = xr.get_mesures(mes, debut=cfg['debut'], fin=cfg['fin'], freq=freq, brut=False) print_synthese(fct, df) xr.disconnect() # Analyse du traitement stdout = self.get_stdout() for pol in [k for e in cfg['mes'] for k in e.keys()]: self.assertTrue('Pour le polluant: %s' % pol in stdout) def test_synthese_excel(self): """ Test la création de fichier de synthèses au format Excel: vérification de la présence des fichiers """ xr = xair.XAIR(user=cfg['xair']['user'], pwd=cfg['xair']['pwd'], adr=cfg['xair']['adr']) for mesures in cfg['mes']: pol, mes = list(mesures.items())[0] fct = getattr(__import__('pyair.reg', fromlist=[pol.lower()]), pol.lower()) # import function freq = 'D' if pol in ['PM10', ] else 'H' xls = os.path.join(cfg['excel_path'], 'stat_%s.xls' % pol) if os.path.isfile(xls): os.remove(xls) # remove old file df = xr.get_mesures(mes, debut=cfg['debut'], fin=cfg['fin'], freq=freq, brut=False) excel_synthese(fct, df, xls) self.assertTrue(os.path.isfile(xls)) xr.disconnect() if __name__ == "__main__": unittest.main()
mit
aspgems/kewego_party
spec/kewego_party/client/request_spec.rb
1065
# -*- encoding: utf-8 -*- require 'spec_helper' describe KewegoParty::Request do before do @client = KewegoParty::Client.new(:token => 'd4c804fd0f42533351aca404313d26eb') end it "raise an exception if the response not a kewego response" do VCR.turned_off do stub_request(:get, "http://api.kewego.com/app/getToken/?appKey=#{@client.token}"). to_return(:body => fixture("not_kewego_response.xml"), :headers => {:content_type => "text/html; charset=utf-8"}) expect { @client.app_get_token }.to raise_error(KewegoParty::InvalidResponseException) end end it "raise an exception if the response has a kewego error" do VCR.turned_off do stub_request(:get, "http://api.kewego.com/app/getToken/?appKey=#{@client.token}"). to_return(:body => fixture("kewego_response_error.xml"), :headers => {:content_type => "text/html; charset=utf-8"}) expect { @client.app_get_token }.to raise_error(KewegoParty::ErrorResponseException, 'appToken can not delivered') end end end
mit
elr-utilities/elr-calendar
src/js/elr-calendar-create.js
851
import $ from 'jquery' import elrMonths from './elr-calendar-months' import elrCalendarWeeks from './elr-calendar-weeks' // const elrMonths = elrCalendarMonths() const elrWeeks = elrCalendarWeeks() const renderDateView = (renderDate, $cal, evts) => { // create date view } const buildCalendar = (view, renderDate, $cal, evts) => { if (view === 'month') { elrMonths.renderMonth(renderDate, $cal, evts) } else if (view === 'week') { elrWeeks.renderWeek(renderDate, $cal, evts) } else { return // self.renderDate(renderDate, $cal, evts); } } export default { buildCalendar, changeCalendar: (view, renderDate, $cal, evts) => { const $inner = $cal.find('.calendar-inner') $.when($inner.animate({ opacity: 0 }, 300)).then( $.when($inner.remove()).then(buildCalendar(view, renderDate, $cal, evts)) ) } }
mit
chikara-chan/full-stack-javascript
manager/client/item/components/Form.js
1646
import React, {Component} from 'react' import {findDOMNode} from 'react-dom' import styles from '../sass/Form' import {Button, Form, Input, DatePicker, Select} from 'antd' class FormComponent extends Component { constructor() { super() this.handleSubmit = this.handleSubmit.bind(this) } handleSubmit(e) { e.preventDefault() const {form, actions} = this.props form.validateFields((err, values) => { if (!err) { actions.getItems(values) } }) } render() { const {form, schools, cats} = this.props return ( <Form onSubmit={this.handleSubmit} className={styles.form} inline> <Form.Item label="学校"> {form.getFieldDecorator('school',{initialValue: schools[0]?schools[0].id:''})( <Select className={styles.select}> {schools.map(school => <Select.Option key={school.id} value={school.id}>{school.schoolName}</Select.Option> )} </Select> )} </Form.Item> <Form.Item label="分类"> {form.getFieldDecorator('cat',{initialValue: ''})( <Select className={styles.select}> <Select.Option value="">全部</Select.Option> {cats.map(cat => <Select.Option key={cat.id} value={cat.id}>{cat.catName}</Select.Option> )} </Select> )} </Form.Item> <Form.Item> <Button htmlType="submit" type="primary">查询</Button> </Form.Item> </Form> ) } } export default Form.create()(FormComponent)
mit
minersc/msc
src/qt/locale/bitcoin_hu.ts
110284
<?xml version="1.0" ?><!DOCTYPE TS><TS language="hu" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About MinerSCoin</source> <translation>A MinerSCoinról</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;MinerSCoin&lt;/b&gt; version</source> <translation>&lt;b&gt;MinerSCoin&lt;/b&gt; verzió</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Ez egy kísérleti program. MIT/X11 szoftverlicenc alatt kiadva, lásd a mellékelt fájlt COPYING vagy http://www.opensource.org/licenses/mit-license.php. Ez a termék az OpenSSL Project által lett kifejlesztve az OpenSSL Toolkit (http://www.openssl.org/) és kriptográfiai szoftvertben való felhasználásra, írta Eric Young (eay@cryptsoft.com) és UPnP szoftver, írta Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The MinerSCoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Címjegyzék</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Dupla-kattintás a cím vagy a címke szerkesztéséhez</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Új cím létrehozása</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>A kiválasztott cím másolása a vágólapra</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Új cím</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your MinerSCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Ezekkel a MinerSCoin-címekkel fogadhatod kifizetéseket. Érdemes lehet minden egyes kifizető számára külön címet létrehozni, hogy könnyebben nyomon követhesd, kitől kaptál már pénzt.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Cím másolása</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>&amp;QR kód mutatása</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a MinerSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Jelenlegi nézet exportálása fájlba</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified MinerSCoin address</source> <translation>Üzenet ellenőrzése, hogy valóban a megjelölt MinerSCoin címekkel van-e aláírva.</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>Üzenet ellenőrzése</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Törlés</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your MinerSCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Címke &amp;másolása</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>Sz&amp;erkesztés</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Címjegyzék adatainak exportálása</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott fájl (*. csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Hiba exportálás közben</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>%1 nevű fájl nem írható.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Címke</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nincs címke)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Kulcsszó párbeszédablak</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Add meg a jelszót</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Új jelszó</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Új jelszó újra</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Írd be az új jelszót a tárcához.&lt;br/&gt;Használj legalább 10&lt;br/&gt;véletlenszerű karaktert&lt;/b&gt; vagy &lt;b&gt;legalább nyolc szót&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Tárca kódolása</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A tárcád megnyitásához a műveletnek szüksége van a tárcád jelszavára.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Tárca megnyitása</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A tárcád dekódolásához a műveletnek szüksége van a tárcád jelszavára.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Tárca dekódolása</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Jelszó megváltoztatása</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Írd be a tárca régi és új jelszavát.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Biztosan kódolni akarod a tárcát?</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR LITECOINS&lt;/b&gt;!</source> <translation>Figyelem: Ha kódolod a tárcát, és elveszíted a jelszavad, akkor &lt;b&gt;AZ ÖSSZES LITECOINODAT IS EL FOGOD VESZÍTENI!&lt;/b&gt;</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Biztosan kódolni akarod a tárcát?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>FONTOS: A pénztárca-fájl korábbi mentéseit ezzel az új, titkosított pénztárca-fájllal kell helyettesíteni. Biztonsági okokból a pénztárca-fájl korábbi titkosítás nélküli mentései haszontalanná válnak amint elkezdi használni az új, titkosított pénztárcát.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation type="unfinished"/> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Tárca kódolva</translation> </message> <message> <location line="-56"/> <source>MinerSCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your minerscoins from being stolen by malware infecting your computer.</source> <translation>MinerSCoin will close now to finish the encryption process. Ne feledd, hogy a tárca titkosítása sem nyújt teljes védelmet az adathalász programok fertőzésével szemben.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Tárca kódolása sikertelen.</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Tárca kódolása belső hiba miatt sikertelen. A tárcád nem lett kódolva.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>A megadott jelszavak nem egyeznek.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Tárca megnyitása sikertelen</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Hibás jelszó.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Dekódolás sikertelen.</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Jelszó megváltoztatva.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Üzenet aláírása...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Szinkronizálás a hálózattal...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Áttekintés</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Tárca általános áttekintése</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Tranzakciók</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Tranzakciótörténet megtekintése</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Tárolt címek és címkék listájának szerkesztése</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Kiizetést fogadó címek listája</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Kilépés</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Kilépés</translation> </message> <message> <location line="+4"/> <source>Show information about MinerSCoin</source> <translation>Információk a MinerSCoinról</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>A &amp;Qt-ról</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Információk a Qt ról</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opciók...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>Tárca &amp;kódolása...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Bisztonsági másolat készítése a Tárcáról</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Jelszó &amp;megváltoztatása...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>A blokkok importálása lemezről...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>A blokkok lemezen történő ujraindexelése...</translation> </message> <message> <location line="-347"/> <source>Send coins to a MinerSCoin address</source> <translation>Érmék küldése megadott címre</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for MinerSCoin</source> <translation>MinerSCoin konfigurációs opciók</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Biztonsági másolat készítése a Tárcáról egy másik helyre</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Tárcakódoló jelszó megváltoztatása</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Debug ablak</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Hibakereső és diagnosztikai konzol megnyitása</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>Üzenet &amp;valódiságának ellenőrzése</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>MinerSCoin</source> <translation>MinerSCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Tárca</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About MinerSCoin</source> <translation>&amp;A MinerSCoinról</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>A pénztárcájához tartozó privát kulcsok titkosítása</translation> </message> <message> <location line="+7"/> <source>Sign messages with your MinerSCoin addresses to prove you own them</source> <translation>Üzenet aláírása a MinerSCoin címmel, amivel bizonyítja, hogy a cím az ön tulajdona.</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified MinerSCoin addresses</source> <translation>Annak ellenőrzése, hogy az üzenetek valóban a megjelölt MinerSCoin címekkel vannak-e alaírva</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Fájl</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Beállítások</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Súgó</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Fül eszköztár</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[teszthálózat]</translation> </message> <message> <location line="+47"/> <source>MinerSCoin client</source> <translation>MinerSCoin kliens</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to MinerSCoin network</source> <translation><numerusform>%n aktív kapcsolat a MinerSCoin-hálózattal</numerusform><numerusform>%n aktív kapcsolat a MinerSCoin-hálózattal</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>A tranzakció-történet %1 blokkja feldolgozva.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Naprakész</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Frissítés...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Tranzakciós díj jóváhagyása</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Tranzakció elküldve.</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Beérkező tranzakció</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Dátum: %1 Összeg: %2 Típus: %3 Cím: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation type="unfinished"/> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid MinerSCoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;kódolva&lt;/b&gt; és jelenleg &lt;b&gt;nyitva&lt;/b&gt;.</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Tárca &lt;b&gt;kódolva&lt;/b&gt; és jelenleg &lt;b&gt;zárva&lt;/b&gt;.</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. MinerSCoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation type="unfinished"/> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Cím szerkesztése</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Cím&amp;ke</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>A címhez tartozó címke</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Cím</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Az ehhez a címjegyzék-bejegyzéshez tartozó cím. Ez csak a küldő címeknél módosítható.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Új fogadó cím</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Új küldő cím</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Fogadó cím szerkesztése</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Küldő cím szerkesztése</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>A megadott &quot;%1&quot; cím már szerepel a címjegyzékben.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid MinerSCoin address.</source> <translation>A megadott &quot;%1&quot; cím nem egy érvényes MinerSCoin-cím.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Tárca feloldása sikertelen</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Új kulcs generálása sikertelen</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>MinerSCoin-Qt</source> <translation type="unfinished"/> </message> <message> <location line="-12"/> <source>version</source> <translation>verzió</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Használat:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>parancssoros opciók</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>UI opciók</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Indítás lekicsinyítve </translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opciók</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Fő</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Tranzakciós &amp;díj fizetése</translation> </message> <message> <location line="+31"/> <source>Automatically start MinerSCoin after logging in to the system.</source> <translation>Induljon el a MinerSCoin a számítógép bekapcsolásakor</translation> </message> <message> <location line="+3"/> <source>&amp;Start MinerSCoin on system login</source> <translation>&amp;Induljon el a számítógép bekapcsolásakor</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Automatically open the MinerSCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>A MinerSCoin-kliens portjának automatikus megnyitása a routeren. Ez csak akkor működik, ha a routered támogatja az UPnP-t és az engedélyezve is van rajta.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>&amp;UPnP port-feltérképezés</translation> </message> <message> <location line="+7"/> <source>Connect to the MinerSCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>SOCKS proxyn keresztüli csatlakozás a MinerSCoin hálózatához (pl. Tor-on keresztüli csatlakozás esetén)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Csatlakozás SOCKS proxyn keresztül:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Proxy IP címe (pl.: 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Proxy portja (pl.: 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation type="unfinished"/> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Kicsinyítés után csak eszköztár-ikont mutass</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Kicsinyítés a tálcára az eszköztár helyett</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Az alkalmazásból való kilépés helyett az eszköztárba kicsinyíti az alkalmazást az ablak bezárásakor. Ez esetben az alkalmazás csak a Kilépés menüponttal zárható be.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>K&amp;icsinyítés záráskor</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Megjelenítés</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting MinerSCoin.</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Mértékegység:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Válaszd ki az interfészen és érmék küldésekor megjelenítendő alapértelmezett alegységet.</translation> </message> <message> <location line="+9"/> <source>Whether to show MinerSCoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Címek megjelenítése a tranzakciólistában</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>Megszakítás</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>Alkalmazás</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>alapértelmezett</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Figyelem</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting MinerSCoin.</source> <translation>Ez a beállítás a MinerSCoin ujraindítása után lép érvénybe.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation type="unfinished"/> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Űrlap</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the MinerSCoin network after a connection is established, but this process has not completed yet.</source> <translation>A kijelzett információ lehet, hogy elavult. A pénztárcája automatikusan szinkronizálja magát a MinerSCoin hálózattal miután a kapcsolat létrejön, de ez e folyamat még nem fejeződött be.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Egyenleg:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Megerősítetlen:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Tárca</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Legutóbbi tranzakciók&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Aktuális egyenleged</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Még megerősítésre váró, a jelenlegi egyenlegbe be nem számított tranzakciók</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>Nincs szinkronban.</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start minerscoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kód párbeszédablak</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Fizetés kérése</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Összeg:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Címke:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Üzenet:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Mentés má&amp;sként</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Hiba lépett fel az URI QR kóddá alakításakor</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>A megadott összeg nem érvényes. Kérem ellenőrizze.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>A keletkezett URI túl hosszú, próbálja meg csökkenteni a cimkeszöveg / üzenet méretét.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>QR kód mentése</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG Képfájlok (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Kliens néve</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>Nem elérhető</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Kliens verzió</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Információ</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation type="unfinished"/> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Bekapcsolás ideje</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Hálózat</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Kapcsolatok száma</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Teszthálózaton</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokklánc</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Aktuális blokkok száma</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Becsült összes blokk</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Utolsó blokk ideje</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Megnyitás</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Show the MinerSCoin-Qt help message to get a list with possible MinerSCoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation type="unfinished"/> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konzol</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Fordítás dátuma</translation> </message> <message> <location line="-104"/> <source>MinerSCoin - Debug window</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>MinerSCoin Core</source> <translation type="unfinished"/> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Open the MinerSCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Konzol törlése</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the MinerSCoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Navigálhat a fel és le nyilakkal, és &lt;b&gt;Ctrl-L&lt;/b&gt; -vel törölheti a képernyőt.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Érmék küldése</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Küldés több címzettnek egyszerre</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;Címzett hozzáadása</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Az összes tranzakciós mező eltávolítása</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Mindent &amp;töröl</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Egyenleg:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Küldés megerősítése</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Küldés</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; %2-re (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Küldés megerősítése</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Valóban el akarsz küldeni %1-t?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> és</translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>A címzett címe érvénytelen, kérlek, ellenőrizd.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A fizetendő összegnek nagyobbnak kell lennie 0-nál.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Nincs ennyi minerscoin az egyenlegeden.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>A küldeni kívánt összeg és a %1 tranzakciós díj együtt meghaladja az egyenlegeden rendelkezésedre álló összeget.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Többször szerepel ugyanaz a cím. Egy küldési műveletben egy címre csak egyszer lehet küldeni.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Hiba: a tranzakciót elutasították. Ezt az okozhatja, ha már elköltöttél valamennyi érmét a tárcádból például ha a wallet.dat-od egy másolatát használtad, és így az elköltés csak abban lett jelölve, de itt nem.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Űrlap</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Összeg:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Címzett:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Milyen címkével kerüljön be ez a cím a címtáradba? </translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Címke:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Válassz egy címet a címjegyzékből</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Cím beillesztése a vágólapról</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Címzett eltávolítása</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a MinerSCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adj meg egy MinerSCoin-címet (pl.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2 )</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>Üzenet aláírása...</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Aláírhat a címeivel üzeneteket, amivel bizonyíthatja, hogy a címek az önéi. Vigyázzon, hogy ne írjon alá semmi félreérthetőt, mivel a phising támadásokkal megpróbálhatják becsapni, hogy az azonosságát átírja másokra. Csak olyan részletes állításokat írjon alá, amivel egyetért.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adj meg egy MinerSCoin-címet (pl.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2 )</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Válassz egy címet a címjegyzékből</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Cím beillesztése a vágólapról</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Ide írja az aláírandó üzenetet</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>A jelenleg kiválasztott aláírás másolása a rendszer-vágólapra</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this MinerSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Mindent &amp;töröl</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>Üzenet ellenőrzése</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Írja be az aláírás címét, az üzenetet (ügyelve arra, hogy az új-sor, szóköz, tab, stb. karaktereket is pontosan) és az aláírást az üzenet ellenőrzéséhez. Ügyeljen arra, ne gondoljon többet az aláírásról, mint amennyi az aláírt szövegben ténylegesen áll, hogy elkerülje a köztes-ember (man-in-the-middle) támadást.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adj meg egy MinerSCoin-címet (pl.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2 )</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified MinerSCoin address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a MinerSCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Adj meg egy MinerSCoin-címet (pl.: Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2 )</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Enter MinerSCoin signature</source> <translation>Adja meg a MinerSCoin aláírást</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>A megadott cím nem érvényes.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Ellenőrizze a címet és próbálja meg újra.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation type="unfinished"/> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation type="unfinished"/> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The MinerSCoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[teszthálózat]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Megnyitva %1-ig</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/megerősítetlen</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 megerősítés</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Állapot</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Dátum</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Legenerálva</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Űrlap</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Címzett</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation type="unfinished"/> </message> <message> <location line="-2"/> <source>label</source> <translation>címke</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Jóváírás</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>elutasítva</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Terhelés</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Tranzakciós díj</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Nettó összeg</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Üzenet</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Megjegyzés</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>A frissen generált érméket csak 120 blokkal később tudod elkölteni. Ez a blokk nyomban szétküldésre került a hálózatba, amint legeneráltad, hogy hozzáadhassák a blokklánchoz. Ha nem kerül be a láncba, úgy az állapota &quot;elutasítva&quot;-ra módosul, és nem költheted el az érméket. Ez akkor következhet be időnként, ha egy másik csomópont mindössze néhány másodperc különbséggel generált le egy blokkot a tiédhez képest.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Tranzakció</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Összeg</translation> </message> <message> <location line="+1"/> <source>true</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>false</source> <translation type="unfinished"/> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, még nem sikerült elküldeni.</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>ismeretlen</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Tranzakció részletei</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Ez a mező a tranzakció részleteit mutatja</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Dátum</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Típus</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Összeg</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>%1-ig megnyitva</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Offline (%1 megerősítés)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Megerősítetlen (%1 %2 megerősítésből)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Megerősítve (%1 megerősítés)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Ezt a blokkot egyetlen másik csomópont sem kapta meg, így valószínűleg nem lesz elfogadva!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Legenerálva, de még el nem fogadva.</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Erre a címre</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Erről az</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Erre a címre</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Magadnak kifizetve</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Kibányászva</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(nincs)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Tranzakció állapota. Húzd ide a kurzort, hogy lásd a megerősítések számát.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Tranzakció fogadásának dátuma és időpontja.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tranzakció típusa.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>A tranzakció címzettjének címe.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Az egyenleghez jóváírt vagy ráterhelt összeg.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Mind</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Mai</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Ezen a héten</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Ebben a hónapban</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Múlt hónapban</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Ebben az évben</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Tartomány ...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Erre a címre</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Erre a címre</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Magadnak</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Kibányászva</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Más</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Írd be a keresendő címet vagy címkét</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimális összeg</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Cím másolása</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Címke másolása</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Összeg másolása</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Címke szerkesztése</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Tranzakciós részletek megjelenítése</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Tranzakció adatainak exportálása</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Vesszővel elválasztott fájl (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Megerősítve</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Dátum</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Típus</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Címke</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Cím</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Összeg</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>Azonosító</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Hiba lépett fel exportálás közben</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>%1 fájlba való kiírás sikertelen.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Tartomány:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>meddig</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Érmék küldése</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Jelenlegi nézet exportálása fájlba</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Biztonsági másolat készítése a Tárcáról</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Tárca fájl (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Biztonsági másolat készítése sikertelen</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Hiba lépett fel a Tárca másik helyre való mentése közben</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>MinerSCoin version</source> <translation>MinerSCoin verzió</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Használat:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or minerscoind</source> <translation>Parancs küldése a -serverhez vagy a minerscoindhez </translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Parancsok kilistázása </translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Segítség egy parancsról </translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opciók </translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: minerscoin.conf)</source> <translation>Konfigurációs fájl (alapértelmezett: minerscoin.conf) </translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: minerscoind.pid)</source> <translation>pid-fájl (alapértelmezett: minerscoind.pid) </translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Adatkönyvtár </translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Az adatbázis gyorsítótár mérete megabájtban (alapértelmezés: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Csatlakozásokhoz figyelendő &lt;port&gt; (alapértelmezett: 9333 or testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Maximálisan &lt;n&gt; számú kapcsolat fenntartása a peerekkel (alapértelmezés: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Kapcsolódás egy csomóponthoz a peerek címeinek megszerzése miatt, majd szétkapcsolás</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Adja meg az Ön saját nyilvános címét</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Helytelenül viselkedő peerek leválasztási határértéke (alapértelmezés: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Helytelenül viselkedő peerek kizárási ideje másodpercben (alapértelmezés: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>JSON-RPC csatlakozásokhoz figyelendő &lt;port&gt; (alapértelmezett: 9332 or testnet: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Parancssoros és JSON-RPC parancsok elfogadása </translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Háttérben futtatás daemonként és parancsok elfogadása </translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Teszthálózat használata </translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=minerscoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;MinerSCoin Alert&quot; admin@foo.com </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. MinerSCoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Figyelem: a -paytxfee nagyon magas. Ennyi tranzakciós díjat fogsz fizetni, ha elküldöd a tranzakciót.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong MinerSCoin will not work properly.</source> <translation>Figyelem: Ellenőrizd, hogy helyesen van-e beállítva a gépeden a dátum és az idő. A MinerSCoin nem fog megfelelően működni, ha rosszul van beállítvaaz órád.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Csatlakozás csak a megadott csomóponthoz</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Érvénytelen -tor cím: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Csak blokklánccal egyező beépített ellenőrző pontok elfogadása (alapértelmezés: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Időbélyeges hibakeresési kimenet hozzáadása az elejéhez</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the MinerSCoin Wiki for SSL setup instructions)</source> <translation>SSL-opciók: (lásd a MinerSCoin Wiki SSL-beállítási instrukcióit)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>trace/debug információ küldése a konzolra a debog.log fájl helyett</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>trace/debug információ küldése a debuggerre</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Csatlakozás időkerete milliszekundumban (alapértelmezett: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Felhasználói név JSON-RPC csatlakozásokhoz </translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Jelszó JSON-RPC csatlakozásokhoz </translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>JSON-RPC csatlakozások engedélyezése meghatározott IP-címről </translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Parancsok küldése &lt;ip&gt; címen működő csomóponthoz (alapértelmezett: 127.0.0.1) </translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Parancs, amit akkor hajt végre, amikor a legjobb blokk megváltozik (%s a cmd-ban lecserélődik a blokk hash-re)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>A Tárca frissítése a legfrissebb formátumra</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Kulcskarika mérete &lt;n&gt; (alapértelmezett: 100) </translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Blokklánc újraszkennelése hiányzó tárca-tranzakciók után </translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>OpenSSL (https) használata JSON-RPC csatalkozásokhoz </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Szervertanúsítvány-fájl (alapértelmezett: server.cert) </translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Szerver titkos kulcsa (alapértelmezett: server.pem) </translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Elfogadható rejtjelkulcsok (alapértelmezett: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH ) </translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Ez a súgó-üzenet </translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>A %s nem elérhető ezen a gépen (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Csatlakozás SOCKS proxyn keresztül</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>DNS-kikeresés engedélyezése az addnode-nál és a connect-nél</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Címek betöltése...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Hiba a wallet.dat betöltése közben: meghibásodott tárca</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of MinerSCoin</source> <translation>Hiba a wallet.dat betöltése közben: ehhez a tárcához újabb verziójú MinerSCoin-kliens szükséges</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart MinerSCoin to complete</source> <translation>A Tárca újraírása szükséges: Indítsa újra a teljesen a MinerSCoin-t</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Hiba az wallet.dat betöltése közben</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Érvénytelen -proxy cím: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Ismeretlen hálózat lett megadva -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Ismeretlen -socks proxy kérése: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Étvénytelen -paytxfee=&lt;összeg&gt; összeg: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Étvénytelen összeg</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nincs elég minerscoinod.</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Blokkindex betöltése...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Elérendő csomópont megadása and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. MinerSCoin is probably already running.</source> <translation>A %s nem elérhető ezen a gépen. A MinerSCoin valószínűleg fut már.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>kB-onként felajánlandó díj az általad küldött tranzakciókhoz</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Tárca betöltése...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Nem sikerült a Tárca visszaállítása a korábbi verzióra</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Nem sikerült az alapértelmezett címet írni.</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Újraszkennelés...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Betöltés befejezve.</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Használd a %s opciót</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Hiba</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Be kell állítani rpcpassword=&lt;password&gt; a konfigurációs fájlban %s Ha a fájl nem létezik, hozd létre &apos;csak a felhasználó által olvasható&apos; fájl engedéllyel</translation> </message> </context> </TS>
mit
arminhammer/rubbertiger
test/index.js
258
'use strict'; var assert = require('assert'); var rubbertiger = require('../lib'); describe('rubbertiger', function () { it('should have unit test!', function () { assert(false, 'we expected this package author to add actual unit tests.'); }); });
mit
angular/angular-cli-stress-test
src/app/components/comp-1976/comp-1976.component.spec.ts
847
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { Comp1976Component } from './comp-1976.component'; describe('Comp1976Component', () => { let component: Comp1976Component; let fixture: ComponentFixture<Comp1976Component>; beforeEach(async(() => { TestBed.configureTestingModule({ declarations: [ Comp1976Component ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(Comp1976Component); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); });
mit
zalari/tus-server
upload.js
713
/** * (c) Christian Ulbrich, Zalari UG (haftungsbeschränkt) * 2014 */ var fs = require('fs'); var self = {}; /** * returns the offset, i.e. the file size of a file. * @param filepath fully qualified path to the file, whose offset should be returned */ self.getOffset = function (filepath) { //when the file is not existing, simply return an offset of 0... //TODO: compensate for io-errors... if (fs.existsSync(filepath)) { //Größe holen var stat = fs.statSync(filepath); return stat.size; } else { return 0 } }; self.getWriteStream = function (filepath, start) { return fs.createWriteStream(filepath,{"start":start}); }; module.exports = self;
mit
trandangquyen/MVC
application/views/site/login.php
5255
<!DOCTYPE html> <html > <head> <base href="<?php echo base_url(); ?>"> <meta charset="UTF-8"> <title>Material Login Form</title> <link rel="stylesheet" href="public/admin/css/reset.min.css"> <link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'> <link rel='stylesheet prefetch' href='http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css'> <link rel="stylesheet" href="public/admin/css/style.css"> <link href="public/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <style> .container{ margin-bottom: 0; } .error{ color: #ed2553; font-size: 13px; margin-bottom: -15px; position: absolute; bottom: -10px; } .r_error{ color: #ed2553; font-size: 13px; margin-bottom: -15px; position: absolute; top: 12px; } </style> </head> <body> <!-- Mixins--> <!-- Pen Title--> <div class="pen-title"> <h1>Hãy đăng nhập hoặc đăng ký</h1><span>Hoặc <i class='fa fa-code'></i><a href='#'>Quay lại trang chủ</a></span> </div> <div class="rerun"><a href="home">Quay lại</a></div> <div class="container"> <div class="card"></div> <div class="card"> <h1 class="title">Đăng nhập</h1> <?php if(isset($error)) echo '<div class="alert alert-danger" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> <span class="sr-only">Error:</span> '.$error.' </div>'; elseif(isset($message)) echo '<div class="alert alert-info" role="alert"> <span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span> '.$message.' </div>'; if(isset($redirect)) echo '<script>setTimeout(function(){window.location.replace("'.$redirect.'");}, 2000);</script>'; ?> <form method="post" action="user/login" name="login"> <input type="hidden" name="dologin" value="true"/> <div class="input-container"> <input name="email" type="text" id="email"/> <label for="email">Email đăng nhập</label> <div class="error" id="email_error"><?php echo form_error('email')?></div> <div class="bar"></div> </div> <div class="input-container"> <input name="password" type="password" id="password" /> <label for="password">Mật khẩu</label> <div class="error" id="password_error"><?php echo form_error('password')?></div> <div class="bar"></div> </div> <div class="button-container"> <button name="login" type="submit"><span>Đăng nhập</span></button> </div> <div class="footer"><a href="login/facebook">Facebook</a> | <a href="login/google">Google</a> | <a href="user/forgot">Quên mật khẩu?</a></div> </form> </div> <div class="card alt"> <div class="toggle"><a href=""></a></div> <h1 class="title">Đăng ký <div class="close"></div> </h1> <form method="post" action="user/register" name="register"> <div class="input-container"> <input name="remail" type="text" id="email"/> <label for="email">Email</label> <div class="r_error"><?php echo form_error('remail'); ?></div> <div class="bar"></div> </div> <div class="input-container"> <input name="rname" type="text" id="name"/> <label for="name">Họ và tên</label> <div class="r_error"><?php echo form_error('rname'); ?></div> <div class="bar"></div> </div> <div class="input-container"> <input name="rpass" type="password" id="password"/> <label for="password">Mật khẩu</label> <div class="r_error"><?php echo form_error('rpass'); ?></div> <div class="bar"></div> </div> <div class="input-container"> <input name="rrepass" type="password" id="re_password"/> <label for="re_password">Nhập lại mật khẩu</label> <div class="r_error"><?php echo form_error('rrepass'); ?></div> <div class="bar"></div> </div> <div class="button-container"> <button><span>Đăng ký</span></button> </div> </form> </div> </div> <!-- Portfolio--><a id="portfolio" href="#" onclick="goBack()" title="View my portfolio!"><i class="fa fa-link"></i></a> <!-- CodePen--><a id="codepen" href="#" onclick="goBack()" title="Follow me!"><i class="fa fa-codepen"></i></a> <script> function goBack() { window.history.back(); } </script> <script src='public/themes/js/jquery-1.7.2.min.js'></script> <script src="public/admin/js/index.js"></script> </body> </html>
mit
jut-io/statsd-jutgraphite-backend
jutgraphite.js
7875
/* * Flush stats to Jut (http://www.jut.io) using the graphite protocol. * * To enable this backend, install alongside statsd and include an entry in the * backends configuration array: * * backends: ['../statsd-jutgraphite-backend/jutgraphite'] * * This backend supports the following config options: * * jutHost: Hostname of Jut graphite collector. * jutPort: Port to contact Jut graphite collector at. */ var net = require('net'), logger = require('../statsd/lib/logger'); // this will be instantiated to the logger var l; var debug; var flushInterval; var jutHost; var jutPort; // prefix configuration var globalPrefix; var prefixPersecond; var prefixCounter; var prefixTimer; var prefixGauge; var prefixSet; // set up namespaces var legacyNamespace = true; var globalNamespace = []; var counterNamespace = []; var timerNamespace = []; var gaugesNamespace = []; var setsNamespace = []; var jutGraphiteStats = {}; var post_stats = function jut_graphite_post_stats(statString) { var last_flush = jutGraphiteStats.last_flush || 0; var last_exception = jutGraphiteStats.last_exception || 0; var flush_time = jutGraphiteStats.flush_time || 0; var flush_length = jutGraphiteStats.flush_length || 0; if (jutHost) { try { var graphite = net.createConnection(jutPort, jutHost); graphite.addListener('error', function(connectionException){ if (debug) { l.log(connectionException); } }); graphite.on('connect', function() { var ts = Math.round(new Date().getTime() / 1000); var ts_suffix = ' ' + ts + "\n"; var namespace = globalNamespace.concat(prefixStats).join("."); statString += namespace + '.jutGraphiteStats.last_exception ' + last_exception + ts_suffix; statString += namespace + '.jutGraphiteStats.last_flush ' + last_flush + ts_suffix; statString += namespace + '.jutGraphiteStats.flush_time ' + flush_time + ts_suffix; statString += namespace + '.jutGraphiteStats.flush_length ' + flush_length + ts_suffix; var starttime = Date.now(); this.write(statString); this.end(); jutGraphiteStats.flush_time = (Date.now() - starttime); jutGraphiteStats.flush_length = statString.length; jutGraphiteStats.last_flush = Math.round(new Date().getTime() / 1000); }); } catch(e){ if (debug) { l.log(e); } jutGraphiteStats.last_exception = Math.round(new Date().getTime() / 1000); } } }; var flush_stats = function jut_graphite_flush(ts, metrics) { var ts_suffix = ' ' + ts + "\n"; var starttime = Date.now(); var statString = ''; var numStats = 0; var key; var timer_data_key; var counters = metrics.counters; var gauges = metrics.gauges; var timers = metrics.timers; var sets = metrics.sets; var counter_rates = metrics.counter_rates; var timer_data = metrics.timer_data; var statsd_metrics = metrics.statsd_metrics; for (key in counters) { var namespace = counterNamespace.concat(key); var value = counters[key]; var valuePerSecond = counter_rates[key]; // pre-calculated "per second" rate if (legacyNamespace === true) { statString += namespace.join(".") + ' ' + valuePerSecond + ts_suffix; statString += 'stats_counts.' + key + ' ' + value + ts_suffix; } else { statString += namespace.concat('rate').join(".") + ' ' + valuePerSecond + ts_suffix; statString += namespace.concat('count').join(".") + ' ' + value + ts_suffix; } numStats += 1; } for (key in timer_data) { var namespace = timerNamespace.concat(key); var the_key = namespace.join("."); for (timer_data_key in timer_data[key]) { if (typeof(timer_data[key][timer_data_key]) === 'number') { statString += the_key + '.' + timer_data_key + ' ' + timer_data[key][timer_data_key] + ts_suffix; } else { for (var timer_data_sub_key in timer_data[key][timer_data_key]) { if (debug) { l.log(timer_data[key][timer_data_key][timer_data_sub_key].toString()); } statString += the_key + '.' + timer_data_key + '.' + timer_data_sub_key + ' ' + timer_data[key][timer_data_key][timer_data_sub_key] + ts_suffix; } } } numStats += 1; } for (key in gauges) { var namespace = gaugesNamespace.concat(key); statString += namespace.join(".") + ' ' + gauges[key] + ts_suffix; numStats += 1; } for (key in sets) { var namespace = setsNamespace.concat(key); statString += namespace.join(".") + '.count ' + sets[key].values().length + ts_suffix; numStats += 1; } var namespace = globalNamespace.concat(prefixStats); if (legacyNamespace === true) { statString += prefixStats + '.numStats ' + numStats + ts_suffix; statString += 'stats.' + prefixStats + '.jutGraphiteStats.calculationtime ' + (Date.now() - starttime) + ts_suffix; for (key in statsd_metrics) { statString += 'stats.' + prefixStats + '.' + key + ' ' + statsd_metrics[key] + ts_suffix; } } else { statString += namespace.join(".") + '.numStats ' + numStats + ts_suffix; statString += namespace.join(".") + '.jutGraphiteStats.calculationtime ' + (Date.now() - starttime) + ts_suffix; for (key in statsd_metrics) { var the_key = namespace.concat(key); statString += the_key.join(".") + ' ' + statsd_metrics[key] + ts_suffix; } } post_stats(statString); if (debug) { l.log("numStats: " + numStats); } }; var backend_status = function jut_graphite_status(writeCb) { for (var stat in jutGraphiteStats) { writeCb(null, 'graphite', stat, jutGraphiteStats[stat]); } }; exports.init = function jut_graphite_init(startup_time, config, events) { l = new logger.Logger(config.log || {}); debug = config.debug; jutHost = config.jutHost; jutPort = config.jutPort; config.graphite = config.graphite || {}; globalPrefix = config.graphite.globalPrefix; prefixCounter = config.graphite.prefixCounter; prefixTimer = config.graphite.prefixTimer; prefixGauge = config.graphite.prefixGauge; prefixSet = config.graphite.prefixSet; legacyNamespace = config.graphite.legacyNamespace; // set defaults for prefixes globalPrefix = globalPrefix !== undefined ? globalPrefix : "stats"; prefixCounter = prefixCounter !== undefined ? prefixCounter : "counters"; prefixTimer = prefixTimer !== undefined ? prefixTimer : "timers"; prefixGauge = prefixGauge !== undefined ? prefixGauge : "gauges"; prefixSet = prefixSet !== undefined ? prefixSet : "sets"; legacyNamespace = legacyNamespace !== undefined ? legacyNamespace : true; if (legacyNamespace === false) { if (globalPrefix !== "") { globalNamespace.push(globalPrefix); counterNamespace.push(globalPrefix); timerNamespace.push(globalPrefix); gaugesNamespace.push(globalPrefix); setsNamespace.push(globalPrefix); } if (prefixCounter !== "") { counterNamespace.push(prefixCounter); } if (prefixTimer !== "") { timerNamespace.push(prefixTimer); } if (prefixGauge !== "") { gaugesNamespace.push(prefixGauge); } if (prefixSet !== "") { setsNamespace.push(prefixSet); } } else { globalNamespace = ['stats']; counterNamespace = ['stats']; timerNamespace = ['stats', 'timers']; gaugesNamespace = ['stats', 'gauges']; setsNamespace = ['stats', 'sets']; } jutGraphiteStats.last_flush = startup_time; jutGraphiteStats.last_exception = startup_time; jutGraphiteStats.flush_time = 0; jutGraphiteStats.flush_length = 0; flushInterval = config.flushInterval; events.on('flush', flush_stats); events.on('status', backend_status); return true; };
mit
soukoku/ModernWpf2
samples/BasicRunner/VM/SampleAppVM.cs
12842
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using ModernWpf; using ModernWpf.Messages; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Text; using System.Threading; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Input; namespace BasicRunner.VM { class SampleAppVM : ViewModelBase { public SampleAppVM() { //Languages = new ObservableCollection<CultureInfoVM>(); //Languages.Add(new CultureInfoVM(new CultureInfo("en-US")) { IsSelected = true }); //Languages.Add(new CultureInfoVM(new CultureInfo("zh-TW"))); //Languages.Add(new CultureInfoVM(new CultureInfo("zh-CN"))); //Languages.Add(new CultureInfoVM(new CultureInfo("ja"))); //Strings = new List<string>(); //Items = new List<ItemVM>(); //for (int i = 1; i <= 1000; i++) //{ // Strings.Add(string.Format("should virtual {0}", i)); // Items.Add(new ItemVM // { // Boolean = i % 5 == 0, // Number = i, // String = string.Format("Item # {0}", i) // }); //} //Progress = new ProgressViewModel(); //TreeItems = new ObservableCollection<HierarchyVM>(); //for (int i = 0; i < 50; i++) //{ // TreeItems.Add(new HierarchyVM(5)); //} } public List<Accent> Accents { get; } = new List<Accent>(Accent.GetPredefinedAccents()); private ICommand _testMessageCommand; public ICommand TestMessageCommand { get { return _testMessageCommand ?? (_testMessageCommand = new RelayCommand<string>(arg => { switch (arg) { case "open-file": Messenger.Default.Send(new ChooseFileMessage(this, files => { Messenger.Default.Send(new MessageBoxMessage(this, "You selected " + files.FirstOrDefault())); }) { Caption = "Test Opening A File (no change will be made)", Purpose = FilePurpose.OpenSingle }); break; case "open-files": Messenger.Default.Send(new ChooseFileMessage(this, files => { Messenger.Default.Send(new MessageBoxMessage(this, $"You selected {files.Count()} files.")); }) { Caption = "Test Opening Multiple Files (no change will be made)", Purpose = FilePurpose.OpenMultiple }); break; case "save-file": Messenger.Default.Send(new ChooseFileMessage(this, files => { Messenger.Default.Send(new MessageBoxMessage(this, "You chose " + files.FirstOrDefault())); }) { Caption = "Test Saving A File (no change will be made)", Purpose = FilePurpose.Save }); break; case "choose-folder": Messenger.Default.Send(new ChooseFolderMessage(this, folder => { Messenger.Default.Send(new MessageBoxMessage(this, "You chose " + folder)); }) { Caption = "Test Choosing A Folder", }); break; } })); } } public string StringValue { get; } = "This is a string from view model"; public int IntValue { get; } = 512; //public ObservableCollection<CultureInfoVM> Languages { get; private set; } //public ObservableCollection<HierarchyVM> TreeItems { get; private set; } //public List<ItemVM> Items { get; private set; } //private ICommand _sortItemsCommand; //public ICommand SortItemsCommand //{ // get // { // return _sortItemsCommand ?? ( // _sortItemsCommand = new RelayCommand<GridViewSortParameter>(e => // { // var head = e.Header; // if (head != null) // { // string field = null; // var bind = head.Column.DisplayMemberBinding as Binding; // if (bind != null) // { // field = bind.Path.Path; // } // if (!string.IsNullOrEmpty(field)) // { // Debug.WriteLine("Sort command exec on " + field); // var view = CollectionViewSource.GetDefaultView(Items); // if (view.CanSort) // { // //view.DeferRefresh(); // view.SortDescriptions.Clear(); // if (e.NewSortDirection.HasValue) // { // view.SortDescriptions.Add(new System.ComponentModel.SortDescription(field, e.NewSortDirection.Value)); // } // } // } // } // }) // ); // } //} //public List<string> Strings { get; private set; } //public ProgressViewModel Progress { get; private set; } //private RelayCommand _testProgressCmd; //public ICommand TestProgressCommand //{ // get // { // if (_testProgressCmd == null) // { // _testProgressCmd = new RelayCommand(() => // { // ThreadPool.QueueUserWorkItem(o => // { // for (double i = 0; i < 100; i++) // { // Progress.UpdateState(System.Windows.Shell.TaskbarItemProgressState.Normal, i / 100, "Progres = " + i); // Thread.Sleep(60); // } // Progress.UpdateState(System.Windows.Shell.TaskbarItemProgressState.None); // App.Current.Dispatcher.BeginInvoke(new Action(() => // { // _testProgressCmd.RaiseCanExecuteChanged(); // })); // }); // }, () => // { // return !Progress.IsBusy; // }); // } // return _testProgressCmd; // } //} //static readonly ResourceDictionary desktopSize = GetResource("/ModernWPF;component/themes/ModernBaseDesktop.xaml"); //static readonly ResourceDictionary modernSize = GetResource("/ModernWPF;component/themes/ModernBase.xaml"); //internal static ResourceDictionary GetResource(string url) //{ // var style = new ResourceDictionary(); // style.Source = new Uri(url, UriKind.Relative); // return style; //} //private static void ApplyResources(ResourceDictionary resources) //{ // foreach (var k in resources.Keys) // { // Application.Current.Resources[k] = resources[k]; // } //} private ICommand _toggleThemeCmd; public ICommand ToggleThemeCommand { get { if (_toggleThemeCmd == null) { _toggleThemeCmd = new RelayCommand<string>(param => { switch (param) { case "dark": Theme.ApplyTheme(ThemeColor.Dark, Theme.CurrentAccent); break; case "light": Theme.ApplyTheme(ThemeColor.Light, Theme.CurrentAccent); break; //case "modern": // ApplyResources(modernSize); // break; //case "desktop": // ApplyResources(desktopSize); // break; } }); } return _toggleThemeCmd; } } //private ICommand _openFileCmd; //public ICommand OpenFileCommand //{ // get // { // if (_openFileCmd == null) // { // _openFileCmd = new RelayCommand<object>(obj => // { // Messenger.Default.Send(new ChooseFileMessage(obj, files => // { // if (files.Count() > 1) // { // Messenger.Default.Send(new Messages.MessageBoxMessage(obj, string.Format("Selected {0} files.", files.Count()), null) { Caption = "Open file result" }); // } // else // { // Messenger.Default.Send(new Messages.MessageBoxMessage(obj, "Selected " + files.FirstOrDefault(), null) { Caption = "Open file result" }); // } // }) // { // Caption = "Open File Dialog", // Purpose = ChooseFileMessage.FilePurpose.OpenMultiple, // }); // }); // } // return _openFileCmd; // } //} //private ICommand _saveFileCmd; //public ICommand SaveFileCommand //{ // get // { // if (_saveFileCmd == null) // { // _saveFileCmd = new RelayCommand<object>(obj => // { // Messenger.Default.Send(new ChooseFileMessage(obj, files => // { // Messenger.Default.Send(new Messages.MessageBoxMessage(obj, "Selected " + files.FirstOrDefault(), null) { Caption = "Save file result" }); // }) // { // Caption = "Save File Dialog", // Purpose = ChooseFileMessage.FilePurpose.Save // }); // }); // } // return _saveFileCmd; // } //} //private ICommand _chooseFolderCmd; //public ICommand ChooseFolderCommand //{ // get // { // if (_chooseFolderCmd == null) // { // _chooseFolderCmd = new RelayCommand<object>(obj => // { // Messenger.Default.Send(new ChooseFolderMessage(obj, folder => // { // Messenger.Default.Send(new Messages.MessageBoxMessage(obj, string.Format("Selected {0}.", folder), null) { Caption = "Folder result" }); // }) // { // Caption = "Choose Folder Dialog" // }); // }); // } // return _chooseFolderCmd; // } //} } }
mit
upfluence/thrift-amqp-ruby
spec/support/handlers/thrift_helpers.rb
752
require 'thrift' require 'thrift/amqp/server' require 'thrift/amqp/client' require 'test' require 'test_handler' def run_server processor = Test::Processor.new(TestHandler.new) prot_factory = Thrift::JsonProtocolFactory.new Thrift::AMQPServer.new( processor, prot_factory, nil, amqp_uri: ENV['RABBITMQ_URL'] || 'amqp://guest:guest@127.0.0.1:5672/%2f', routing_key: 'test', exchange_name: 'test', queue_name: 'test', prefetch: ENV['PREFETCH'] || 1, consumer_tag: 'test' ).serve end def build_client trans = Thrift::AMQPClientTransport.new( ENV['RABBITMQ_URL'] || 'amqp://guest:guest@127.0.0.1:5672/%2f', 'test', 'test' ) prot = Thrift::JsonProtocol.new(trans) [Test::Client.new(prot), trans] end
mit
Mohammad-Alavi/Samandoon
config/ide-helper.php
5961
<?php return array( /* |-------------------------------------------------------------------------- | Filename & Format |-------------------------------------------------------------------------- | | The default filename (without extension) and the format (php or json) | */ 'filename' => '_ide_helper', 'format' => 'php', 'meta_filename' => '.phpstorm.meta.php', /* |-------------------------------------------------------------------------- | Fluent helpers |-------------------------------------------------------------------------- | | Set to true to generate commonly used Fluent methods | */ 'include_fluent' => true, /* |-------------------------------------------------------------------------- | Write Model Magic methods |-------------------------------------------------------------------------- | | Set to false to disable write magic methods of model | */ 'write_model_magic_where' => true, /* |-------------------------------------------------------------------------- | Helper files to include |-------------------------------------------------------------------------- | | Include helper files. By default not included, but can be toggled with the | -- helpers (-H) option. Extra helper files can be included. | */ 'include_helpers' => true, 'helper_files' => array( base_path().'/vendor/laravel/framework/src/Illuminate/Support/helpers.php', ), /* |-------------------------------------------------------------------------- | Model locations to include |-------------------------------------------------------------------------- | | Define in which directories the ide-helper:models command should look | for models. | */ 'model_locations' => array( 'app', ), /* |-------------------------------------------------------------------------- | Extra classes |-------------------------------------------------------------------------- | | These implementations are not really extended, but called with magic functions | */ 'extra' => array( 'Eloquent' => array('Illuminate\Database\Eloquent\Builder', 'Illuminate\Database\Query\Builder'), 'Session' => array('Illuminate\Session\Store'), ), 'magic' => array( 'Log' => array( 'debug' => 'Monolog\Logger::addDebug', 'info' => 'Monolog\Logger::addInfo', 'notice' => 'Monolog\Logger::addNotice', 'warning' => 'Monolog\Logger::addWarning', 'error' => 'Monolog\Logger::addError', 'critical' => 'Monolog\Logger::addCritical', 'alert' => 'Monolog\Logger::addAlert', 'emergency' => 'Monolog\Logger::addEmergency', ) ), /* |-------------------------------------------------------------------------- | Interface implementations |-------------------------------------------------------------------------- | | These interfaces will be replaced with the implementing class. Some interfaces | are detected by the helpers, others can be listed below. | */ 'interfaces' => array( ), /* |-------------------------------------------------------------------------- | Support for custom DB types |-------------------------------------------------------------------------- | | This setting allow you to map any custom database type (that you may have | created using CREATE TYPE statement or imported using database plugin | / extension to a Doctrine type. | | Each key in this array is a name of the Doctrine2 DBAL Platform. Currently valid names are: | 'postgresql', 'db2', 'drizzle', 'mysql', 'oracle', 'sqlanywhere', 'sqlite', 'mssql' | | This name is returned by getName() method of the specific Doctrine/DBAL/Platforms/AbstractPlatform descendant | | The value of the array is an array of type mappings. Key is the name of the custom type, | (for example, "jsonb" from Postgres 9.4) and the value is the name of the corresponding Doctrine2 type (in | our case it is 'json_array'. Doctrine types are listed here: | http://doctrine-dbal.readthedocs.org/en/latest/reference/types.html | | So to support jsonb in your models when working with Postgres, just add the following entry to the array below: | | "postgresql" => array( | "jsonb" => "json_array", | ), | */ 'custom_db_types' => array( ), /* |-------------------------------------------------------------------------- | Support for camel cased models |-------------------------------------------------------------------------- | | There are some Laravel packages (such as Eloquence) that allow for accessing | Eloquent model properties via camel case, instead of snake case. | | Enabling this option will support these packages by saving all model | properties as camel case, instead of snake case. | | For example, normally you would see this: | | * @property \Carbon\Carbon $created_at | * @property \Carbon\Carbon $updated_at | | With this enabled, the properties will be this: | | * @property \Carbon\Carbon $createdAt | * @property \Carbon\Carbon $updatedAt | | Note, it is currently an all-or-nothing option. | */ 'model_camel_case_properties' => false, /* |-------------------------------------------------------------------------- | Property Casts |-------------------------------------------------------------------------- | | Cast the given "real type" to the given "type". | */ 'type_overrides' => array( 'integer' => 'int', 'boolean' => 'bool', ), );
mit
ddtm/deep-smile-warp
deepwarp/Transformer5.lua
4822
-- [SublimeLinter luacheck-globals:+cudnn,deepwarp,nn] require 'cudnn' require 'nn' require 'nngraph' require 'stn' local nninit = require 'nninit' local nnq = require 'nnquery' cudnn.fastest = true local backend = cudnn local Transformer, parent = torch.class('deepwarp.Transformer5', 'nn.Container') function Transformer:__init(opts) parent.__init(self) self.batch_size = opts.batch_size if opts.delta_vec == nil then opts.delta_vec = 16 end local input_node = nn.Identity()() local mu_node = nn.Identity()() local deltas_node = nn.Identity()() local model_inputs = {input_node, mu_node, deltas_node} ---------------------------- Transform input angle into hidden representation local num_attrs = 1 if opts.use_all_attrs then num_attrs = 40 end local delta_net = self.createDeltaNet(num_attrs, opts.delta_vec) local delta_net_node = delta_net(deltas_node) ----------------------------------------------------- Calculate source pixels local src_net_input = {input_node, mu_node, delta_net_node} if opts.use_anchors then local anchors_node = nn.Identity()() table.insert(model_inputs, anchors_node) table.insert(src_net_input, anchors_node) end self.src_net = deepwarp.base.ConvSrcMs5(opts) local bhwd_src_node, mixture_weights_node = self.src_net(src_net_input):split(2) -- Wrap src_net output nodes in identity layers so that we can extract -- output tensors later. bhwd_src_node = nn.Identity()(bhwd_src_node):annotate{name = 'bhwd_src'} mixture_weights_node = nn.Identity()(mixture_weights_node):annotate{name = 'mixture_weights'} ------------------------------------------------------------- Transform input local bhwd_input_node = nn.Transpose({3, 4}, {2, 4})(input_node) local bhwd_output_node = nn.BilinearSamplerBHWD()({bhwd_input_node, bhwd_src_node}) local output_node = nn.Transpose({2, 4}, {3, 4})(bhwd_output_node) -------------------------------- Post-process output using correction palette -- output_node = deepwarp.PrintGrads('before_lcm')(output_node) output_node = self:_applyLCM( output_node, mixture_weights_node, opts.palette_size) -- output_node = deepwarp.PrintGrads('after_lcm')(output_node) ---------------------------------------------------------------- Create model self.model = nn.gModule(model_inputs, {output_node}) local model = nnq(self.model) self.bhwd_src_module = model:descendants() :attr{name = 'bhwd_src'} :only():module() self.mixture_weights_module = model:descendants() :attr{name = 'mixture_weights'} :only():module() -- Pass-through parameters of the embedded network -- (otherwise no updates will happen). self.modules = {self.model} end function Transformer:_applyLCM(output_node, mixture_weights_node, palette_size) local palette_module = deepwarp.TrainableTensor(1.0, palette_size, 3) local palette_node = backend.Sigmoid()(palette_module(output_node)) -- Mix palette and output using LCM wieghts. output_node = nn.View(1, 3, 64, 64)(output_node) palette_node = nn.View(palette_size, 3, 64, 64)( nn.Transpose({1, 3})( nn.Reshape(64, 64, self.batch_size * palette_size * 3)( nn.Replicate(64 * 64)(palette_node)))) mixture_weights_node = nn.Transpose({1, 3}, {1, 2})( nn.Reshape(3, self.batch_size, 1 + palette_size, 64, 64)( nn.Replicate(3)(mixture_weights_node))) local output_and_palette_node = nn.JoinTable(1, 4)( {output_node, palette_node}) local weighted_output_and_palette_node = nn.CMulTable()( {output_and_palette_node, mixture_weights_node}) output_node = nn.Sum(1, 4)(weighted_output_and_palette_node) return output_node end function Transformer:updateOutput(input) self.output = self.model:updateOutput(input) return self.output end function Transformer:updateGradInput(input, gradOutput) self.gradInput = self.model:updateGradInput(input, gradOutput) return self.gradInput end function Transformer:accGradParameters(input, gradOutput, scale) self.model:accGradParameters(input, gradOutput, scale) end function Transformer.createDeltaNet(num_attrs, num_hidden) num_attrs = num_attrs or 1 num_hidden = num_hidden or 16 local trainable_modules = {} local net = nn.Sequential() local m = nn.Linear(num_attrs, num_hidden) trainable_modules.fc_1 = m net:add(m) net:add(backend.ReLU()) m = nn.Linear(num_hidden, num_hidden) trainable_modules.fc_2 = m net:add(m) net:add(backend.ReLU()) -- Initialize network. for _, v in pairs(trainable_modules) do v:init('weight', nninit.kaiming, {gain = 'relu'}) :init('bias', nninit.constant, 0.0) end return net end
mit
flyelmos/Software-University
03. Software Technologies/Java Exercises/02. Boolean Variable/src/Main.java
357
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scan = new Scanner(System.in); String word = scan.nextLine(); boolean bool = (word.equals("True")); if(bool){ System.out.println("Yes"); } else { System.out.println("No"); } } }
mit
Condors/TunisiaMall
vendor/payum/core/Payum/Core/Reply/HttpResponse.php
984
<?php namespace Payum\Core\Reply; class HttpResponse extends Base { /** * @var string */ protected $content; /** * @var int */ protected $statusCode; /** * @var string[] */ protected $headers; /** * @param string $content * @param int $statusCode * @param string[] $headers */ public function __construct($content, $statusCode = 200, array $headers = array()) { $this->content = $content; $this->statusCode = $statusCode; $this->headers = $headers; } /** * @return string */ public function getContent() { return $this->content; } /** * @return int */ public function getStatusCode() { return $this->statusCode; } /** * @return string[] */ public function getHeaders() { return $this->headers; } }
mit
tamirdresher/RxInAction
AppendixC-Testing/RxLibrary.Tests/PlayingWithTestSchduler/ColdObservable.cs
3336
using System; using System.Reactive; using System.Reactive.Linq; using Microsoft.Reactive.Testing; using Xunit; using RxLibrary; using Xunit.Abstractions; namespace RxLibrary.Tests { public class CreatColdObservableTests : ReactiveTest { [Fact] public void CreatColdObservable_ShortWay() { var testScheduler = new TestScheduler(); ITestableObservable<int> coldObservable = testScheduler.CreateColdObservable<int>( // Inheritting your test class from ReactiveTest opens the following // factory methods that make your code much more fluent OnNext(20, 1), OnNext(40, 2), OnNext(60, 2), OnCompleted<int>(900) ); // Creating an observer that captures the emission it recieves var testableObserver = testScheduler.CreateObserver<int>(); // Subscribing the observer, but until TestSchduler is started, emissions // are not be emitted coldObservable .Subscribe(testableObserver); // Starting the TestScheduler means that only now emissions that were configured // will be emitted testScheduler.Start(); // Asserting that every emitted value was recieved by the observer at the // same time it was emitted coldObservable.Messages .AssertEqual(testableObserver.Messages); // Asserting that the observer was subscribed at Scheduler inital time coldObservable.Subscriptions.AssertEqual( Subscribe(0)); } [Fact] public void CreatColdObservable_LongWay() { var testScheduler = new TestScheduler(); ITestableObservable<int> coldObservable = testScheduler.CreateColdObservable<int>( // This is the long way to configure emissions. see below for a shorter one new Recorded<Notification<int>>(20, Notification.CreateOnNext<int>(1)), new Recorded<Notification<int>>(40, Notification.CreateOnNext<int>(2)), new Recorded<Notification<int>>(60, Notification.CreateOnCompleted<int>()) ); // Creating an observer that captures the emission it recieves var testableObserver = testScheduler.CreateObserver<int>(); // Subscribing the observer, but until TestSchduler is started, emissions // are not be emitted coldObservable .Subscribe(testableObserver); // Starting the TestScheduler means that only now emissions that were configured // will be emitted testScheduler.Start(); // Asserting that every emitted value was recieved by the observer at the // same time it was emitted coldObservable.Messages .AssertEqual(testableObserver.Messages); // Asserting that the observer was subscribed at Scheduler inital time coldObservable.Subscriptions.AssertEqual( Subscribe(0)); } } }
mit
darul75/dynupdate-aws
test/main.js
558
// test/main.js var dynupdate = require('../src/dynupdate-aws'); var assert = require("assert"); describe('service calls', function() { describe('with ip arguments', function() { it('return simple call result', function(done) { dynupdate.daemon({hostname: 'coucou.no-ip.biz', auth:'user:password', myip: '0.0.0.0'}, function(err, geoData) { if (err) console.log(err); assert.equal(1, 1); done(); }); }); }); });
mit
hakobe/hakoblog-python
hakoblog/config.py
486
import os class Config: """Extendable configuation class. This is also used for flask application config. """ DATABASE = "hakoblog" DATABASE_HOST = "db" DATABASE_USER = "root" DATABASE_PASS = "" TESTING = False GLOBAL_USER_NAME = "hakobe" class Test(Config): DATABASE = "hakoblog_test" TESTING = True def config(): if os.getenv("HAKOBLOG_ENV") == "test": return Test() else: return Config() CONFIG = config()
mit
xt0rted/Raygun.Owin
src/Raygun.Owin.AppBuilder/AppBuilderExtensions.cs
1858
namespace Raygun.Owin { using System; using System.Collections.Generic; using global::Owin; using Raygun.LibOwin; public static class AppBuilderExtensions { public static IAppBuilder UseRaygun(this IAppBuilder builder, Action<RaygunOptions> configuration) { if (builder == null) { throw new ArgumentNullException("builder"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } var options = new RaygunOptions(); configuration(options); return UseRaygun(builder, options); } public static IAppBuilder UseRaygun(this IAppBuilder builder, RaygunOptions options = null) { if (builder == null) { throw new ArgumentNullException("builder"); } var raygunOptions = options ?? new RaygunOptions(); if (raygunOptions.LogUnhandledExceptions) { builder.Use(typeof (RaygunUnhandledExceptionMiddleware), raygunOptions.Settings); } if (raygunOptions.LogUnhandledRequests) { builder.Use(typeof (RaygunUnhandledRequestMiddleware), raygunOptions.Settings); } SetRaygunCapabilities(builder.Properties); return builder; } private static void SetRaygunCapabilities(IDictionary<string, object> properties) { object obj; if (properties.TryGetValue(OwinConstants.CommonKeys.Capabilities, out obj)) { var capabilities = (IDictionary<string, object>) obj; capabilities["raygun.Version"] = RaygunClient.ClientVersion; } } } }
mit
EmberSands/esi_client
spec/models/put_fleets_fleet_id_members_member_id_internal_server_error_spec.rb
1144
=begin #EVE Swagger Interface #An OpenAPI for EVE Online OpenAPI spec version: 0.4.6.dev11 Generated by: https://github.com/swagger-api/swagger-codegen.git =end require 'spec_helper' require 'json' require 'date' # Unit tests for ESIClient::PutFleetsFleetIdMembersMemberIdInternalServerError # Automatically generated by swagger-codegen (github.com/swagger-api/swagger-codegen) # Please update as you see appropriate describe 'PutFleetsFleetIdMembersMemberIdInternalServerError' do before do # run before each test @instance = ESIClient::PutFleetsFleetIdMembersMemberIdInternalServerError.new end after do # run after each test end describe 'test an instance of PutFleetsFleetIdMembersMemberIdInternalServerError' do it 'should create an instact of PutFleetsFleetIdMembersMemberIdInternalServerError' do expect(@instance).to be_instance_of(ESIClient::PutFleetsFleetIdMembersMemberIdInternalServerError) end end describe 'test attribute "error"' do it 'should work' do # assertion here. ref: https://www.relishapp.com/rspec/rspec-expectations/docs/built-in-matchers end end end
mit
pdaniell/machine.js
test/Condition.Test.js
478
describe("Condiiton Test Suite", function() { it("FSA Condition Constructor Test", function() { //imports var State = Machine.State; var Condition = Machine.Condition; var controlState = new Machine.State({label:"A", isAccepting:false}); var tsCondition = new Condition({state: controlState, character:"0"}); expect(tsCondition.getState()).toBe(controlState); expect(tsCondition.getCharacter()).toBe("0"); }); });
mit
NativeScript/NativeScript
packages/core/ui/core/view-base/index.d.ts
14310
import { Property, CssProperty, CssAnimationProperty, InheritedProperty } from '../properties'; import { BindingOptions } from '../bindable'; import { Observable } from '../../../data/observable'; import { Style } from '../../styling/style'; import { CoreTypes } from '../../../core-types'; import { Page } from '../../page'; import { Order, FlexGrow, FlexShrink, FlexWrapBefore, AlignSelf } from '../../layouts/flexbox-layout'; import { Length } from '../../styling/style-properties'; import { DOMNode } from '../../../debugger/dom-node'; /** * Iterates through all child views (via visual tree) and executes a function. * @param view - Starting view (parent container). * @param callback - A function to execute on every child. If function returns false it breaks the iteration. */ export function eachDescendant(view: ViewBase, callback: (child: ViewBase) => boolean); /** * Gets an ancestor from a given type. * @param view - Starting view (child view). * @param criterion - The type of ancestor view we are looking for. Could be a string containing a class name or an actual type. * Returns an instance of a view (if found), otherwise undefined. */ export function getAncestor(view: ViewBase, criterion: string | Function): ViewBase; export function isEventOrGesture(name: string, view: ViewBase): boolean; /** * Gets a child view by id. * @param view - The parent (container) view of the view to look for. * @param id - The id of the view to look for. * Returns an instance of a view (if found), otherwise undefined. */ export function getViewById(view: ViewBase, id: string): ViewBase; /** * Gets a child view by domId. * @param view - The parent (container) view of the view to look for. * @param domId - The id of the view to look for. * Returns an instance of a view (if found), otherwise undefined. */ export function getViewByDomId(view: ViewBase, domId: number): ViewBase; export interface ShowModalOptions { /** * Any context you want to pass to the modally shown view. This same context will be available in the arguments of the shownModally event handler. */ context: any; /** * A function that will be called when the view is closed. Any arguments provided when calling ShownModallyData.closeCallback will be available here. */ closeCallback: Function; /** * An optional parameter specifying whether to show the modal view in full-screen mode. */ fullscreen?: boolean; /** * An optional parameter specifying whether to show the modal view with animation. */ animated?: boolean; /** * An optional parameter specifying whether to stretch the modal view when not in full-screen mode. */ stretched?: boolean; /** * An optional parameter that specify options specific to iOS as an object. */ ios?: { /** * The UIModalPresentationStyle to be used when showing the dialog in iOS . */ presentationStyle?: any /* UIModalPresentationStyle */; /** * width of the popup dialog */ width?: number; /** * height of the popup dialog */ height?: number; }; android?: { /** * @deprecated Use ShowModalOptions.cancelable instead. * An optional parameter specifying whether the modal view can be dismissed when not in full-screen mode. */ cancelable?: boolean; /** * An optional parameter specifying the windowSoftInputMode of the dialog window * For possible values see https://developer.android.com/reference/android/view/WindowManager.LayoutParams#softInputMode */ windowSoftInputMode?: number; }; /** * An optional parameter specifying whether the modal view can be dismissed when not in full-screen mode. */ cancelable?: boolean; } export abstract class ViewBase extends Observable { // Dynamic properties. left: CoreTypes.LengthType; top: CoreTypes.LengthType; effectiveLeft: number; effectiveTop: number; dock: 'left' | 'top' | 'right' | 'bottom'; row: number; col: number; /** * Setting `column` property is the same as `col` */ column: number; rowSpan: number; colSpan: number; /** * Setting `columnSpan` property is the same as `colSpan` */ columnSpan: number; domNode: DOMNode; order: Order; flexGrow: FlexGrow; flexShrink: FlexShrink; flexWrapBefore: FlexWrapBefore; alignSelf: AlignSelf; /** * @private * Module name when the view is a module root. Otherwise, it is undefined. */ _moduleName?: string; //@private /** * @private */ _oldLeft: number; /** * @private */ _oldTop: number; /** * @private */ _oldRight: number; /** * @private */ _oldBottom: number; /** * @private */ _defaultPaddingTop: number; /** * @private */ _defaultPaddingRight: number; /** * @private */ _defaultPaddingBottom: number; /** * @private */ _defaultPaddingLeft: number; /** * A property bag holding suspended native updates. * Native setters that had to execute while there was no native view, * or the view was detached from the visual tree etc. will accumulate in this object, * and will be applied when all prerequisites are met. * @private */ _suspendedUpdates: { [propertyName: string]: Property<any, any> | CssProperty<Style, any> | CssAnimationProperty<Style, any>; }; //@endprivate /** * Shows the View contained in moduleName as a modal view. * @param moduleName - The name of the module to load starting from the application root. * @param modalOptions - A ShowModalOptions instance */ showModal(moduleName: string, modalOptions?: ShowModalOptions): ViewBase; /** * Shows the view passed as parameter as a modal view. * @param view - View instance to be shown modally. * @param modalOptions - A ShowModalOptions instance */ showModal(view: ViewBase, modalOptions?: ShowModalOptions): ViewBase; /** * Closes the current modal view that this page is showing. * @param context - Any context you want to pass back to the host when closing the modal view. */ closeModal(context?: any): void; public effectiveMinWidth: number; public effectiveMinHeight: number; public effectiveWidth: number; public effectiveHeight: number; public effectiveMarginTop: number; public effectiveMarginRight: number; public effectiveMarginBottom: number; public effectiveMarginLeft: number; public effectivePaddingTop: number; public effectivePaddingRight: number; public effectivePaddingBottom: number; public effectivePaddingLeft: number; public effectiveBorderTopWidth: number; public effectiveBorderRightWidth: number; public effectiveBorderBottomWidth: number; public effectiveBorderLeftWidth: number; /** * String value used when hooking to loaded event. */ public static loadedEvent: string; /** * String value used when hooking to unloaded event. */ public static unloadedEvent: string; public ios: any; public android: any; /** * returns the native UIViewController. */ public viewController: any; /** * read-only. If you want to set out-of-band the nativeView use the setNativeView method. */ public nativeViewProtected: any; public nativeView: any; public bindingContext: any; /** * Gets or sets if the view is reusable. * Reusable views are not automatically destroyed when removed from the View tree. */ public reusable: boolean; /** * Gets the name of the constructor function for this instance. E.g. for a Button class this will return "Button". */ public typeName: string; /** * Gets the parent view. This property is read-only. */ public readonly parent: ViewBase; /** * Gets the template parent or the native parent. Sets the template parent. */ public parentNode: ViewBase; /** * Gets or sets the id for this view. */ public id: string; /** * Gets or sets the CSS class name for this view. */ public className: string; /** * Gets owner page. This is a read-only property. */ public readonly page: Page; /** * Gets the style object associated to this view. */ public readonly style: Style; /** * Returns true if visibility is set to 'collapse'. * Readonly property */ public isCollapsed: boolean; public readonly isLoaded: boolean; /** * Returns the child view with the specified id. */ public getViewById<T extends ViewBase>(id: string): T; /** * Returns the child view with the specified domId. */ public getViewByDomId<T extends ViewBase>(id: number): T; /** * Load view. * @param view to load. */ public loadView(view: ViewBase): void; /** * Unload view. * @param view to unload. */ public unloadView(view: ViewBase): void; public onLoaded(): void; public onUnloaded(): void; public onResumeNativeUpdates(): void; public bind(options: BindingOptions, source?: Object): void; public unbind(property: string): void; /** * Invalidates the layout of the view and triggers a new layout pass. */ public requestLayout(): void; /** * Iterates over children of type ViewBase. * @param callback Called for each child of type ViewBase. Iteration stops if this method returns falsy value. */ public eachChild(callback: (child: ViewBase) => boolean): void; public _addView(view: ViewBase, atIndex?: number): void; /** * Method is intended to be overridden by inheritors and used as "protected" */ public _addViewCore(view: ViewBase, atIndex?: number): void; public _removeView(view: ViewBase): void; /** * Method is intended to be overridden by inheritors and used as "protected" */ public _removeViewCore(view: ViewBase): void; public _parentChanged(oldParent: ViewBase): void; /** * Method is intended to be overridden by inheritors and used as "protected" */ public _dialogClosed(): void; /** * Method is intended to be overridden by inheritors and used as "protected" */ public _onRootViewReset(): void; _domId: number; _cssState: any /* "ui/styling/style-scope" */; /** * @private * Notifies each child's css state for change, recursively. * Either the style scope, className or id properties were changed. */ _onCssStateChange(): void; public cssClasses: Set<string>; public cssPseudoClasses: Set<string>; public _goToVisualState(state: string): void; public setInlineStyle(style: string): void; _context: any /* android.content.Context */; /** * Setups the UI for ViewBase and all its children recursively. * This method should *not* be overridden by derived views. */ _setupUI(context: any /* android.content.Context */, atIndex?: number): void; /** * Tears down the UI for ViewBase and all its children recursively. * This method should *not* be overridden by derived views. */ _tearDownUI(force?: boolean): void; /** * Tears down the UI of a reusable node by making it no longer reusable. * @see _tearDownUI * @param forceDestroyChildren Force destroy the children (even if they are reusable) */ destroyNode(forceDestroyChildren?: boolean): void; /** * Creates a native view. * Returns either android.view.View or UIView. */ createNativeView(): Object; /** * Initializes properties/listeners of the native view. */ initNativeView(): void; /** * Clean up references to the native view. */ disposeNativeView(): void; /** * Resets properties/listeners set to the native view. */ resetNativeView(): void; /** * Set the nativeView field performing extra checks and updates to the native properties on the new view. * Use in cases where the createNativeView is not suitable. * As an example use in item controls where the native parent view will create the native views for child items. */ setNativeView(view: any): void; _isAddedToNativeVisualTree: boolean; /** * Performs the core logic of adding a child view to the native visual tree. Returns true if the view's native representation has been successfully added, false otherwise. */ _addViewToNativeVisualTree(view: ViewBase, atIndex?: number): boolean; _removeViewFromNativeVisualTree(view: ViewBase): void; _childIndexToNativeChildIndex(index?: number): number; /** * @protected * @unstable * A widget can call this method to add a matching css pseudo class. */ public addPseudoClass(name: string): void; /** * @protected * @unstable * A widget can call this method to discard matching css pseudo class. */ public deletePseudoClass(name: string): void; /** * @unstable * Ensures a dom-node for this view. */ public ensureDomNode(); public recycleNativeView: 'always' | 'never' | 'auto'; /** * @private */ public _isPaddingRelative: boolean; /** * @private */ public _ignoreFlexMinWidthHeightReset: boolean; public _styleScope: any; /** * @private */ public _automaticallyAdjustsScrollViewInsets: boolean; /** * @private */ _isStyleScopeHost: boolean; /** * @private */ public _layoutParent(): void; /** * Determines the depth of suspended updates. * When the value is 0 the current property updates are not batched nor scoped and must be immediately applied. * If the value is 1 or greater, the current updates are batched and does not have to provide immediate update. * Do not set this field, the _batchUpdate method is responsible to keep the count up to date, * as well as adding/rmoving the view to/from the visual tree. */ public _suspendNativeUpdatesCount: number; /** * Allow multiple updates to be performed on the instance at once. */ public _batchUpdate<T>(callback: () => T): T; /** * @private */ _setupAsRootView(context: any): void; /** * When returning true the callLoaded method will be run in setTimeout * Method is intended to be overridden by inheritors and used as "protected" */ _shouldDelayLayout(): boolean; /** * @private */ _inheritStyleScope(styleScope: any /* StyleScope */): void; /** * @private */ callLoaded(): void; /** * @private */ callUnloaded(): void; //@endprivate } export class Binding { constructor(target: ViewBase, options: BindingOptions); public bind(source: Object): void; public unbind(); } export const idProperty: Property<any, string>; export const classNameProperty: Property<any, string>; export const bindingContextProperty: InheritedProperty<any, any>; /** * Converts string into boolean value. * Throws error if value is not 'true' or 'false'. */ export function booleanConverter(v: string): boolean;
mit
joeleyu/coc
application/config/autoload.php
3992
<?php defined('BASEPATH') OR exit('No direct script access allowed'); /* | ------------------------------------------------------------------- | AUTO-LOADER | ------------------------------------------------------------------- | This file specifies which systems should be loaded by default. | | In order to keep the framework as light-weight as possible only the | absolute minimal resources are loaded by default. For example, | the database is not connected to automatically since no assumption | is made regarding whether you intend to use it. This file lets | you globally define which systems you would like loaded with every | request. | | ------------------------------------------------------------------- | Instructions | ------------------------------------------------------------------- | | These are the things you can load automatically: | | 1. Packages | 2. Libraries | 3. Drivers | 4. Helper files | 5. Custom config files | 6. Language files | 7. Models | */ /* | ------------------------------------------------------------------- | Auto-load Packages | ------------------------------------------------------------------- | Prototype: | | $autoload['packages'] = array(APPPATH.'third_party', '/usr/local/shared'); | */ $autoload['packages'] = array(); /* | ------------------------------------------------------------------- | Auto-load Libraries | ------------------------------------------------------------------- | These are the classes located in system/libraries/ or your | application/libraries/ directory, with the addition of the | 'database' library, which is somewhat of a special case. | | Prototype: | | $autoload['libraries'] = array('database', 'email', 'session'); | | You can also supply an alternative library name to be assigned | in the controller: | | $autoload['libraries'] = array('user_agent' => 'ua'); */ $autoload['libraries'] = array('database','form_validation', 'session','ion_auth'); /* | ------------------------------------------------------------------- | Auto-load Drivers | ------------------------------------------------------------------- | These classes are located in system/libraries/ or in your | application/libraries/ directory, but are also placed inside their | own subdirectory and they extend the CI_Driver_Library class. They | offer multiple interchangeable driver options. | | Prototype: | | $autoload['drivers'] = array('cache'); */ $autoload['drivers'] = array(); /* | ------------------------------------------------------------------- | Auto-load Helper Files | ------------------------------------------------------------------- | Prototype: | | $autoload['helper'] = array('url', 'file'); */ $autoload['helper'] = array('url','form','text','file','language','string'); /* | ------------------------------------------------------------------- | Auto-load Config files | ------------------------------------------------------------------- | Prototype: | | $autoload['config'] = array('config1', 'config2'); | | NOTE: This item is intended for use ONLY if you have created custom | config files. Otherwise, leave it blank. | */ $autoload['config'] = array('cms_settings'); /* | ------------------------------------------------------------------- | Auto-load Language files | ------------------------------------------------------------------- | Prototype: | | $autoload['language'] = array('lang1', 'lang2'); | | NOTE: Do not include the "_lang" part of your file. For example | "codeigniter_lang.php" would be referenced as array('codeigniter'); | */ $autoload['language'] = array(); /* | ------------------------------------------------------------------- | Auto-load Models | ------------------------------------------------------------------- | Prototype: | | $autoload['model'] = array('first_model', 'second_model'); | | You can also supply an alternative model name to be assigned | in the controller: | | $autoload['model'] = array('first_model' => 'first'); */ $autoload['model'] = array();
mit
joshterainsights/Grad_Apps
public/modules/applications/tests/applications.client.controller.test.js
5902
'use strict'; (function() { // Applications Controller Spec describe('Applications Controller Tests', function() { // Initialize global variables var ApplicationsController, scope, $httpBackend, $stateParams, $event, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Applications controller. ApplicationsController = $controller('ApplicationsController', { $scope: scope }); })); it('$scope.find() should create an array with at least one Application object fetched from XHR', inject(function(Applications) { // Create sample Application using the Applications service var sampleApplication = new Applications({ name: 'New Application' }); // Create a sample Applications array that includes the new Application var sampleApplications = [sampleApplication]; // Set GET response $httpBackend.expectGET('applications').respond(sampleApplications); $httpBackend.expectGET('applications').respond(sampleApplications); // Run controller functionality scope.find(); $httpBackend.flush(); // Test scope value expect(scope.applications).toEqualData(sampleApplications); })); it('$scope.findOne() should create an array with one Application object fetched from XHR using a applicationId URL parameter', inject(function(Applications) { // Define a sample Application object var sampleApplication = new Applications({ name: 'New Application' }); // Set the URL parameter $stateParams.applicationId = '525a8422f6d0f87f0e407a33'; // Set GET response $httpBackend.expectGET('applications').respond(200); $httpBackend.expectGET(/applications\/([0-9a-fA-F]{24})$/).respond(sampleApplication); // Run controller functionality scope.findOne(); $httpBackend.flush(); // Test scope value expect(scope.application).toEqualData(sampleApplication); })); it('$scope.create() with valid form data should send a POST request with the form input values and then locate to new object URL', inject(function(Applications) { // Create a sample Application object var sampleApplicationPostData = new Applications({ name: 'New Application' }); // Create a sample Application response var sampleApplicationResponse = new Applications({ _id: '525cf20451979dea2c000001', name: 'New Application' }); // Fixture mock form input values scope.name = 'New Application'; // Set POST response $httpBackend.expectGET('applications').respond(200); $httpBackend.expectPOST('applications', sampleApplicationPostData).respond(sampleApplicationResponse); // Run controller functionality scope.create(); $httpBackend.flush(); // Test form inputs are reset expect(scope.name).toEqual(''); // Test URL redirection after the Application was created expect($location.path()).toBe('/applications/' + sampleApplicationResponse._id); })); it('$scope.update() should update a valid Application', inject(function(Applications) { // Define a sample Application put data var sampleApplicationPutData = new Applications({ _id: '525cf20451979dea2c000001', name: 'New Application' }); // Mock Application in scope scope.application = sampleApplicationPutData; // Set PUT response $httpBackend.expectGET('applications').respond(200); $httpBackend.expectPUT(/applications\/([0-9a-fA-F]{24})$/).respond(); // Run controller functionality scope.update(); $httpBackend.flush(); // Test URL location to new object expect($location.path()).toBe('/applications/' + sampleApplicationPutData._id + '/edit'); })); it('$scope.remove() should send a DELETE request with a valid applicationId and remove the Application from the scope', inject(function(Applications) { // Create new Application object var sampleApplication = new Applications({ _id: '525a8422f6d0f87f0e407a33' }); // Create new Applications array and include the Application scope.applications = [sampleApplication]; // Set expected DELETE response $httpBackend.expectGET('applications').respond(200); $httpBackend.expectDELETE(/applications\/([0-9a-fA-F]{24})$/).respond(204); // Run controller functionality scope.remove(sampleApplication); $httpBackend.flush(); // Test array after successful delete expect(scope.applications.length).toBe(0); })); it('Testing toggle Min function (date picker)', inject(function(Applications) { // Create new Application object scope.toggleMin(); expect(scope.minDate).toBe(null); })); }); }());
mit
xezw211/wx
resources/views/admin/user/permission.blade.php
325
@if($status) <h3>用户: {{$user->name}}</h3> <ul class="list-group"> @foreach($user_permissions as $user_permission) <li class="list-group-item list-group-item-default">{{$user_permission->slug}}--{{$user_permission->name}}--{{$user_permission->description}}</li> @endforeach </ul> @else <p>{{$msg}}</p> @endif
mit
findologic/sentry-browser-demo
test/unit/sentry-browser-demo.js
194
describe('sentryBrowserDemo', () => { describe('Raven.js wrapper', () => { it('should not pollute the window object', () => { expect(window.Raven).to.be.undefined; }); }); });
mit
mediawiki-utilities/python-mwsessions
mwsessions/defaults.py
160
CUTOFF = 60 * 60 """ Default cutoff is set to one hour. This is almost always a good choice. See https://meta.wikimedia.org/wiki/Research:Activity_session """
mit
enlim/core
app/Models/Mship/Account/Note/Format.php
1115
<?php namespace App\Models\Mship\Account\Note; use App\Traits\RecordsActivity; use Illuminate\Database\Eloquent\SoftDeletes as SoftDeletingTrait; /** * App\Models\Mship\Account\Note\Format * * @property-read \App\Models\Mship\Account\Note $note * @method static bool|null forceDelete() * @method static \Illuminate\Database\Query\Builder|\App\Models\Mship\Account\Note\Format onlyTrashed() * @method static bool|null restore() * @method static \Illuminate\Database\Query\Builder|\App\Models\Mship\Account\Note\Format withTrashed() * @method static \Illuminate\Database\Query\Builder|\App\Models\Mship\Account\Note\Format withoutTrashed() * @mixin \Eloquent */ class Format extends \Eloquent { use SoftDeletingTrait, RecordsActivity; protected $table = 'mship_account_note_format'; protected $primaryKey = 'account_note_format_id'; protected $dates = ['created_at', 'deleted_at']; protected $hidden = ['account_note_format_id']; public function note() { return $this->belongsTo(\App\Models\Mship\Account\Note::class, 'format_id', 'account_note_format_id'); } }
mit
MIAUUUUUUU/Sticky.io
src/MiauCore.IO/Domain/Services/NewsService.cs
1013
using MiauCore.IO.Data; using MiauCore.IO.Domain.Repository; using MiauCore.IO.Models; using Microsoft.EntityFrameworkCore; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace MiauCore.IO.Domain.Services { public class NewsService { private ApplicationDbContext _context; public NewsService(ApplicationDbContext context) { _context = context; } public async Task<News> GetNews(int id) { var news = await _context.News .Include(product => product.Product) .FirstOrDefaultAsync(n => n.Id == id); return news; } public async Task<ICollection<News>> ListNews() { var news = await _context.News .Include(product => product.Product) .Where(n => n.IsActive) .ToListAsync(); return news.OrderByDescending(x => x.WriteDate).ToList(); } } }
mit
rajdeep26/Java-mini-project
src/DisplayData.java
2000
import java.awt.*; import java.io.IOException; import javax.swing.*; import java.io.*; public class DisplayData extends JApplet { public DisplayData() { Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); final String[] colHeads = { "Phone Name", "Phone Type", "Operating System","Processor","Camera","Screen Size","Memory" ,"Price"}; int var; String DATA[][]; DATA=new String[100][100]; int linecount = 0; try { BufferedReader bf = new BufferedReader(new FileReader("Mobiles.txt")); String line; int i=0,j=0; DATA=new String[100][100]; while (( DATA[i][j]= bf.readLine()) != null) { linecount++; j++; if(j==8) { i=i+1; j=0; } } var=linecount/8; bf.close(); } catch (IOException e) { System.out.println("IO Error Occurred: " + e.toString()); } var=linecount/6; final Object[][] data=new Object[100][8]; for(int i=0;i<var;i++) { for(int j=0;j<8;j++) { data[i][j]= DATA[i][j]; } } JTable table = new JTable(data, colHeads); int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED; int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp = new JScrollPane(table, v, h); contentPane.add(jsp, BorderLayout.CENTER); } }
mit
yoanngern/gospelcenter
src/gospelcenter/UserBundle/gospelcenterUserBundle.php
217
<?php namespace gospelcenter\UserBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class gospelcenterUserBundle extends Bundle { public function getParent() { return 'FOSUserBundle'; } }
mit
dmeikle/GossamerCMS-DB-V2
src/components/shoppingcart/entities/Client.php
334
<?php namespace components\shoppingcart\entities; use entities\AbstractEntity; use database\SQLInterface; class Client extends AbstractEntity implements SQLInterface { public function __construct(){ $this->primaryKeys = array('id'); parent::__construct(); $this->tablename = 'Clients'; } }
mit
WsdlToPhp/PackagePayPal
src/StructType/ManageRecurringPaymentsProfileStatusRequestType.php
2351
<?php namespace PayPal\StructType; use \WsdlToPhp\PackageBase\AbstractStructBase; /** * This class stands for ManageRecurringPaymentsProfileStatusRequestType StructType * @subpackage Structs * @author WsdlToPhp <contact@wsdltophp.com> */ class ManageRecurringPaymentsProfileStatusRequestType extends AbstractRequestType { /** * The ManageRecurringPaymentsProfileStatusRequestDetails * Meta information extracted from the WSDL * - ref: ebl:ManageRecurringPaymentsProfileStatusRequestDetails * @var \PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType */ public $ManageRecurringPaymentsProfileStatusRequestDetails; /** * Constructor method for ManageRecurringPaymentsProfileStatusRequestType * @uses ManageRecurringPaymentsProfileStatusRequestType::setManageRecurringPaymentsProfileStatusRequestDetails() * @param \PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType $manageRecurringPaymentsProfileStatusRequestDetails */ public function __construct(\PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType $manageRecurringPaymentsProfileStatusRequestDetails = null) { $this ->setManageRecurringPaymentsProfileStatusRequestDetails($manageRecurringPaymentsProfileStatusRequestDetails); } /** * Get ManageRecurringPaymentsProfileStatusRequestDetails value * @return \PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType|null */ public function getManageRecurringPaymentsProfileStatusRequestDetails() { return $this->ManageRecurringPaymentsProfileStatusRequestDetails; } /** * Set ManageRecurringPaymentsProfileStatusRequestDetails value * @param \PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType $manageRecurringPaymentsProfileStatusRequestDetails * @return \PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestType */ public function setManageRecurringPaymentsProfileStatusRequestDetails(\PayPal\StructType\ManageRecurringPaymentsProfileStatusRequestDetailsType $manageRecurringPaymentsProfileStatusRequestDetails = null) { $this->ManageRecurringPaymentsProfileStatusRequestDetails = $manageRecurringPaymentsProfileStatusRequestDetails; return $this; } }
mit
SpongePowered/SpongeCommon
src/main/java/org/spongepowered/common/data/processor/data/item/BreakableDataProcessor.java
4203
/* * This file is part of Sponge, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.common.data.processor.data.item; import com.google.common.collect.ImmutableSet; import net.minecraft.item.ItemStack; import org.spongepowered.api.block.BlockType; import org.spongepowered.api.data.DataTransactionResult; import org.spongepowered.api.data.key.Keys; import org.spongepowered.api.data.manipulator.immutable.item.ImmutableBreakableData; import org.spongepowered.api.data.manipulator.mutable.item.BreakableData; import org.spongepowered.api.data.value.ValueContainer; import org.spongepowered.api.data.value.immutable.ImmutableSetValue; import org.spongepowered.api.data.value.mutable.SetValue; import org.spongepowered.common.data.manipulator.mutable.item.SpongeBreakableData; import org.spongepowered.common.data.processor.common.AbstractItemSingleDataProcessor; import org.spongepowered.common.data.processor.common.BreakablePlaceableUtils; import org.spongepowered.common.data.value.immutable.ImmutableSpongeSetValue; import org.spongepowered.common.data.value.mutable.SpongeSetValue; import org.spongepowered.common.util.Constants; import java.util.Optional; import java.util.Set; public class BreakableDataProcessor extends AbstractItemSingleDataProcessor<Set<BlockType>, SetValue<BlockType>, BreakableData, ImmutableBreakableData> { public BreakableDataProcessor() { super(stack -> true, Keys.BREAKABLE_BLOCK_TYPES); } @Override protected BreakableData createManipulator() { return new SpongeBreakableData(); } @Override protected Optional<Set<BlockType>> getVal(ItemStack itemStack) { return BreakablePlaceableUtils.get(itemStack, Constants.Item.ITEM_BREAKABLE_BLOCKS); } @Override protected boolean set(ItemStack itemStack, Set<BlockType> value) { return BreakablePlaceableUtils.set(itemStack, Constants.Item.ITEM_BREAKABLE_BLOCKS, value); } @Override public DataTransactionResult removeFrom(ValueContainer<?> container) { if (supports(container)) { ItemStack stack = (ItemStack) container; Optional<Set<BlockType>> old = getVal(stack); if (!old.isPresent()) { return DataTransactionResult.successNoData(); } if (set((ItemStack) container, ImmutableSet.<BlockType>of())) { return DataTransactionResult.successRemove(constructImmutableValue(old.get())); } return DataTransactionResult.builder().result(DataTransactionResult.Type.ERROR).build(); } return DataTransactionResult.failNoData(); } @Override protected SetValue<BlockType> constructValue(Set<BlockType> actualValue) { return new SpongeSetValue<>(Keys.BREAKABLE_BLOCK_TYPES, actualValue); } @Override protected ImmutableSetValue<BlockType> constructImmutableValue(Set<BlockType> value) { return new ImmutableSpongeSetValue<>(Keys.BREAKABLE_BLOCK_TYPES, value); } }
mit
yigexiangfa/the_data
app/channels/done_channel.rb
213
class DoneChannel < ApplicationCable::Channel def subscribed stream_from "done:#{current_receiver.class.base_class.name}:#{current_receiver.id}" if current_receiver end def unsubscribed end end
mit