repo_name
stringlengths
4
116
path
stringlengths
4
379
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
sanjoydesk/cygniteframework
vendor/cygnite/framework/src/Cygnite/Common/SessionManager/Native/Session.php
6672
<?php namespace Cygnite\Common\SessionManager\Native; use Cygnite\Helpers\Config; use Cygnite\Helpers\String; use Cygnite\Common\SessionManager\Manager; use Cygnite\Common\SessionManager\SessionInterface; use Cygnite\Common\SessionManager\Session as SessionManager; use Cygnite\Common\SessionManager\Exceptions\SessionNotStartedException; class Session extends Manager implements SessionInterface { private $wrapper; /** * We will create instance of session wrapper and * validate existing session - if session is invalid, we will resets it * * @param string $sessionName * @param string $cacheLimiter * @param null $wrapperInstance */ public function __construct($sessionName = null, $cacheLimiter = null, $wrapperInstance = null) { /* |We will set session name. |If user doesn't provide session name we will set default name */ $this->name($sessionName); /* |We will set cache limiter */ $this->cacheLimiter($cacheLimiter); $this->setWrapperInstance($wrapperInstance); /* | We will check is http referrer if it is not same as current url, | meaning fake session. We will destroy the fake session */ $this->checkReferer(); /* |Check if session started if not we will start new session |if session started already we will try */ if (!$this->started()) { $this->startSession(); } $this->storage = & $_SESSION; /* | Check csrf token already exists into session | else regenerate the token */ $this->checkToken(); } /** * @param $instance */ public function setWrapperInstance($instance) { $this->wrapper = $instance; } /** * Get the instance of session manager * * @return null */ public function getWrapper() { return isset($this->wrapper) ? $this->wrapper : null; } public function setSessionConfig() { /* | Get user configuration */ $config = Config::get('config.session'); $sessionManager = $this->getWrapper(); $sessionManager->setHash(); // set session hash // We will use session cookie if configured if ($config['use_session_cookie']) { $sessionManager->useOnlyCookie(); // use cookie } // Make sure the session cookie is not accessible via javascript. $sessionManager->setCookieParams($config['secure'], $config['httponly']); } /** * Starts session * * @throws \RuntimeException */ protected function startSession() { if (@session_status() === \PHP_SESSION_ACTIVE) { throw new SessionNotStartedException('Session started already!'); } if (ini_get('session.use_cookies') && headers_sent($file, $line)) { throw new SessionNotStartedException(sprintf('Unable to start session, headers already sent by "%s" at line %d.', $file, $line)); } $this->setSessionConfig(); /* | We will start session, if fails | we will throw exception to user */ if (!session_start()) { throw new SessionNotStartedException('Unable to start session'); } } /** * Destroy all session data and regenerates session ID * * @return $this */ public function destroy() { unset($this->storage); $_SESSION = []; /* |We will destroy existing session and start |new session for user */ session_destroy(); $this->startSession(); $this->storage = & $_SESSION; return $this; } /** * We will check referer url from the same server or not * else we will destroy the session */ protected function checkReferer() { if (!empty($_SERVER['HTTP_REFERER'])) { $url = parse_url($_SERVER['HTTP_REFERER']); if ($url['host'] != $_SERVER['HTTP_HOST']) { session_destroy(); // destroy fake session } } } /** * Regenerate the session ID * * @return $this */ public function regenerate() { // we will regenerate session ID session_regenerate_id(true); session_write_close(); if (isset($_SESSION)) { $data = $_SESSION; session_start(); $_SESSION = $data; } else { session_start(); } // we will store session global variable reference into storage property $this->storage = & $_SESSION; return $this; } /** * Check is session started, if set then return session id * * @param string $id * * @return string */ public function started($id = null) { if ($id !== null) { session_id($id); } return session_id(); } /** * Set or return session name * * @param string $name * * @return string */ public function name($name = null) { if ($name !== null) { session_name($name); } return session_name(); } /** * Set or return session cache limiter * * @param string $cacheLimiter * * @return string */ public function cacheLimiter($cacheLimiter = null) { if ($cacheLimiter !== null) { session_cache_limiter($cacheLimiter); } return session_cache_limiter(); } /** * @reference http://stackoverflow.com/questions/24843309/laravel-4-csrf-token-never-changes */ public function checkToken() { /* | We will check if token already exists in session | else we will regenerate token id */ if (! $this->has('_token')) { $this->regenerateToken(); } } /** * Regenerate the CSRF token value. * * @return void */ public function regenerateToken() { $this->set('_token', String::random('alnum', 32)); } /** * Get the CSRF token value. * * @return string */ public function token() { return $this->get('_token'); } /** * We will call Manager method * * @param $method * @param $args * @return mixed */ public function __call($method, $args) { return call_user_func_array([new Manager(), $method], [$args]); } }
mit
robertkrimen/otto
builtin_object.go
7555
package otto import ( "fmt" ) // Object func builtinObject(call FunctionCall) Value { value := call.Argument(0) switch value.kind { case valueUndefined, valueNull: return toValue_object(call.runtime.newObject()) } return toValue_object(call.runtime.toObject(value)) } func builtinNewObject(self *_object, argumentList []Value) Value { value := valueOfArrayIndex(argumentList, 0) switch value.kind { case valueNull, valueUndefined: case valueNumber, valueString, valueBoolean: return toValue_object(self.runtime.toObject(value)) case valueObject: return value default: } return toValue_object(self.runtime.newObject()) } func builtinObject_valueOf(call FunctionCall) Value { return toValue_object(call.thisObject()) } func builtinObject_hasOwnProperty(call FunctionCall) Value { propertyName := call.Argument(0).string() thisObject := call.thisObject() return toValue_bool(thisObject.hasOwnProperty(propertyName)) } func builtinObject_isPrototypeOf(call FunctionCall) Value { value := call.Argument(0) if !value.IsObject() { return falseValue } prototype := call.toObject(value).prototype thisObject := call.thisObject() for prototype != nil { if thisObject == prototype { return trueValue } prototype = prototype.prototype } return falseValue } func builtinObject_propertyIsEnumerable(call FunctionCall) Value { propertyName := call.Argument(0).string() thisObject := call.thisObject() property := thisObject.getOwnProperty(propertyName) if property != nil && property.enumerable() { return trueValue } return falseValue } func builtinObject_toString(call FunctionCall) Value { var result string if call.This.IsUndefined() { result = "[object Undefined]" } else if call.This.IsNull() { result = "[object Null]" } else { result = fmt.Sprintf("[object %s]", call.thisObject().class) } return toValue_string(result) } func builtinObject_toLocaleString(call FunctionCall) Value { toString := call.thisObject().get("toString") if !toString.isCallable() { panic(call.runtime.panicTypeError()) } return toString.call(call.runtime, call.This) } func builtinObject_getPrototypeOf(call FunctionCall) Value { objectValue := call.Argument(0) object := objectValue._object() if object == nil { panic(call.runtime.panicTypeError()) } if object.prototype == nil { return nullValue } return toValue_object(object.prototype) } func builtinObject_getOwnPropertyDescriptor(call FunctionCall) Value { objectValue := call.Argument(0) object := objectValue._object() if object == nil { panic(call.runtime.panicTypeError()) } name := call.Argument(1).string() descriptor := object.getOwnProperty(name) if descriptor == nil { return Value{} } return toValue_object(call.runtime.fromPropertyDescriptor(*descriptor)) } func builtinObject_defineProperty(call FunctionCall) Value { objectValue := call.Argument(0) object := objectValue._object() if object == nil { panic(call.runtime.panicTypeError()) } name := call.Argument(1).string() descriptor := toPropertyDescriptor(call.runtime, call.Argument(2)) object.defineOwnProperty(name, descriptor, true) return objectValue } func builtinObject_defineProperties(call FunctionCall) Value { objectValue := call.Argument(0) object := objectValue._object() if object == nil { panic(call.runtime.panicTypeError()) } properties := call.runtime.toObject(call.Argument(1)) properties.enumerate(false, func(name string) bool { descriptor := toPropertyDescriptor(call.runtime, properties.get(name)) object.defineOwnProperty(name, descriptor, true) return true }) return objectValue } func builtinObject_create(call FunctionCall) Value { prototypeValue := call.Argument(0) if !prototypeValue.IsNull() && !prototypeValue.IsObject() { panic(call.runtime.panicTypeError()) } object := call.runtime.newObject() object.prototype = prototypeValue._object() propertiesValue := call.Argument(1) if propertiesValue.IsDefined() { properties := call.runtime.toObject(propertiesValue) properties.enumerate(false, func(name string) bool { descriptor := toPropertyDescriptor(call.runtime, properties.get(name)) object.defineOwnProperty(name, descriptor, true) return true }) } return toValue_object(object) } func builtinObject_isExtensible(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { return toValue_bool(object.extensible) } panic(call.runtime.panicTypeError()) } func builtinObject_preventExtensions(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { object.extensible = false } else { panic(call.runtime.panicTypeError()) } return object } func builtinObject_isSealed(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { if object.extensible { return toValue_bool(false) } result := true object.enumerate(true, func(name string) bool { property := object.getProperty(name) if property.configurable() { result = false } return true }) return toValue_bool(result) } panic(call.runtime.panicTypeError()) } func builtinObject_seal(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { object.enumerate(true, func(name string) bool { if property := object.getOwnProperty(name); nil != property && property.configurable() { property.configureOff() object.defineOwnProperty(name, *property, true) } return true }) object.extensible = false } else { panic(call.runtime.panicTypeError()) } return object } func builtinObject_isFrozen(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { if object.extensible { return toValue_bool(false) } result := true object.enumerate(true, func(name string) bool { property := object.getProperty(name) if property.configurable() || property.writable() { result = false } return true }) return toValue_bool(result) } panic(call.runtime.panicTypeError()) } func builtinObject_freeze(call FunctionCall) Value { object := call.Argument(0) if object := object._object(); object != nil { object.enumerate(true, func(name string) bool { if property, update := object.getOwnProperty(name), false; nil != property { if property.isDataDescriptor() && property.writable() { property.writeOff() update = true } if property.configurable() { property.configureOff() update = true } if update { object.defineOwnProperty(name, *property, true) } } return true }) object.extensible = false } else { panic(call.runtime.panicTypeError()) } return object } func builtinObject_keys(call FunctionCall) Value { if object, keys := call.Argument(0)._object(), []Value(nil); nil != object { object.enumerate(false, func(name string) bool { keys = append(keys, toValue_string(name)) return true }) return toValue_object(call.runtime.newArrayOf(keys)) } panic(call.runtime.panicTypeError()) } func builtinObject_getOwnPropertyNames(call FunctionCall) Value { if object, propertyNames := call.Argument(0)._object(), []Value(nil); nil != object { object.enumerate(true, func(name string) bool { if object.hasOwnProperty(name) { propertyNames = append(propertyNames, toValue_string(name)) } return true }) return toValue_object(call.runtime.newArrayOf(propertyNames)) } panic(call.runtime.panicTypeError()) }
mit
dibley1973/StoredProcedureFramework
Tests/Dibware.StoredProcedureFramework.IntegrationTests/StoredProcedures/CountCharsInReturnParameterStoredProcedure.cs
739
using Dibware.StoredProcedureFramework.Base; using Dibware.StoredProcedureFramework.StoredProcedureAttributes; using System.Data; namespace Dibware.StoredProcedureFramework.IntegrationTests.StoredProcedures { internal class CountCharsInReturnParameterStoredProcedure : NoReturnTypeStoredProcedureBase<CountCharsInReturnParameterStoredProcedure.Parameter> { public CountCharsInReturnParameterStoredProcedure(Parameter parameters) : base(parameters) { } public class Parameter { [Size(100)] public string Value1 { get; set; } [Direction(ParameterDirection.ReturnValue)] public int Value2 { get; set; } } } }
mit
michaelchu/kaleidoscope
kaleidoscope/__init__.py
339
from kaleidoscope import brokers, sizers, datafeeds from kaleidoscope.backtest import Backtest from kaleidoscope.strategy import Strategy from kaleidoscope.options.option_strategies import OptionStrategies from kaleidoscope.options.option_query import OptionQuery from .globals import Period, OptionType, OrderAction, OrderType, OrderTIF
mit
cawel/vinifera
db/migrate/20090819024702_create_regions.rb
319
class CreateRegions < ActiveRecord::Migration def self.up create_table "regions", :force => true do |t| t.column :name, :string, :limit => 50 t.timestamps end add_column :wines, :region_id, :integer end def self.down drop_table :regions remove_column :wines, :region_id end end
mit
MightyPixel/MatchUp
matchup-client/test/karma.conf.js
2084
// Karma configuration // http://karma-runner.github.io/0.12/config/configuration-file.html // Generated on 2014-11-07 using // generator-karma 0.8.3 module.exports = function(config) { 'use strict'; config.set({ // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // base path, that will be used to resolve files and exclude basePath: '../', // testing framework to use (jasmine/mocha/qunit/...) frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'bower_components/angular/angular.js', 'bower_components/angular-mocks/angular-mocks.js', 'bower_components/angular-animate/angular-animate.js', 'bower_components/angular-cookies/angular-cookies.js', 'bower_components/angular-resource/angular-resource.js', 'bower_components/angular-route/angular-route.js', 'bower_components/angular-sanitize/angular-sanitize.js', 'bower_components/angular-touch/angular-touch.js', 'app/scripts/**/*.js', 'test/mock/**/*.js', 'test/spec/**/*.js' ], // list of files / patterns to exclude exclude: [], // web server port port: 8080, // Start these browsers, currently available: // - Chrome // - ChromeCanary // - Firefox // - Opera // - Safari (only Mac) // - PhantomJS // - IE (only Windows) browsers: [ 'PhantomJS' ], // Which plugins to enable plugins: [ 'karma-phantomjs-launcher', 'karma-jasmine' ], // Continuous Integration mode // if true, it capture browsers, run tests and exit singleRun: false, colors: true, // level of logging // possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG logLevel: config.LOG_INFO, // Uncomment the following lines if you are using grunt's server to run the tests // proxies: { // '/': 'http://localhost:9000/' // }, // URL root prevent conflicts with the site root // urlRoot: '_karma_' }); };
mit
Mati365/pyWinUSB
pywinusb/decorators.py
589
# Dla fluent API def chain_method(func): def func_wrapper(self, *args, **kwargs): func(self, *args, **kwargs) return self return func_wrapper # Szybkie emitowanie zdarzeń def event_method(status): def dec(func): def func_wrapper(self, *args, **kwargs): self.event_handler.on_status(status) func(self, *args, **kwargs) return self return func_wrapper return dec # Metoda instalacyjna def installer_method(status): def dec(func): return chain_method(event_method(status)(func)) return dec
mit
abelcarreras/DynaPhoPy
unittest/MgO_test.py
1551
#!/usr/bin/env python import numpy as np import dynaphopy.interface.iofile as io import dynaphopy from dynaphopy.interface.phonopy_link import get_force_constants_from_file import unittest class TestDynaphopy(unittest.TestCase): def setUp(self): structure = io.read_from_file_structure_poscar('MgO_data/POSCAR') structure.set_primitive_matrix([[0.0, 0.5, 0.5], [0.5, 0.0, 0.5], [0.5, 0.5, 0.0]]) structure.set_force_constants(get_force_constants_from_file(file_name='MgO_data/FORCE_CONSTANTS', fc_supercell=[[2, 0, 0], [0, 2, 0], [0, 0, 2]])) trajectory = io.generate_test_trajectory(structure, supercell=[2, 2, 2], total_time=5, silent=False) self.calculation = dynaphopy.Quasiparticle(trajectory) def test_force_constants_self_consistency(self): self.calculation.select_power_spectra_algorithm(2) renormalized_force_constants = self.calculation.get_renormalized_force_constants().get_array() harmonic_force_constants = self.calculation.dynamic.structure.get_force_constants().get_array() self.assertEqual(np.allclose(renormalized_force_constants, harmonic_force_constants, rtol=1, atol=1.e-2), True) if __name__ == '__main__': unittest.main()
mit
maxinfet/FlaUI
src/FlaUI.UIA2/Patterns/ItemContainerPattern.cs
1351
#if !NET35 using FlaUI.Core; using FlaUI.Core.AutomationElements.Infrastructure; using FlaUI.Core.Identifiers; using FlaUI.Core.Patterns; using FlaUI.Core.Patterns.Infrastructure; using FlaUI.UIA2.Converters; using FlaUI.UIA2.Identifiers; using UIA = System.Windows.Automation; namespace FlaUI.UIA2.Patterns { public class ItemContainerPattern : PatternBase<UIA.ItemContainerPattern>, IItemContainerPattern { public static readonly PatternId Pattern = PatternId.Register(AutomationType.UIA2, UIA.ItemContainerPattern.Pattern.Id, "ItemContainer", AutomationObjectIds.IsItemContainerPatternAvailableProperty); public ItemContainerPattern(BasicAutomationElementBase basicAutomationElement, UIA.ItemContainerPattern nativePattern) : base(basicAutomationElement, nativePattern) { } public AutomationElement FindItemByProperty(AutomationElement startAfter, PropertyId property, object value) { var foundNativeElement = NativePattern.FindItemByProperty( startAfter?.ToNative(), property == null ? null : UIA.AutomationProperty.LookupById(property.Id), ValueConverter.ToNative(value)); return AutomationElementConverter.NativeToManaged((UIA2Automation)BasicAutomationElement.Automation, foundNativeElement); } } } #endif
mit
Luatix/OpenEx
openex-platform/openex-api/src/Constant/ExerciseConstantClass.php
4082
<?php namespace App\Constant; class ExerciseConstantClass { const CST_EXERCISE = 'exercise'; const CST_AUDIENCE = 'audience'; const CST_OBJECTIVE = 'objective'; const CST_SCENARIOS = 'scenarios'; const CST_INJECTS = 'injects'; const CST_INCIDENTS = 'incidents'; // Constantes Import/Export Exercise const CST_EXERCISE_ID = 'EXERCISE_ID'; const CST_EXERCISE_OWNER = 'EXERCISE_OWNER'; const CST_EXERCISE_IMAGE = 'EXERCISE_IMAGE'; const CST_EXERCISE_ANIMATION_GROUP = 'EXERCISE_ANIMATION_GROUP'; const CST_EXERCISE_NAME = 'EXERCISE_NAME'; const CST_EXERCISE_SUBTITLE = 'EXERCISE_SUBTITLE'; const CST_EXERCISE_DESCRIPTION = 'EXERCISE_DESCRIPTION'; const CST_EXERCISE_START_DATE = 'EXERCISE_START_DATE'; const CST_EXERCISE_END_DATE = 'EXERCISE_END_DATE'; const CST_EXERCISE_MESSAGE_HEADER = 'EXERCISE_MESSAGE_HEADER'; const CST_EXERCISE_MESSAGE_FOOTER = 'EXERCISE_MESSAGE_FOOTER'; const CST_EXERCISE_CANCELED = 'EXERCISE_CANCELED'; const CST_EXERCISE_MAIL_EXPEDITEUR = 'EXERCISE_MAIL_EXPEDITEUR'; // Audience const CST_AUDIENCE_ID = 'AUDIENCE_ID'; const CST_AUDIENCE_NAME = 'AUDIENCE_NAME'; const CST_AUDIENCE_ENABLED = 'AUDIENCE_ENABLED'; // Sub Audience const CST_SUBAUDIENCE_ID = 'SUBAUDIENCE_ID'; const CST_SUBAUDIENCE_NAME = 'SUBAUDIENCE_NAME'; const CST_SUBAUDIENCE_ENABLED = 'SUBAUDIENCE_ENABLED'; // User const CST_USER_ID = 'USER_ID'; const CST_USER_ORGANIZATION = 'USER_ORGANIZATION'; const CST_USER_LOGIN = 'USER_LOGIN'; const CST_USER_FIRSTNAME = 'USER_FIRSTNAME'; const CST_USER_LASTNAME = 'USER_LASTNAME'; const CST_USER_EMAIL = 'USER_EMAIL'; const CST_USER_EMAIL2 = 'USER_EMAIL2'; const CST_USER_PHONE = 'USER_PHONE'; const CST_USER_PHONE2 = 'USER_PHONE2'; const CST_USER_PHONE3 = 'USER_PHONE3'; const CST_USER_ADMIN = 'USER_ADMIN'; const CST_USER_STATUS = 'USER_STATUS'; const CST_USER_PASSWORD = 'USER_PASSWORD'; // Objective Data const CST_OBJECTIVE_ID = 'OBJECTIVE_ID'; const CST_OBJECTIVE_TITLE = 'OBJECTIVE_TITLE'; const CST_OBJECTIVE_DESCRIPTION = 'OBJECTIVE_DESCRIPTION'; const CST_OBJECTIVE_PRIORITY = 'OBJECTIVE_PRIORITY'; const CST_SUBOBJECTIVE_ID = 'SUBOBJECTIVE_ID'; const CST_SUBOBJECTIVE_TITLE = 'SUBOBJECTIVE_TITLE'; const CST_SUBOBJECTIVE_DESCRIPTION = 'SUBOBJECTIVE_DESCRIPTION'; const CST_SUBOBJECTIVE_PRIORITY = 'SUBOBJECTIVE_PRIORITY'; // Scenarios Data const CST_EVENT_ID = 'EVENT_ID'; const CST_EVENT_IMAGE = 'EVENT_IMAGE'; const CST_EVENT_TITLE = 'EVENT_TITLE'; const CST_EVENT_DESCRIPTION = 'EVENT_DESCRIPTION'; const CST_EVENT_ORDER = 'EVENT_ORDER'; // Incident Data const CST_INCIDENT_ID = 'INCIDENT_ID'; const CST_INCIDENT_TYPE = 'INCIDENT_TYPE'; const CST_INCIDENT_EVENT = 'INCIDENT_EVENT'; const CST_INCIDENT_TITLE = 'INCIDENT_TITLE'; const CST_INCIDENT_STORY = 'INCIDENT_STORY'; const CST_INCIDENT_WEIGHT = 'INCIDENT_WEIGHT'; const CST_INCIDENT_ORDER = 'INCIDENT_ORDER'; const CST_INCIDENT_OUTCOME_COMMENT = 'INCIDENT_OUTCOME_COMMENT'; const CST_INCIDENT_OUTCOME_RESULT = 'INCIDENT_OUTCOME_RESULT'; // Injects Data const CST_INJECT_ID = 'INJECT_ID'; const CST_INJECT_INCIDENT_ID = 'INJECT_INCIDENT_ID'; const CST_INJECT_USER = 'INJECT_USER'; const CST_INJECT_TITLE = 'INJECT_TITLE'; const CST_INJECT_DESCRIPTION = 'INJECT_DESCRIPTION'; const CST_INJECT_CONTENT = 'INJECT_CONTENT'; const CST_INJECT_TYPE = 'INJECT_TYPE'; const CST_INJECT_ALL_AUDIENCES = 'INJECT_ALL_AUDIENCES'; const CST_INJECT_AUDIENCES = 'INJECT_AUDIENCES'; const CST_INJECT_SUBAUDIENCES = 'INJECT_SUBAUDIENCES'; const CST_INJECT_ENABLED = 'INJECT_ENABLED'; const CST_INJECT_DATE = 'INJECT_DATE'; const CST_INJECT_STATUS_NAME = 'INJECT_STATUS_NAME'; const CST_INJECT_STATUS_MESSAGE = 'INJECT_STATUS_MESSAGE'; const CST_INJECT_STATUS_DATE = 'INJECT_STATUS_DATE'; const CST_INJECT_STATUS_EXECUTION = 'INJECT_STATUS_EXECUTION'; }
mit
JueTech/Jue-php-sdk
example/test_cloud.php
739
<?php /** * @package /example/test_node * @author xiaocao * @link http://homeway.me/ * @copyright Copyright(c) 2015 * @version 15.07.16 **/ require_once(__DIR__."/../vendor/autoload.php"); use Jue\Server; use Jue\Auth\Token; /** * */ $app_key = "homeway"; $app_secret = "homeway"; $server = new Server($app_key, $app_secret); //$oauth = $server->auth()->get_access_token("client_credentials"); //$oauth_type_password = $server->auth()->get_access_token("password"); $user = $server->secret->portal("1", "api.jue.so", md5(time())); //print_r($user);exit(); $user = json_decode($user, true); if($user["code"] == 1000){ $data = $server->cloud->get_upload_token($user["data"]["uuid"]); echo json_encode($data); }
mit
smptracing/SMP
application/views/front/Pmi/js/jsMetaNoPip.php
76
<script src="<?php echo base_url(); ?>assets/js/PMI/MetaNoPip.js"></script>
mit
dwhelan/atdd_training
ruby/features/google/support/matchers/page_object_matcher.rb
1031
require_relative 'page_object' module RSpec module Matchers module PageObjectMatcher include PageObject def failure_message if element? "expected '#{page}' '#{expected}' #{tag_description} to have a '<#{tag_name}>' tag but it has a '<#{element.tag_name}>' tag" else "expected '#{page}' to have a '#{expected}' #{tag_description}: #{element_error}" end end def failure_message_when_negated "expected '#{page}' not to have a '#{expected}' #{tag_description} but it does" end def element_ok? element? && tag_ok? end def tag_ok? tag_name.nil? || element.tag_name == tag_name end def tag_options default_options.merge options end def default_options { tag_name: nil, tag_description: 'element' } end def tag_name self.name.to_s.sub(/.*_/, '') end def tag_description self.name.to_s.sub(/.*_/, '') end end end end
mit
guoxf/Ants
Util/Page.cs
2321
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data.SqlClient; using System.Data; using Newtonsoft.Json; using FrameWork.DBHelper; namespace FrameWork.Util { public class Page { /// <summary> /// 分页 /// </summary> /// <param name="tablename"></param> /// <param name="strGetFields"></param> /// <param name="fixWhere"></param> /// <param name="orderBy"></param> /// <param name="pageIndex"></param> /// <param name="pageSize"></param> /// <param name="isAsc"></param> /// <returns></returns> public static string GetPage(string tablename, string strGetFields, string fixWhere, string orderBy, int pageIndex = 1, int pageSize = 1, bool isAsc = true) { SqlParameter[] param = new SqlParameter[] { new SqlParameter("@tblName",SqlDbType.NVarChar,50){Value=tablename}, new SqlParameter("@fields",SqlDbType.NVarChar,5000){Value=strGetFields}, new SqlParameter("@sortString",SqlDbType.NVarChar,5000){Value=orderBy}, new SqlParameter("@fixWhere",SqlDbType.NVarChar,5000){Value=fixWhere}, new SqlParameter("@filterWhere",SqlDbType.NVarChar,5000){Value=null}, new SqlParameter("@pageSize",SqlDbType.Int){Value=pageSize}, new SqlParameter("@pageIndex",SqlDbType.Int){Value=pageIndex}, new SqlParameter("@totalPage",SqlDbType.Int){Value=null,Direction=ParameterDirection.Output}, new SqlParameter("@totalRecord",SqlDbType.Int){Value=null,Direction=ParameterDirection.Output}, new SqlParameter("@totalFiltered",SqlDbType.Int){Value=null,Direction=ParameterDirection.Output} }; DataSet ds = DBManager.Instance().ExecuteDataSet(CommandType.StoredProcedure,"SP_Common_GetDataPage", param); return JsonConvert.SerializeObject( new { data = ds.Tables[0], totalpages = param[7].Value, recordcount = param[8].Value }, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new LowerPropertyNamesContractResolver() }); } } }
mit
cuckata23/wurfl-data
data/samsung_nexus_s_ver1_suban41_subu3k9.php
228
<?php return array ( 'id' => 'samsung_nexus_s_ver1_suban41_subu3k9', 'fallback' => 'samsung_nexus_s_ver1_suban41', 'capabilities' => array ( 'mobile_browser' => 'UCWeb', 'mobile_browser_version' => '9', ), );
mit
devingoodsell/ComingSoon
config/env/production.js
210
/* jshint node:true */ "use strict"; module.exports = { db: process.env.MONGOLAB_URI, logLevel: "error", mailChimp: { key: process.env.CHIMP_KEY, userList: process.env.CHIMP_USERLIST } };
mit
ferggren/ferg-v4-frontend
src/components/ui/container/index.js
65
'use strict'; export { default as default } from './container';
mit
zBMNForks/orats
lib/orats/argv_adjust.rb
1317
require 'orats/ui' module Orats # adjust ARGV by adding args from the .oratsrc file if necessary class ARGVAdjust include Orats::UI def initialize(argv = ARGV) @argv = argv @default_rc_file = File.expand_path('~/.oratsrc') @rc_path = '' end def init rc_path @argv.first return @argv if @rc_path.empty? argv end private def rc_path(command) return unless command == 'new' || command == 'nuke' rc_flag = @argv.index { |item| item.include?('--rc') } if rc_flag cli_rc_file(rc_flag) elsif File.exist?(@default_rc_file) @rc_path = @default_rc_file end end def argv if File.exist?(@rc_path) extra_args = File.readlines(@rc_path).flat_map(&:split) results 'Using values from an .oratsrc file', 'args', extra_args.join(' ') puts (@argv += extra_args).flatten else error 'The .oratsrc file cannot be found', @rc_path end end def cli_rc_file(index) rc_value = @argv[index] if rc_value.include?('=') @rc_path = rc_value.gsub('--rc=', '') @argv.slice! index elsif rc_value == '--rc' @rc_path = @argv[index + 1] @argv.slice! index + 1 end end end end
mit
dhedlund/importu
lib/importu/sources/ruby.rb
423
require "importu/sources" # Supports a plain array of hashes as source data, or an enumerable that # produces objects that respond to #to_hash. Hash keys must be strings. class Importu::Sources::Ruby def initialize(data, **) @data = data end def rows Enumerator.new do |yielder| @data.each {|row| yielder.yield(row.to_hash) } end end def write_errors(summary, only_errors: false) end end
mit
sexyboys/FileDownloader
src/FileD/UserBundle/DependencyInjection/Configuration.php
876
<?php namespace FileD\UserBundle\DependencyInjection; use Symfony\Component\Config\Definition\Builder\TreeBuilder; use Symfony\Component\Config\Definition\ConfigurationInterface; /** * This is the class that validates and merges configuration from your app/config files * * To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html#cookbook-bundles-extension-config-class} */ class Configuration implements ConfigurationInterface { /** * {@inheritDoc} */ public function getConfigTreeBuilder() { $treeBuilder = new TreeBuilder(); $rootNode = $treeBuilder->root('file_d_user'); // Here you should define the parameters that are allowed to // configure your bundle. See the documentation linked above for // more information on that topic. return $treeBuilder; } }
mit
cdnjs/cdnjs
ajax/libs/chartjs-chart-box-and-violin-plot/1.2.0/Chart.BoxPlot.js
30976
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('chart.js')) : typeof define === 'function' && define.amd ? define(['exports', 'chart.js'], factory) : factory(global.ChartBoxPlot = {},global.Chart); }(typeof self !== 'undefined' ? self : this, function (exports,Chart) { 'use strict'; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(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"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } function ascending(a, b) { return a - b; } function quantiles(d, quantiles) { d = d.slice().sort(ascending); var n_1 = d.length - 1; return quantiles.map(function (q) { if (q === 0) return d[0];else if (q === 1) return d[n_1]; var index = 1 + q * n_1, lo = Math.floor(index), h = index - lo, a = d[lo - 1]; return h === 0 ? a : a + h * (d[lo] - a); }); } // See <http://en.wikipedia.org/wiki/Kernel_(statistics)>. function gaussian(u) { return 1 / Math.sqrt(2 * Math.PI) * Math.exp(-.5 * u * u); } // Welford's algorithm. function mean(x) { var n = x.length; if (n === 0) return NaN; var m = 0, i = -1; while (++i < n) m += (x[i] - m) / (i + 1); return m; } // Also known as the sample variance, where the denominator is n - 1. function variance(x) { var n = x.length; if (n < 1) return NaN; if (n === 1) return 0; var mean$$1 = mean(x), i = -1, s = 0; while (++i < n) { var v = x[i] - mean$$1; s += v * v; } return s / (n - 1); } function iqr(x) { var quartiles = quantiles(x, [.25, .75]); return quartiles[1] - quartiles[0]; } // Visualization. Wiley. function nrd(x) { var h = iqr(x) / 1.34; return 1.06 * Math.min(Math.sqrt(variance(x)), h) * Math.pow(x.length, -1 / 5); } function functor(v) { return typeof v === "function" ? v : function () { return v; }; } function kde() { var kernel = gaussian, sample = [], bandwidth = nrd; function kde(points, i) { var bw = bandwidth.call(this, sample); return points.map(function (x) { var i = -1, y = 0, n = sample.length; while (++i < n) { y += kernel((x - sample[i]) / bw); } return [x, y / bw / n]; }); } kde.kernel = function (x) { if (!arguments.length) return kernel; kernel = x; return kde; }; kde.sample = function (x) { if (!arguments.length) return sample; sample = x; return kde; }; kde.bandwidth = function (x) { if (!arguments.length) return bandwidth; bandwidth = functor(x); return kde; }; return kde; } function extent(arr) { return arr.reduce(function (acc, v) { return [Math.min(acc[0], v), Math.max(acc[1], v)]; }, [Number.POSITIVE_INFINITY, Number.NEGATIVE_INFINITY]); } function whiskers(boxplot, arr) { var iqr = boxplot.q3 - boxplot.q1; // since top left is max var whiskerMin = Math.max(boxplot.min, boxplot.q1 - iqr); var whiskerMax = Math.min(boxplot.max, boxplot.q3 + iqr); if (Array.isArray(arr)) { // compute the closest real element for (var i = 0; i < arr.length; i++) { var v = arr[i]; if (v >= whiskerMin) { whiskerMin = v; break; } } for (var _i = arr.length - 1; _i >= 0; _i--) { var _v = arr[_i]; if (_v <= whiskerMax) { whiskerMax = _v; break; } } } return { whiskerMin: whiskerMin, whiskerMax: whiskerMax }; } function boxplotStats(arr) { // console.assert(Array.isArray(arr)); if (arr.length === 0) { return { min: NaN, max: NaN, median: NaN, q1: NaN, q3: NaN, whiskerMin: NaN, whiskerMax: NaN, outliers: [] }; } arr = arr.filter(function (v) { return typeof v === 'number' && !isNaN(v); }); arr.sort(function (a, b) { return a - b; }); var _quantiles = quantiles(arr, [0.5, 0.25, 0.75]), _quantiles2 = _slicedToArray(_quantiles, 3), median = _quantiles2[0], q1 = _quantiles2[1], q3 = _quantiles2[2]; var minmax = extent(arr); var base = { min: minmax[0], max: minmax[1], median: median, q1: q1, q3: q3, outliers: [] }; var _whiskers = whiskers(base, arr), whiskerMin = _whiskers.whiskerMin, whiskerMax = _whiskers.whiskerMax; base.outliers = arr.filter(function (v) { return v < whiskerMin || v > whiskerMax; }); base.whiskerMin = whiskerMin; base.whiskerMax = whiskerMax; return base; } function violinStats(arr) { // console.assert(Array.isArray(arr)); if (arr.length === 0) { return { outliers: [] }; } arr = arr.filter(function (v) { return typeof v === 'number' && !isNaN(v); }); arr.sort(function (a, b) { return a - b; }); var minmax = extent(arr); return { min: minmax[0], max: minmax[1], median: quantiles(arr, [0.5])[0], kde: kde().sample(arr) }; } function asBoxPlotStats(value) { if (!value) { return null; } if (typeof value.median === 'number' && typeof value.q1 === 'number' && typeof value.q3 === 'number') { // sounds good, check for helper if (typeof value.whiskerMin === 'undefined') { var _whiskers2 = whiskers(value, Array.isArray(value.items) ? value.items.slice().sort(function (a, b) { return a - b; }) : null), whiskerMin = _whiskers2.whiskerMin, whiskerMax = _whiskers2.whiskerMax; value.whiskerMin = whiskerMin; value.whiskerMax = whiskerMax; } return value; } if (!Array.isArray(value)) { return undefined; } if (value.__stats === undefined) { value.__stats = boxplotStats(value); } return value.__stats; } function asViolinStats(value) { if (!value) { return null; } if (typeof value.median === 'number' && (typeof value.kde === 'function' || Array.isArray(value.coords))) { return value; } if (!Array.isArray(value)) { return undefined; } if (value.__kde === undefined) { value.__kde = violinStats(value); } return value.__kde; } function asValueStats(value, minStats, maxStats) { if (typeof value[minStats] === 'number' && typeof value[maxStats] === 'number') { return value; } if (!Array.isArray(value)) { return undefined; } return asBoxPlotStats(value); } function getRightValue(rawValue) { if (!rawValue) { return rawValue; } if (typeof rawValue === 'number' || typeof rawValue === 'string') { return Number(rawValue); } var b = asBoxPlotStats(rawValue); return b ? b.median : rawValue; } var commonScaleOptions = { ticks: { minStats: 'min', maxStats: 'max' } }; function commonDataLimits(extraCallback) { var _this = this; var chart = this.chart; var isHorizontal = this.isHorizontal(); var tickOpts = this.options.ticks; var minStats = tickOpts.minStats; var maxStats = tickOpts.maxStats; var matchID = function matchID(meta) { return isHorizontal ? meta.xAxisID === _this.id : meta.yAxisID === _this.id; }; // First Calculate the range this.min = null; this.max = null; // Regular charts use x, y values // For the boxplot chart we have rawValue.min and rawValue.max for each point chart.data.datasets.forEach(function (d, i) { var meta = chart.getDatasetMeta(i); if (!chart.isDatasetVisible(i) || !matchID(meta)) { return; } d.data.forEach(function (value, j) { if (!value || meta.data[j].hidden) { return; } var stats = asValueStats(value, minStats, maxStats); if (!stats) { return; } if (_this.min === null || stats[minStats] < _this.min) { _this.min = stats[minStats]; } if (_this.max === null || stats[maxStats] > _this.max) { _this.max = stats[maxStats]; } if (extraCallback) { extraCallback(stats); } }); }); } function rnd(seed) { // Adapted from http://indiegamr.com/generate-repeatable-random-numbers-in-js/ if (seed === undefined) { seed = Date.now(); } return function () { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; }; } var defaults = Object.assign({}, Chart.defaults.global.elements.rectangle, { borderWidth: 1, outlierRadius: 2, outlierColor: Chart.defaults.global.elements.rectangle.backgroundColor, itemRadius: 0, itemStyle: 'circle', itemBackgroundColor: Chart.defaults.global.elements.rectangle.backgroundColor, itemBorderColor: Chart.defaults.global.elements.rectangle.borderColor, hitPadding: 2 }); var ArrayElementBase = Chart.Element.extend({ isVertical: function isVertical() { return this._view.width !== undefined; }, draw: function draw() {// abstract }, _drawItems: function _drawItems(vm, container, ctx, vert) { if (vm.itemRadius <= 0 || !container.items || container.items.length <= 0) { return; } ctx.save(); ctx.strokeStle = vm.itemBorderColor; ctx.fillStyle = vm.itemBackgroundColor; // jitter based on random data // use the datesetindex and index to initialize the random number generator var random = rnd(this._datasetIndex * 1000 + this._index); if (vert) { container.items.forEach(function (v) { Chart.canvasHelpers.drawPoint(ctx, vm.itemStyle, vm.itemRadius, vm.x - vm.width / 2 + random() * vm.width, v); }); } else { container.items.forEach(function (v) { Chart.canvasHelpers.drawPoint(ctx, vm.itemStyle, vm.itemRadius, v, vm.y - vm.height / 2 + random() * vm.height); }); } ctx.restore(); }, _drawOutliers: function _drawOutliers(vm, container, ctx, vert) { if (!container.outliers) { return; } ctx.fillStyle = vm.outlierColor; ctx.beginPath(); if (vert) { container.outliers.forEach(function (v) { ctx.arc(vm.x, v, vm.outlierRadius, 0, Math.PI * 2); }); } else { container.outliers.forEach(function (v) { ctx.arc(v, vm.y, vm.outlierRadius, 0, Math.PI * 2); }); } ctx.fill(); ctx.closePath(); }, _getBounds: function _getBounds() { // abstract return { left: 0, top: 0, right: 0, bottom: 0 }; }, _getHitBounds: function _getHitBounds() { var padding = this._view.hitPadding; var b = this._getBounds(); return { left: b.left - padding, top: b.top - padding, right: b.right + padding, bottom: b.bottom + padding }; }, height: function height() { return 0; // abstract }, inRange: function inRange(mouseX, mouseY) { if (!this._view) { return false; } var bounds = this._getHitBounds(); return mouseX >= bounds.left && mouseX <= bounds.right && mouseY >= bounds.top && mouseY <= bounds.bottom; }, inLabelRange: function inLabelRange(mouseX, mouseY) { if (!this._view) { return false; } var bounds = this._getHitBounds(); if (this.isVertical()) { return mouseX >= bounds.left && mouseX <= bounds.right; } return mouseY >= bounds.top && mouseY <= bounds.bottom; }, inXRange: function inXRange(mouseX) { var bounds = this._getHitBounds(); return mouseX >= bounds.left && mouseX <= bounds.right; }, inYRange: function inYRange(mouseY) { var bounds = this._getHitBounds(); return mouseY >= bounds.top && mouseY <= bounds.bottom; }, getCenterPoint: function getCenterPoint() { var _this$_view = this._view, x = _this$_view.x, y = _this$_view.y; return { x: x, y: y }; }, getArea: function getArea() { return 0; // abstract }, tooltipPosition_: function tooltipPosition_() { return this.getCenterPoint(); } }); Chart.defaults.global.elements.boxandwhiskers = Object.assign({}, defaults); function transitionBoxPlot(start, view, model, ease) { var keys = Object.keys(model); for (var _i = 0; _i < keys.length; _i++) { var key = keys[_i]; var target = model[key]; var origin = start[key]; if (origin === target) { continue; } if (typeof target === 'number') { view[key] = origin + (target - origin) * ease; continue; } if (Array.isArray(target)) { var v = view[key]; var common = Math.min(target.length, origin.length); for (var i = 0; i < common; ++i) { v[i] = origin[i] + (target[i] - origin[i]) * ease; } } } } var BoxAndWiskers = Chart.elements.BoxAndWhiskers = ArrayElementBase.extend({ transition: function transition(ease) { var r = Chart.Element.prototype.transition.call(this, ease); var model = this._model; var start = this._start; var view = this._view; // No animation -> No Transition if (!model || ease === 1) { return r; } if (start.boxplot == null) { return r; // model === view -> not copied } // create deep copy to avoid alternation if (model.boxplot === view.boxplot) { view.boxplot = Chart.helpers.clone(view.boxplot); } transitionBoxPlot(start.boxplot, view.boxplot, model.boxplot, ease); return r; }, draw: function draw() { var ctx = this._chart.ctx; var vm = this._view; var boxplot = vm.boxplot; var vert = this.isVertical(); this._drawItems(vm, boxplot, ctx, vert); ctx.save(); ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; ctx.lineWidth = vm.borderWidth; this._drawBoxPlot(vm, boxplot, ctx, vert); this._drawOutliers(vm, boxplot, ctx, vert); ctx.restore(); }, _drawBoxPlot: function _drawBoxPlot(vm, boxplot, ctx, vert) { ctx.beginPath(); if (vert) { var x = vm.x; var width = vm.width; var x0 = x - width / 2; ctx.fillRect(x0, boxplot.q1, width, boxplot.q3 - boxplot.q1); ctx.strokeRect(x0, boxplot.q1, width, boxplot.q3 - boxplot.q1); ctx.moveTo(x0, boxplot.whiskerMin); ctx.lineTo(x0 + width, boxplot.whiskerMin); ctx.moveTo(x, boxplot.whiskerMin); ctx.lineTo(x, boxplot.q1); ctx.moveTo(x0, boxplot.whiskerMax); ctx.lineTo(x0 + width, boxplot.whiskerMax); ctx.moveTo(x, boxplot.whiskerMax); ctx.lineTo(x, boxplot.q3); ctx.moveTo(x0, boxplot.median); ctx.lineTo(x0 + width, boxplot.median); } else { var y = vm.y; var height = vm.height; var y0 = y - height / 2; ctx.fillRect(boxplot.q1, y0, boxplot.q3 - boxplot.q1, height); ctx.strokeRect(boxplot.q1, y0, boxplot.q3 - boxplot.q1, height); ctx.moveTo(boxplot.whiskerMin, y0); ctx.lineTo(boxplot.whiskerMin, y0 + height); ctx.moveTo(boxplot.whiskerMin, y); ctx.lineTo(boxplot.q1, y); ctx.moveTo(boxplot.whiskerMax, y0); ctx.lineTo(boxplot.whiskerMax, y0 + height); ctx.moveTo(boxplot.whiskerMax, y); ctx.lineTo(boxplot.q3, y); ctx.moveTo(boxplot.median, y0); ctx.lineTo(boxplot.median, y0 + height); } ctx.stroke(); ctx.closePath(); }, _getBounds: function _getBounds() { var vm = this._view; var vert = this.isVertical(); var boxplot = vm.boxplot; if (!boxplot) { return { left: 0, top: 0, right: 0, bottom: 0 }; } if (vert) { var x = vm.x, width = vm.width; var x0 = x - width / 2; return { left: x0, top: boxplot.whiskerMax, right: x0 + width, bottom: boxplot.whiskerMin }; } var y = vm.y, height = vm.height; var y0 = y - height / 2; return { left: boxplot.whiskerMin, top: y0, right: boxplot.whiskerMax, bottom: y0 + height }; }, height: function height() { var vm = this._view; return vm.base - Math.min(vm.boxplot.q1, vm.boxplot.q3); }, getArea: function getArea() { var vm = this._view; var iqr = Math.abs(vm.boxplot.q3 - vm.boxplot.q1); if (this.isVertical()) { return iqr * vm.width; } return iqr * vm.height; } }); Chart.defaults.global.elements.violin = Object.assign({ points: 100 }, defaults); function transitionViolin(start, view, model, ease) { var keys = Object.keys(model); for (var _i = 0; _i < keys.length; _i++) { var key = keys[_i]; var target = model[key]; var origin = start[key]; if (origin === target) { continue; } if (typeof target === 'number') { view[key] = origin + (target - origin) * ease; continue; } if (key === 'coords') { var v = view[key]; var common = Math.min(target.length, origin.length); for (var i = 0; i < common; ++i) { v[i].v = origin[i].v + (target[i].v - origin[i].v) * ease; v[i].estimate = origin[i].estimate + (target[i].estimate - origin[i].estimate) * ease; } } } } var Violin = Chart.elements.Violin = ArrayElementBase.extend({ transition: function transition(ease) { var r = Chart.Element.prototype.transition.call(this, ease); var model = this._model; var start = this._start; var view = this._view; // No animation -> No Transition if (!model || ease === 1) { return r; } if (start.violin == null) { return r; // model === view -> not copied } // create deep copy to avoid alternation if (model.violin === view.violin) { view.violin = Chart.helpers.clone(view.violin); } transitionViolin(start.violin, view.violin, model.violin, ease); return r; }, draw: function draw() { var ctx = this._chart.ctx; var vm = this._view; var violin = vm.violin; var vert = this.isVertical(); this._drawItems(vm, violin, ctx, vert); ctx.save(); ctx.fillStyle = vm.backgroundColor; ctx.strokeStyle = vm.borderColor; ctx.lineWidth = vm.borderWidth; var coords = violin.coords; Chart.canvasHelpers.drawPoint(ctx, 'rectRot', 5, vm.x, vm.y); ctx.stroke(); ctx.beginPath(); if (vert) { var x = vm.x; var width = vm.width; var factor = width / 2 / violin.maxEstimate; ctx.moveTo(x, violin.min); coords.forEach(function (_ref) { var v = _ref.v, estimate = _ref.estimate; ctx.lineTo(x - estimate * factor, v); }); ctx.lineTo(x, violin.max); ctx.moveTo(x, violin.min); coords.forEach(function (_ref2) { var v = _ref2.v, estimate = _ref2.estimate; ctx.lineTo(x + estimate * factor, v); }); ctx.lineTo(x, violin.max); } else { var y = vm.y; var height = vm.height; var _factor = height / 2 / violin.maxEstimate; ctx.moveTo(violin.min, y); coords.forEach(function (_ref3) { var v = _ref3.v, estimate = _ref3.estimate; ctx.lineTo(v, y - estimate * _factor); }); ctx.lineTo(violin.max, y); ctx.moveTo(violin.min, y); coords.forEach(function (_ref4) { var v = _ref4.v, estimate = _ref4.estimate; ctx.lineTo(v, y + estimate * _factor); }); ctx.lineTo(violin.max, y); } ctx.stroke(); ctx.fill(); ctx.closePath(); this._drawOutliers(vm, violin, ctx, vert); ctx.restore(); }, _getBounds: function _getBounds() { var vm = this._view; var vert = this.isVertical(); var violin = vm.violin; if (vert) { var x = vm.x, width = vm.width; var x0 = x - width / 2; return { left: x0, top: violin.max, right: x0 + width, bottom: violin.min }; } var y = vm.y, height = vm.height; var y0 = y - height / 2; return { left: violin.min, top: y0, right: violin.max, bottom: y0 + height }; }, height: function height() { var vm = this._view; return vm.base - Math.min(vm.violin.min, vm.violin.max); }, getArea: function getArea() { var vm = this._view; var iqr = Math.abs(vm.violin.max - vm.violin.min); if (this.isVertical()) { return iqr * vm.width; } return iqr * vm.height; } }); var verticalDefaults = { scales: { yAxes: [{ type: 'arrayLinear' }] } }; var horizontalDefaults = { scales: { xAxes: [{ type: 'arrayLinear' }] } }; var array = { _elementOptions: function _elementOptions() { return {}; }, updateElement: function updateElement(elem, index, reset) { var dataset = this.getDataset(); var custom = elem.custom || {}; var options = this._elementOptions(); Chart.controllers.bar.prototype.updateElement.call(this, elem, index, reset); ['outlierRadius', 'itemRadius', 'itemStyle', 'itemBackgroundColor', 'itemBorderColor', 'outlierColor', 'hitPadding'].forEach(function (item) { elem._model[item] = custom[item] !== undefined ? custom[item] : Chart.helpers.valueAtIndexOrDefault(dataset[item], index, options[item]); }); }, _calculateCommonModel: function _calculateCommonModel(r, data, container, scale) { if (container.outliers) { r.outliers = container.outliers.map(function (d) { return scale.getPixelForValue(Number(d)); }); } if (Array.isArray(data)) { r.items = data.map(function (d) { return scale.getPixelForValue(Number(d)); }); } } }; var defaults$1 = { tooltips: { callbacks: { label: function label(item, data) { var datasetLabel = data.datasets[item.datasetIndex].label || ''; var value = data.datasets[item.datasetIndex].data[item.index]; var b = asBoxPlotStats(value); var label = "".concat(datasetLabel, " ").concat(typeof item.xLabel === 'string' ? item.xLabel : item.yLabel); if (!b) { return label + 'NaN'; } return "".concat(label, " (min: ").concat(b.min, ", q1: ").concat(b.q1, ", median: ").concat(b.median, ", q3: ").concat(b.q3, ", max: ").concat(b.max, ")"); } } } }; Chart.defaults.boxplot = Chart.helpers.merge({}, [Chart.defaults.bar, verticalDefaults, defaults$1]); Chart.defaults.horizontalBoxplot = Chart.helpers.merge({}, [Chart.defaults.horizontalBar, horizontalDefaults, defaults$1]); var boxplot = Object.assign({}, array, { dataElementType: Chart.elements.BoxAndWhiskers, _elementOptions: function _elementOptions() { return this.chart.options.elements.boxandwhiskers; }, /** * @private */ updateElementGeometry: function updateElementGeometry(elem, index, reset) { Chart.controllers.bar.prototype.updateElementGeometry.call(this, elem, index, reset); elem._model.boxplot = this._calculateBoxPlotValuesPixels(this.index, index); }, /** * @private */ _calculateBoxPlotValuesPixels: function _calculateBoxPlotValuesPixels(datasetIndex, index) { var scale = this.getValueScale(); var data = this.chart.data.datasets[datasetIndex].data[index]; if (!data) { return null; } var v = asBoxPlotStats(data); var r = {}; Object.keys(v).forEach(function (key) { if (key !== 'outliers') { r[key] = scale.getPixelForValue(Number(v[key])); } }); this._calculateCommonModel(r, data, v, scale); return r; } }); /** * This class is based off controller.bar.js from the upstream Chart.js library */ var BoxPlot = Chart.controllers.boxplot = Chart.controllers.bar.extend(boxplot); var HorizontalBoxPlot = Chart.controllers.horizontalBoxplot = Chart.controllers.horizontalBar.extend(boxplot); var defaults$2 = {}; Chart.defaults.violin = Chart.helpers.merge({}, [Chart.defaults.bar, verticalDefaults, defaults$2]); Chart.defaults.horizontalViolin = Chart.helpers.merge({}, [Chart.defaults.horizontalBar, horizontalDefaults, defaults$2]); var controller = Object.assign({}, array, { dataElementType: Chart.elements.Violin, _elementOptions: function _elementOptions() { return this.chart.options.elements.violin; }, /** * @private */ updateElementGeometry: function updateElementGeometry(elem, index, reset) { Chart.controllers.bar.prototype.updateElementGeometry.call(this, elem, index, reset); var custom = elem.custom || {}; var options = this._elementOptions(); elem._model.violin = this._calculateViolinValuesPixels(this.index, index, custom.points !== undefined ? custom.points : options.points); }, /** * @private */ _calculateViolinValuesPixels: function _calculateViolinValuesPixels(datasetIndex, index, points) { var scale = this.getValueScale(); var data = this.chart.data.datasets[datasetIndex].data[index]; var violin = asViolinStats(data); var range = violin.max - violin.min; var samples = []; var inc = range / points; for (var v = violin.min; v <= violin.max; v += inc) { samples.push(v); } if (samples[samples.length - 1] !== violin.max) { samples.push(violin.max); } var coords = violin.coords || violin.kde(samples).map(function (v) { return { v: v[0], estimate: v[1] }; }); var r = { min: scale.getPixelForValue(violin.min), max: scale.getPixelForValue(violin.max), median: scale.getPixelForValue(violin.median), coords: coords.map(function (_ref) { var v = _ref.v, estimate = _ref.estimate; return { v: scale.getPixelForValue(v), estimate: estimate }; }), maxEstimate: coords.reduce(function (a, d) { return Math.max(a, d.estimate); }, Number.NEGATIVE_INFINITY) }; this._calculateCommonModel(r, data, violin, scale); return r; } }); /** * This class is based off controller.bar.js from the upstream Chart.js library */ var Violin$1 = Chart.controllers.violin = Chart.controllers.bar.extend(controller); var HorizontalViolin = Chart.controllers.horizontalViolin = Chart.controllers.horizontalBar.extend(controller); var helpers = Chart.helpers; var ArrayLinearScaleOptions = helpers.merge({}, [commonScaleOptions, Chart.scaleService.getScaleDefaults('linear')]); var ArrayLinearScale = Chart.scaleService.getScaleConstructor('linear').extend({ getRightValue: function getRightValue$$1(rawValue) { return Chart.LinearScaleBase.prototype.getRightValue.call(this, getRightValue(rawValue)); }, determineDataLimits: function determineDataLimits() { commonDataLimits.call(this); // Common base implementation to handle ticks.min, ticks.max, ticks.beginAtZero this.handleTickRangeOptions(); } }); Chart.scaleService.registerScaleType('arrayLinear', ArrayLinearScale, ArrayLinearScaleOptions); var helpers$1 = Chart.helpers; var ArrayLogarithmicScaleOptions = helpers$1.merge({}, [commonScaleOptions, Chart.scaleService.getScaleDefaults('logarithmic')]); var ArrayLogarithmicScale = Chart.scaleService.getScaleConstructor('logarithmic').extend({ getRightValue: function getRightValue$$1(rawValue) { return Chart.LinearScaleBase.prototype.getRightValue.call(this, getRightValue(rawValue)); }, determineDataLimits: function determineDataLimits() { var _this = this; // Add whitespace around bars. Axis shouldn't go exactly from min to max var tickOpts = this.options.ticks; this.minNotZero = null; commonDataLimits.call(this, function (boxPlot) { var value = boxPlot[tickOpts.minStats]; if (value !== 0 && (_this.minNotZero === null || value < _this.minNotZero)) { _this.minNotZero = value; } }); this.min = helpers$1.valueOrDefault(tickOpts.min, this.min - this.min * 0.05); this.max = helpers$1.valueOrDefault(tickOpts.max, this.max + this.max * 0.05); if (this.min === this.max) { if (this.min !== 0 && this.min !== null) { this.min = Math.pow(10, Math.floor(helpers$1.log10(this.min)) - 1); this.max = Math.pow(10, Math.floor(helpers$1.log10(this.max)) + 1); } else { this.min = 1; this.max = 10; } } } }); Chart.scaleService.registerScaleType('arrayLogarithmic', ArrayLogarithmicScale, ArrayLogarithmicScaleOptions); exports.BoxAndWhiskers = BoxAndWiskers; exports.Violin = Violin; exports.ArrayLinearScale = ArrayLinearScale; exports.ArrayLogarithmicScale = ArrayLogarithmicScale; exports.BoxPlot = BoxPlot; exports.HorizontalBoxPlot = HorizontalBoxPlot; exports.HorizontalViolin = HorizontalViolin; Object.defineProperty(exports, '__esModule', { value: true }); }));
mit
edloidas/roll-parser
test/mapper/mapper.mapToRoll.spec.js
1299
const { parseSimple, parseClassic } = require( '../../src/parser' ); const { mapToRoll } = require( '../../src/mapper' ); describe( 'Map parser result to Roll:', () => { test( 'Should map falsy values to `null`', () => { expect( mapToRoll( null )).toBeNull(); }); test( 'Should set dice for single value roll', () => { expect( mapToRoll( parseSimple( '10' ))).toMatchObject({ dice: 10 }); expect( mapToRoll( parseClassic( 'd10' ))).toMatchObject({ dice: 10 }); }); test( 'Should map dice to second value and count to first value', () => { expect( mapToRoll( parseSimple( '2 10' ))).toMatchObject({ dice: 10, count: 2 }); }); test( 'Should correctly map from 3 to 5 values', () => { expect( mapToRoll( parseSimple( '2 10 -2' ))).toEqual({ dice: 10, count: 2, modifier: -2 }); expect( mapToRoll( parseSimple( '2 10 +2' ))).toEqual({ dice: 10, count: 2, modifier: 2 }); expect( mapToRoll( parseSimple( '2 20 2' ))).toEqual({ dice: 20, count: 2, modifier: 2 }); expect( mapToRoll( parseClassic( 'd10' ))).toEqual({ dice: 10, count: 1, modifier: 0 }); expect( mapToRoll( parseClassic( 'd10+3' ))).toEqual({ dice: 10, count: 1, modifier: 3 }); expect( mapToRoll( parseClassic( '2d10-2' ))).toEqual({ dice: 10, count: 2, modifier: -2 }); }); });
mit
segafan/wme1_jankavan_tlc_edition-repo
src/ProjectMan/ChildFrm.cpp
5751
// ChildFrm.cpp : implementation of the CChildFrame class // #include "stdafx.h" #include "ProjectMan.h" #include "ProjectView.h" #include "ViewHint.h" #include "ViewLog.h" #include "ViewProps.h" #include "ViewTree.h" #include "ChildFrm.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CChildFrame IMPLEMENT_DYNCREATE(CChildFrame, CDCGFMDIChildWindow) BEGIN_MESSAGE_MAP(CChildFrame, CDCGFMDIChildWindow) //{{AFX_MSG_MAP(CChildFrame) ON_WM_DESTROY() ON_WM_CLOSE() //}}AFX_MSG_MAP END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CChildFrame construction/destruction ////////////////////////////////////////////////////////////////////////// CChildFrame::CChildFrame() { // TODO: add member initialization code here } ////////////////////////////////////////////////////////////////////////// CChildFrame::~CChildFrame() { } ////////////////////////////////////////////////////////////////////////// BOOL CChildFrame::PreCreateWindow(CREATESTRUCT& cs) { // TODO: Modify the Window class or styles here by modifying // the CREATESTRUCT cs if( !CDCGFMDIChildWindow::PreCreateWindow(cs) ) return FALSE; cs.style = WS_CHILD /*| WS_VISIBLE*/ | WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | FWS_ADDTOTITLE | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX; return TRUE; } ////////////////////////////////////////////////////////////////////////// void CChildFrame::ActivateFrame(int nCmdShow) { // TODO: Modify this function to change how the frame is activated. nCmdShow = SW_SHOWMAXIMIZED; CDCGFMDIChildWindow::ActivateFrame(nCmdShow); m_Framework.LoadSettings(); } ///////////////////////////////////////////////////////////////////////////// // CChildFrame diagnostics #ifdef _DEBUG void CChildFrame::AssertValid() const { CDCGFMDIChildWindow::AssertValid(); } void CChildFrame::Dump(CDumpContext& dc) const { CDCGFMDIChildWindow::Dump(dc); } #endif //_DEBUG ///////////////////////////////////////////////////////////////////////////// // CChildFrame message handlers ////////////////////////////////////////////////////////////////////////// BOOL CChildFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext) { TVisualObject *SplitMain = new TVisualObject(1,"MainSplitter",1,3,pContext); SplitMain->SetDefaultSize(0, 0, CSize(20,-1)); SplitMain->SetDefaultSize(0, 1, CSize(20,-1)); // right side TVisualObject *SplitRight = new TVisualObject(2, 0,2, 2,1,pContext); SplitRight->SetDefaultSize(0, 0, CSize(-1,80)); TVisualObject *ViewProject = new TVisualObject(3,0,0,pContext,RUNTIME_CLASS(CProjectView), CSize(0,100)); TVisualObject *TabLog = new TVisualObject(4,1,0,pContext,RUNTIME_CLASS(TTabWnd), CSize(0,0)); TVisualObject *ViewHint = new TVisualObject(5, LOC("/str0105/Help"),pContext,RUNTIME_CLASS(CViewHint)); TVisualObject *ViewLog = new TVisualObject(6, LOC("/str0106/Log"),pContext,RUNTIME_CLASS(CViewLog)); TVisualObject *ViewProps = new TVisualObject(7,0,0,pContext,RUNTIME_CLASS(CViewProps), CSize(0,100)); TVisualObject *ViewTree = new TVisualObject(8,0,1,pContext,RUNTIME_CLASS(CViewTree), CSize(0,100)); m_Framework.Add(SplitMain); m_Framework.Add(SplitMain, SplitRight); m_Framework.Add(SplitRight,ViewProject); m_Framework.Add(SplitRight,TabLog); m_Framework.Add(TabLog,ViewHint); m_Framework.Add(TabLog,ViewLog); m_Framework.Add(SplitMain, ViewProps); m_Framework.Add(SplitMain, ViewTree); BOOL ret = m_Framework.Create(this); // get main view TVisualFrameworkIterator iterator(m_Framework); while (!iterator.End()) { TVisualObject *pObject = iterator.Get(); if(pObject->GetWnd() && pObject->GetWnd()->IsKindOf(RUNTIME_CLASS(CProjectView))){ m_View = (CProjectView*)pObject->GetWnd(); break; } iterator ++; } // get view panes if(m_View){ while (!iterator.End()) { TVisualObject *pObject = iterator.Get(); if(!pObject || !pObject->GetSafeWnd()) continue; if(pObject->GetWnd()->IsKindOf(RUNTIME_CLASS(CViewHint))) ((CProjectView*)m_View)->m_ViewHint = (CViewHint*)pObject->GetWnd(); else if(pObject->GetWnd()->IsKindOf(RUNTIME_CLASS(CViewLog))) ((CProjectView*)m_View)->m_ViewLog = (CViewLog*)pObject->GetWnd(); else if(pObject->GetWnd()->IsKindOf(RUNTIME_CLASS(CViewProps))) ((CProjectView*)m_View)->m_ViewProps = (CViewProps*)pObject->GetWnd(); else if(pObject->GetWnd()->IsKindOf(RUNTIME_CLASS(CViewTree))) ((CProjectView*)m_View)->m_ViewTree = (CViewTree*)pObject->GetWnd(); iterator ++; } } return ret; } ////////////////////////////////////////////////////////////////////////// void CChildFrame::OnDestroy() { CDCGFMDIChildWindow::OnDestroy(); if(m_View){ CProjectView* View = (CProjectView*)m_View; View->m_ViewHint->m_View = NULL; View->m_ViewLog->m_View = NULL; View->m_ViewProps->m_View = NULL; View->m_ViewTree->m_View = NULL; View->m_ViewHint = NULL; View->m_ViewLog = NULL; View->m_ViewProps = NULL; View->m_ViewTree = NULL; } if(m_View && m_View->GetSafeHwnd()){ m_Framework.SaveSettings(); } GetParentFrame()->SetActiveView(NULL); SetActiveView(NULL); m_Framework.Destroy(); } ////////////////////////////////////////////////////////////////////////// void CChildFrame::OnClose() { if(m_View && m_View->GetSafeHwnd()){ m_Framework.SaveSettings(); } CDCGFMDIChildWindow::OnClose(); }
mit
InversePalindrome/Prime-Numbers
src/CalculatorPanel.cpp
2545
/* Copyright (c) 2017 InversePalindrome InPal - MainPanel.cpp InversePalindrome.com */ #include "CalculatorPanel.hpp" #include <wx/sizer.h> #include <boost/format.hpp> #include <boost/algorithm/string/trim.hpp> CalculatorPanel::CalculatorPanel(wxWindow* parent, MathDataDefault* mathData) : wxPanel(parent, wxID_ANY), mathData(mathData), taskEntry(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxSize(700u, 600u), wxTE_MULTILINE)), taskSolution(new wxTextCtrl(this, wxID_ANY, "", wxDefaultPosition, wxSize(700u, 50u), wxTE_READONLY)), solveButton(new wxButton(this, wxID_ANY, "Solve")), clearButton(new wxButton(this, wxID_ANY, "Clear")) { SetBackgroundColour(wxColor(128u, 128u, 128u)); auto* topSizer = new wxBoxSizer(wxVERTICAL); auto* buttonSizer = new wxBoxSizer(wxHORIZONTAL); topSizer->Add(taskSolution, 0u, wxEXPAND | wxALL, 10u); topSizer->AddSpacer(20u); buttonSizer->Add(solveButton, 0u, wxALIGN_CENTER); buttonSizer->AddSpacer(5u); buttonSizer->Add(clearButton, 0u, wxALIGN_CENTER); topSizer->Add(buttonSizer, 0u, wxALIGN_TOP | wxALIGN_CENTER_HORIZONTAL); topSizer->AddSpacer(10u); topSizer->Add(taskEntry, 0u, wxEXPAND | wxALL, 10u); topSizer->Fit(this); topSizer->SetSizeHints(this); SetSizer(topSizer); taskSolution->SetFont(wxFont(30u, wxFontFamily::wxFONTFAMILY_DEFAULT, wxFontStyle::wxFONTSTYLE_NORMAL, wxFontWeight::wxFONTWEIGHT_BOLD)); taskEntry->SetFont(wxFont(18u, wxFontFamily::wxFONTFAMILY_DEFAULT, wxFontStyle::wxFONTSTYLE_NORMAL, wxFontWeight::wxFONTWEIGHT_BOLD)); solveButton->Bind(wxEVT_LEFT_DOWN, &CalculatorPanel::OnSolveTask, this); clearButton->Bind(wxEVT_LEFT_DOWN, &CalculatorPanel::OnClearTask, this); } void CalculatorPanel::OnSolveTask(wxMouseEvent & event) { this->mathData->mathSolver.setTask(this->taskEntry->GetValue().ToStdString()); if (this->mathData->mathSolver.solve()) { auto& result = boost::str(boost::format("%.18f") % this->mathData->mathSolver.getValue()); boost::trim_right_if(result, boost::is_any_of("0")); boost::trim_right_if(result, boost::is_any_of(".")); this->taskSolution->SetValue(result); } else { this->taskSolution->SetValue("nan"); } } void CalculatorPanel::OnClearTask(wxMouseEvent & event) { this->mathData->mathSolver.clearTask(); this->taskEntry->Clear(); this->taskSolution->Clear(); }
mit
josh/dom-prof
index.js
3832
(function() { var Promise, aggregateCallLog, childProcess, cssExplain, execFile, explainCssSelectors, phantomjs, __slice = [].slice; cssExplain = require('css-explain').cssExplain; Promise = require('es6-promise').Promise; phantomjs = require('phantomjs'); childProcess = require('child_process'); execFile = function() { var args; args = 1 <= arguments.length ? __slice.call(arguments, 0) : []; return new Promise(function(resolve, reject) { return childProcess.execFile.apply(childProcess, __slice.call(args).concat([function() { var args, error; error = arguments[0], args = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (error) { return reject(error); } else { return resolve(args); } }])); }); }; explainCssSelectors = function(selectors) { var categories, keys, report, scores, total, _i, _len, _name, _ref; if (!(selectors && selectors.length)) { return; } total = 0; categories = { id: 0, "class": 0, tag: 0, universal: 0 }; scores = { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0 }; keys = {}; _ref = cssExplain(selectors); for (_i = 0, _len = _ref.length; _i < _len; _i++) { report = _ref[_i]; categories[report.category] += 1; scores[report.score] += 1; if (keys[_name = report.key] == null) { keys[_name] = 0; } keys[report.key] += 1; total++; } return { total: total, categories: categories, scores: scores, keys: keys }; }; aggregateCallLog = function(calls, propName) { var call, k, prop, report, v, _base, _i, _len; report = { total: 0, calls: {} }; for (_i = 0, _len = calls.length; _i < _len; _i++) { call = calls[_i]; prop = call[propName]; if ((_base = report.calls)[prop] == null) { _base[prop] = 0; } report.calls[prop]++; report.total++; } if (propName === 'selector') { report.explain = explainCssSelectors((function() { var _ref, _results; _ref = report.calls; _results = []; for (k in _ref) { v = _ref[k]; _results.push(k); } return _results; })()); } return report; }; exports.profile = function(url) { return execFile(phantomjs.path, ['--web-security=no', "" + __dirname + "/runner.js", url], { maxBuffer: 1024 * 1024 }).then(function(_arg) { var call, name, props, report, stdout, _i, _len, _ref, _ref1, _ref2; stdout = _arg[0]; report = JSON.parse(stdout); report.cssExplain = explainCssSelectors(report.cssRules); report.eventListeners = aggregateCallLog(report.calls.addEventListener, 'name'); report.querySelector = aggregateCallLog(report.calls.querySelector.concat(report.calls.querySelectorAll), 'selector'); if (report.calls.jquery) { report.jquery.find = aggregateCallLog(report.calls.jquery.find, 'selector'); report.jquery.match = aggregateCallLog(report.calls.jquery.match, 'selector'); report.jquery.event.ready = { total: 0 }; _ref = report.calls.jquery.ready; for (_i = 0, _len = _ref.length; _i < _len; _i++) { call = _ref[_i]; report.jquery.event.ready.total++; } _ref1 = report.jquery.event; for (name in _ref1) { props = _ref1[name]; if ((_ref2 = props.selectors) != null ? _ref2.length : void 0) { report.jquery.event[name].explain = explainCssSelectors(props.selectors); } } } return report; }); }; }).call(this);
mit
aceslick911/mobnation
V1/mobnation/mobnation/App_Start/WebApiConfig.cs
1335
using System; using System.Collections.Generic; using System.Linq; using System.Web.Http; namespace mobnation { public static class WebApiConfig { public static void Register(HttpConfiguration config) { config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); // Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type. // To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries. // For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712. //config.EnableQuerySupport(); // To disable tracing in your application, please comment out or remove the following line of code // For more information, refer to: http://www.asp.net/web-api config.EnableSystemDiagnosticsTracing(); var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml"); config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType); } } }
mit
jsahdeva/skya
app/wp-includes/ms-files.php
29
Multisite support not enabled
mit
kneufeld/django-dynamicstatics
dynamicstatics/templatetags/__init__.py
534
from ipware.ip import get_ip def __lookup(request, url_map, default_url ): """ based on the current request, pick the appropriate static url """ remote_ip = get_ip(request) for ips, url in url_map.iteritems(): if hasattr(ips, '__iter__'): if any( map( lambda ip: remote_ip in ip, ips ) ): return url else: if remote_ip == ips: return url try: return url_map['default'] except KeyError: pass return default_url
mit
aullman/opentok-meet
src/js/whiteboard/app.js
931
/* eslint-disable no-multi-assign */ window.$ = window.jQuery = require('jquery'); const angular = require('angular'); require('opentok-angular'); require('opentok-whiteboard'); require('opentok-whiteboard/opentok-whiteboard.css'); angular.module('opentok-meet', ['opentok', 'opentok-whiteboard']) .controller('WhiteboardCtrl', ['$scope', 'RoomService', 'OTSession', function WhiteboardCtrl($scope, RoomService, OTSession) { $scope.connected = false; // A bit cheeky: Forcing checkSystemRequirements to pass so that this works on mobile OT.checkSystemRequirements = () => true; RoomService.getRoom().then((roomData) => { OTSession.init(roomData.apiKey, roomData.sessionId, roomData.token, (err) => { if (!err) { $scope.$apply(() => { $scope.connected = true; }); } }); }); }]); require('../services.js'); require('../../css/whiteboard.css');
mit
devonChurch/blueberry-danish
src/js/triangle.js
3295
const $ = require('jquery'); const Triangle = class { constructor(Pin, Shape) { this.Pin = Pin; this.Shape = Shape; this.size = 84; this.x = this.Pin.center - (this.size / 2); this.y = this.Pin.center + 130; this.ratio = this.calculateRatio(); this.height = this.size / 2 * this.ratio + this.y; } calculateRatio() { // Find the ratio of an equilateral triangles incline in respect to its // width and height properties. // // This will help us in generating the stencil area but more importantly // we can test if a dot resides within the triangle by using the ratio // as a maximum value i.e if the incline ratio of a dot is > base ratio // it is outside the triangle area. // // We do this by cutting the equilateral triangle in half to create an // easy to manage right angle triangle. From there we use the known // values (width and hypotenuse) to generate the height of the triangle. // Now we know all 3 side measurements we can create a ratio between the // width and the height. const width = 10 / 2; const hypotenuse = 10; const height = Math.sqrt(Math.pow(hypotenuse, 2) - Math.pow(width, 2)); return height / width; // \-------/ // \ | / // \ | / // \|/ } generateStencil() { // This function is for debug purposes ONLY. // Controlled via Pin.Dots.moveDots(); // It renders the current location of the shape on the canvas with a // pink stroke. This is great for testing out your math but the ultimate // goal is for the shapes dimensions to be represented by the particle // system. const ctx = this.Pin.ctx; ctx.beginPath(); ctx.moveTo(this.x, this.y); ctx.lineTo(this.x + this.size, this.y); ctx.lineTo(this.Pin.center, this.size / 2 * this.ratio + this.y); ctx.lineTo(this.x, this.y); ctx.strokeStyle = 'hotpink'; ctx.stroke(); } testRelevance(x, y) { // We need to find if the current dot instance resides within the // triangle area. First we test if the square that surrounds the // triangle has any relevance and if so we move onto calculating the // dots relationship to the triangles actual dimensions. // // We once again cut the equilateral triangle in half to create an easy // to manage right angle triangle. We want to make a right angle // triangle out of the current x and y coordinates and reference it // against the slope of the actual triangle shape (a larger slope === // outside the triangle area). // // To create the test we set the triangle to be in either the top left // or top right corner of the icon triangle (depending on which is // closer i.e. which side of the centre line the dot resides). Using // this corner point and the dots location we can drive a width, height // and starting point for the reference triangle. // // From there we use the equilateral ratio to test if the reference // triangle height is > or < an equilateral height. let center = this.Pin.center, offset = this.size / 2; if ((x < center - offset || x > center + offset) || (y < this.y || y > this.height)) { return false; } let width = x > center ? (center + offset) - x : x - (center - offset), height = y - this.y; return width * this.ratio > height ? true : false; } }; module.exports = Triangle;
mit
Zarel/Pokemon-Showdown
server/chat-plugins/mafia.ts
161949
import {Utils, FS} from '../../lib'; interface MafiaData { // keys for all of these are IDs alignments: {[k: string]: MafiaDataAlignment}; roles: {[k: string]: MafiaDataRole}; themes: {[k: string]: MafiaDataTheme}; IDEAs: {[k: string]: MafiaDataIDEA}; terms: {[k: string]: MafiaDataTerm}; aliases: {[k: string]: ID}; } interface MafiaDataAlignment { name: string; plural: string; color?: string; buttonColor?: string; memo: string[]; image?: string; } interface MafiaDataRole { name: string; memo: string[]; alignment?: string; image?: string; } interface MafiaDataTheme { name: string; desc: string; // roles [players: number]: string; } interface MafiaDataIDEA { name: string; roles: string[]; picks: string[]; choices: number; } interface MafiaDataTerm { name: string; memo: string[]; } interface MafiaLogTable { [date: string]: {[userid: string]: number}; } type MafiaLogSection = 'leaderboard' | 'mvps' | 'hosts' | 'plays' | 'leavers'; type MafiaLog = {[section in MafiaLogSection]: MafiaLogTable}; interface MafiaRole { name: string; safeName: string; id: string; memo: string[]; alignment: string; image: string; } interface MafiaLynch { // number of people on this lynch count: number; // number of votes, accounting for doublevoter etc trueCount: number; lastLynch: number; dir: 'up' | 'down'; lynchers: ID[]; } interface MafiaIDEAData { name: string; // do we trust the roles to parse properly untrusted?: true; roles: string[]; // eg, GestI has 3 choices choices: number; // eg, GestI has 2 things to pick, role and alignment picks: string[]; } interface MafiaIDEAModule { data: MafiaIDEAData | null; timer: NodeJS.Timer | null; discardsHidden: boolean; discardsHTML: string; // users that haven't picked a role yet waitingPick: string[]; } interface MafiaIDEAPlayerData { choices: string[]; originalChoices: string[]; picks: {[choice: string]: string | null}; } const DATA_FILE = 'config/chat-plugins/mafia-data.json'; const LOGS_FILE = 'config/chat-plugins/mafia-logs.json'; // see: https://play.pokemonshowdown.com/fx/ const VALID_IMAGES = [ 'cop', 'dead', 'doctor', 'fool', 'godfather', 'goon', 'hooker', 'mafia', 'mayor', 'villager', 'werewolf', ]; let MafiaData: MafiaData = Object.create(null); let logs: MafiaLog = {leaderboard: {}, mvps: {}, hosts: {}, plays: {}, leavers: {}}; Punishments.addRoomPunishmentType('MAFIAGAMEBAN', 'banned from playing mafia games'); Punishments.addRoomPunishmentType('MAFIAHOSTBAN', 'banned from hosting mafia games'); const hostQueue: ID[] = []; const IDEA_TIMER = 90 * 1000; function readFile(path: string) { try { const json = FS(path).readIfExistsSync(); if (!json) { return false; } return Object.assign(Object.create(null), JSON.parse(json)); } catch (e) { if (e.code !== 'ENOENT') throw e; } } function writeFile(path: string, data: AnyObject) { FS(path).writeUpdate(() => ( JSON.stringify(data) )); } // data assumptions - // the alignments "town" and "solo" always exist (defaults) // <role>.alignment is always a valid key in data.alignments // roles and alignments have no common keys (looked up together in the role parser) // themes and IDEAs have no common keys (looked up together when setting themes) // Load data MafiaData = readFile(DATA_FILE) || {alignments: {}, roles: {}, themes: {}, IDEAs: {}, terms: {}, aliases: {}}; if (!MafiaData.alignments.town) { MafiaData.alignments.town = { name: 'town', plural: 'town', memo: [`This alignment is required for the script to function properly.`], }; } if (!MafiaData.alignments.solo) { MafiaData.alignments.solo = { name: 'solo', plural: 'solo', memo: [`This alignment is required for the script to function properly.`], }; } logs = readFile(LOGS_FILE) || {leaderboard: {}, mvps: {}, hosts: {}, plays: {}, leavers: {}}; const tables: MafiaLogSection[] = ['leaderboard', 'mvps', 'hosts', 'plays', 'leavers']; for (const section of tables) { // Check to see if we need to eliminate an old month's data. const month = new Date().toLocaleString("en-us", {month: "numeric", year: "numeric"}); if (!logs[section]) logs[section] = {}; if (!logs[section][month]) logs[section][month] = {}; if (Object.keys(logs[section]).length >= 3) { // eliminate the oldest month(s) const keys = Utils.sortBy(Object.keys(logs[section]), key => { const [monthStr, yearStr] = key.split('/'); return [parseInt(yearStr), parseInt(monthStr)]; }); while (keys.length > 2) { const curKey = keys.shift(); if (!curKey) break; // should never happen delete logs[section][curKey]; } } } writeFile(LOGS_FILE, logs); class MafiaPlayer extends Rooms.RoomGamePlayer { game: Mafia; safeName: string; role: MafiaRole | null; lynching: ID; /** false - can't hammer (priest), true - can only hammer (actor) */ hammerRestriction: null | boolean; lastLynch: number; treestump: boolean; restless: boolean; silenced: boolean; nighttalk: boolean; revealed: string; IDEA: MafiaIDEAPlayerData | null; /** false - used an action, true - idled, null - no response */ idle: null | boolean; constructor(user: User, game: Mafia) { super(user, game); this.game = game; this.safeName = Utils.escapeHTML(this.name); this.role = null; this.lynching = ''; this.hammerRestriction = null; this.lastLynch = 0; this.treestump = false; this.restless = false; this.silenced = false; this.nighttalk = false; this.revealed = ''; this.IDEA = null; this.idle = null; } getRole(button = false) { if (!this.role) return; let color = MafiaData.alignments[this.role.alignment].color; if (button && MafiaData.alignments[this.role.alignment].buttonColor) { color = MafiaData.alignments[this.role.alignment].buttonColor; } return `<span style="font-weight:bold;color:${color}">${this.role.safeName}</span>`; } updateHtmlRoom() { const user = Users.get(this.id); if (!user?.connected) return; if (this.game.ended) return user.send(`>view-mafia-${this.game.room.roomid}\n|deinit`); for (const conn of user.connections) { void Chat.resolvePage(`view-mafia-${this.game.room.roomid}`, user, conn); } } updateHtmlLynches() { const user = Users.get(this.id); if (!user?.connected) return; const lynches = this.game.lynchBoxFor(this.id); user.send(`>view-mafia-${this.game.room.roomid}\n|selectorhtml|#mafia-lynches|` + lynches); } } class Mafia extends Rooms.RoomGame { started: boolean; theme: MafiaDataTheme | null; hostid: ID; host: string; cohostids: ID[]; cohosts: string[]; playerTable: {[userid: string]: MafiaPlayer}; dead: {[userid: string]: MafiaPlayer}; subs: ID[]; autoSub: boolean; requestedSub: ID[]; hostRequestedSub: ID[]; played: ID[]; hammerCount: number; lynches: {[userid: string]: MafiaLynch}; lynchModifiers: {[userid: string]: number}; hammerModifiers: {[userid: string]: number}; hasPlurality: ID | null; enableNL: boolean; forceLynch: boolean; closedSetup: boolean; noReveal: boolean; selfEnabled: boolean | 'hammer'; takeIdles: boolean; originalRoles: MafiaRole[]; originalRoleString: string; roles: MafiaRole[]; roleString: string; phase: 'signups' | 'locked' | 'IDEApicking' | 'IDEAlocked' | 'day' | 'night'; dayNum: number; timer: NodeJS.Timer | null; dlAt: number; IDEA: MafiaIDEAModule; constructor(room: ChatRoom, host: User) { super(room); this.gameid = 'mafia' as ID; this.title = 'Mafia'; this.playerCap = 20; this.allowRenames = false; this.started = false; this.ended = false; this.theme = null; this.hostid = host.id; this.host = Utils.escapeHTML(host.name); this.cohostids = []; this.cohosts = []; this.playerTable = Object.create(null); this.dead = Object.create(null); this.subs = []; this.autoSub = true; this.requestedSub = []; this.hostRequestedSub = []; this.played = []; this.hammerCount = 0; this.lynches = Object.create(null); this.lynchModifiers = Object.create(null); this.hammerModifiers = Object.create(null); this.hasPlurality = null; this.enableNL = true; this.forceLynch = false; this.closedSetup = false; this.noReveal = false; this.selfEnabled = false; this.takeIdles = true; this.originalRoles = []; this.originalRoleString = ''; this.roles = []; this.roleString = ''; this.phase = "signups"; this.dayNum = 0; this.timer = null; this.dlAt = 0; this.IDEA = { data: null, timer: null, discardsHidden: false, discardsHTML: '', waitingPick: [], }; this.sendHTML(this.roomWindow()); } join(user: User) { if (this.phase !== 'signups') return user.sendTo(this.room, `|error|The game of ${this.title} has already started.`); this.canJoin(user, true); if (this.playerCount >= this.playerCap) return user.sendTo(this.room, `|error|The game of ${this.title} is full.`); if (!this.addPlayer(user)) return user.sendTo(this.room, `|error|You have already joined the game of ${this.title}.`); if (this.subs.includes(user.id)) this.subs.splice(this.subs.indexOf(user.id), 1); this.playerTable[user.id].updateHtmlRoom(); this.sendRoom(`${this.playerTable[user.id].name} has joined the game.`); } leave(user: User) { if (!(user.id in this.playerTable)) { return user.sendTo(this.room, `|error|You have not joined the game of ${this.title}.`); } if (this.phase !== 'signups') return user.sendTo(this.room, `|error|The game of ${this.title} has already started.`); this.playerTable[user.id].destroy(); delete this.playerTable[user.id]; this.playerCount--; let subIndex = this.requestedSub.indexOf(user.id); if (subIndex !== -1) this.requestedSub.splice(subIndex, 1); subIndex = this.hostRequestedSub.indexOf(user.id); if (subIndex !== -1) this.hostRequestedSub.splice(subIndex, 1); this.sendRoom(`${user.name} has left the game.`); for (const conn of user.connections) { void Chat.resolvePage(`view-mafia-${this.room.roomid}`, user, conn); } } static isGameBanned(room: Room, user: User) { return Punishments.hasRoomPunishType(room, toID(user), 'MAFIAGAMEBAN'); } static gameBan(room: Room, user: User, reason: string, duration: number) { Punishments.roomPunish(room, user, { type: 'MAFIAGAMEBAN', id: toID(user), expireTime: Date.now() + (duration * 24 * 60 * 60 * 1000), reason, }); } static ungameBan(room: Room, user: User) { Punishments.roomUnpunish(room, toID(user), 'MAFIAGAMEBAN', false); } static isHostBanned(room: Room, user: User) { return Mafia.isGameBanned(room, user) || Punishments.hasRoomPunishType(room, toID(user), 'MAFIAGAMEBAN'); } static hostBan(room: Room, user: User, reason: string, duration: number) { Punishments.roomPunish(room, user, { type: 'MAFIAHOSTBAN', id: toID(user), expireTime: Date.now() + (duration * 24 * 60 * 60 * 1000), reason, }); } static unhostBan(room: Room, user: User) { Punishments.roomUnpunish(room, toID(user), 'MAFIAHOSTBAN', false); } makePlayer(user: User) { return new MafiaPlayer(user, this); } setRoles(user: User, roleString: string, force = false, reset = false) { let roles = roleString.split(',').map(x => x.trim()); if (roles.length === 1) { // Attempt to set roles from a theme let themeName: string = toID(roles[0]); if (themeName in MafiaData.aliases) themeName = MafiaData.aliases[themeName]; if (themeName in MafiaData.themes) { // setting a proper theme const theme = MafiaData.themes[themeName]; if (!theme[this.playerCount]) { return user.sendTo( this.room, `|error|The theme "${theme.name}" does not have a role list for ${this.playerCount} players.` ); } const themeRoles: string = theme[this.playerCount]; roles = themeRoles.split(',').map(x => x.trim()); this.theme = theme; } else if (themeName in MafiaData.IDEAs) { // setting an IDEA's rolelist as a theme, a la Great Idea const IDEA = MafiaData.IDEAs[themeName]; roles = IDEA.roles; this.theme = null; } else { return user.sendTo(this.room, `|error|${roles[0]} is not a valid theme or IDEA.`); } } else { this.theme = null; } if (roles.length < this.playerCount) { return user.sendTo(this.room, `|error|You have not provided enough roles for the players.`); } else if (roles.length > this.playerCount) { user.sendTo( this.room, `|error|You have provided too many roles, ${roles.length - this.playerCount} ${Chat.plural(roles.length - this.playerCount, 'roles', 'role')} will not be assigned.` ); } if (force) { this.originalRoles = roles.map(r => ({ name: r, safeName: Utils.escapeHTML(r), id: toID(r), alignment: 'solo', image: '', memo: [`To learn more about your role, PM the host (${this.host}).`], })); Utils.sortBy(this.originalRoles, role => role.name); this.roles = this.originalRoles.slice(); this.originalRoleString = this.originalRoles.map( r => `<span style="font-weight:bold;color:${MafiaData.alignments[r.alignment].color || '#FFF'}">${r.safeName}</span>` ).join(', '); this.roleString = this.originalRoleString; this.sendRoom(`The roles have been ${reset ? 're' : ''}set.`); if (reset) this.distributeRoles(); return; } const newRoles: MafiaRole[] = []; const problems: string[] = []; const alignments: string[] = []; const cache: {[k: string]: MafiaRole} = Object.create(null); for (const roleName of roles) { const roleId = roleName.toLowerCase().replace(/[^\w\d\s]/g, ''); if (roleId in cache) { newRoles.push({...cache[roleId]}); } else { const role = Mafia.parseRole(roleName); if (role.problems.length) { problems.push(...role.problems); } if (!alignments.includes(role.role.alignment)) alignments.push(role.role.alignment); cache[roleId] = role.role; newRoles.push(role.role); } } if (alignments.length < 2 && alignments[0] !== 'solo') { problems.push(`There must be at least 2 different alignments in a game!`); } if (problems.length) { for (const problem of problems) { user.sendTo(this.room, `|error|${problem}`); } return user.sendTo(this.room, `|error|To forcibly set the roles, use /mafia force${reset ? "re" : ""}setroles`); } this.IDEA.data = null; this.originalRoles = newRoles; Utils.sortBy(this.originalRoles, role => [role.alignment, role.name]); this.roles = this.originalRoles.slice(); this.originalRoleString = this.originalRoles.map( r => `<span style="font-weight:bold;color:${MafiaData.alignments[r.alignment].color || '#FFF'}">${r.safeName}</span>` ).join(', '); this.roleString = this.originalRoleString; if (!reset) this.phase = 'locked'; this.updatePlayers(); this.sendRoom(`The roles have been ${reset ? 're' : ''}set.`); if (reset) this.distributeRoles(); } static parseRole(roleString: string) { const roleName = roleString.replace(/solo/, '').trim(); const role = { name: roleName, safeName: Utils.escapeHTML(roleName), id: toID(roleName), image: '', memo: ['During the Day, you may vote for someone to be eliminated.'], alignment: '', }; const problems: string[] = []; // if a role has a modifier with an alignment and a proper alignment, // the proper alignment overrides the modifier's alignment let modAlignment = ''; const roleWords = roleString .replace(/\(.+?\)/g, '') // remove (notes within brackets) .split(' ') .map(toID); let iters = 0; outer: while (roleWords.length) { const currentWord = roleWords.slice(); while (currentWord.length) { if (iters++ === 1000) throw new Error(`Infinite loop.`); let currentSearch = currentWord.join(''); if (currentSearch in MafiaData.aliases) currentSearch = MafiaData.aliases[currentSearch]; if (currentSearch in MafiaData.roles) { // we found something with our current search, remove it from the main role and restart const mod = MafiaData.roles[currentSearch]; if (mod.memo) role.memo.push(...mod.memo); if (mod.alignment && !modAlignment) modAlignment = mod.alignment; if (mod.image && !role.image) role.image = mod.image; roleWords.splice(0, currentWord.length); continue outer; } else if (currentSearch in MafiaData.alignments) { if (role.alignment && role.alignment !== currentSearch) { problems.push(`The role ${roleString} has multiple possible alignments (${role.alignment} and ${currentSearch})`); } role.alignment = currentSearch; roleWords.splice(0, currentWord.length); continue outer; } // we didnt find something, take the last word off our current search and continue currentWord.pop(); } // no matches, take the first word off and continue roleWords.shift(); } role.alignment = role.alignment || modAlignment; if (!role.alignment) { // Default to town role.alignment = 'town'; } if (problems.length) { // multiple possible alignment, default to solo role.alignment = 'solo'; role.memo.push(`Your role has multiple conflicting alignments, ask the host for details.`); } else { const alignment = MafiaData.alignments[role.alignment]; if (alignment) { role.memo.push(...MafiaData.alignments[role.alignment].memo); if (alignment.image && !role.image) role.image = alignment.image; } else { problems.push(`Alignment desync: role ${role.name}'s alignment ${role.alignment} doesn't exist in data. Please report this to a mod.`); } } return {role, problems}; } start(user: User, night = false) { if (!user) return; if (this.phase !== 'locked' && this.phase !== 'IDEAlocked') { if (this.phase === 'signups') return user.sendTo(this.room, `You need to close the signups first.`); if (this.phase === 'IDEApicking') { return user.sendTo(this.room, `You must wait for IDEA picks to finish before starting.`); } return user.sendTo(this.room, `The game is already started!`); } if (this.playerCount < 2) return user.sendTo(this.room, `You need at least 2 players to start.`); if (this.phase === 'IDEAlocked') { for (const p in this.playerTable) { if (!this.playerTable[p].role) return user.sendTo(this.room, `|error|Not all players have a role.`); } } else { if (!Object.keys(this.roles).length) return user.sendTo(this.room, `You need to set the roles before starting.`); if (Object.keys(this.roles).length < this.playerCount) { return user.sendTo(this.room, `You have not provided enough roles for the players.`); } } this.started = true; this.sendDeclare(`The game of ${this.title} is starting!`); // Mafia#played gets set in distributeRoles this.distributeRoles(); if (night) { this.night(false, true); } else { this.day(null, true); } if (this.IDEA.data && !this.IDEA.discardsHidden) { this.room.add(`|html|<div class="infobox"><details><summary>IDEA discards:</summary>${this.IDEA.discardsHTML}</details></div>`).update(); } } distributeRoles() { const roles = Utils.shuffle(this.roles.slice()); if (roles.length) { for (const p in this.playerTable) { const role = roles.shift()!; this.playerTable[p].role = role; const u = Users.get(p); this.playerTable[p].revealed = ''; if (u?.connected) { u.send(`>${this.room.roomid}\n|notify|Your role is ${role.safeName}. For more details of your role, check your Role PM.`); } } } this.dead = {}; this.played = [this.hostid, ...this.cohostids, ...(Object.keys(this.playerTable) as ID[])]; this.sendDeclare(`The roles have been distributed.`); this.updatePlayers(); } getPartners(alignment: string, player: MafiaPlayer) { if (!player?.role || ['town', 'solo', 'traitor'].includes(player.role.alignment)) return ""; const partners = []; for (const p in this.playerTable) { if (p === player.id) continue; const role = this.playerTable[p].role; if (role && role.alignment === player.role.alignment) partners.push(this.playerTable[p].name); } return partners.join(", "); } day(extension: number | null = null, initial = false) { if (this.phase !== 'night' && !initial) return; if (this.timer) this.setDeadline(0); if (extension === null) { if (!isNaN(this.hammerCount)) this.hammerCount = Math.floor(Object.keys(this.playerTable).length / 2) + 1; this.clearLynches(); } this.phase = 'day'; if (extension !== null && !initial) { // Day stays same this.setDeadline(extension); } else { this.dayNum++; } if (isNaN(this.hammerCount)) { this.sendDeclare(`Day ${this.dayNum}. Hammering is disabled.`); } else { this.sendDeclare(`Day ${this.dayNum}. The hammer count is set at ${this.hammerCount}`); } for (const p in this.playerTable) { this.playerTable[p].idle = null; } this.sendPlayerList(); this.updatePlayers(); } night(early = false, initial = false) { if (this.phase !== 'day' && !initial) return; if (this.timer) this.setDeadline(0, true); this.phase = 'night'; for (const hostid of [...this.cohostids, this.hostid]) { const host = Users.get(hostid); if (host?.connected) host.send(`>${this.room.roomid}\n|notify|It's night in your game of Mafia!`); } if (this.takeIdles) { this.sendDeclare(`Night ${this.dayNum}. Submit whether you are using an action or idle. If you are using an action, DM your action to the host.`); } else { this.sendDeclare(`Night ${this.dayNum}. PM the host your action, or idle.`); } const hasPlurality = this.getPlurality(); if (!early && hasPlurality) { this.sendRoom(`Plurality is on ${this.playerTable[hasPlurality] ? this.playerTable[hasPlurality].name : 'No Vote'}`); } if (!early && !initial) this.sendRoom(`|raw|<div class="infobox">${this.lynchBox()}</div>`); if (initial && !isNaN(this.hammerCount)) this.hammerCount = Math.floor(Object.keys(this.playerTable).length / 2) + 1; this.updatePlayers(); } lynch(userid: ID, target: ID) { if (this.phase !== 'day') return this.sendUser(userid, `|error|You can only vote during the day.`); let player = this.playerTable[userid]; if (!player && this.dead[userid] && this.dead[userid].restless) player = this.dead[userid]; if (!player) return; if (!(target in this.playerTable) && target !== 'nolynch') { return this.sendUser(userid, `|error|${target} is not a valid player.`); } if (!this.enableNL && target === 'nolynch') return this.sendUser(userid, `|error|No Vote is not allowed.`); if (target === player.id && !this.selfEnabled) return this.sendUser(userid, `|error|Self voting is not allowed.`); const hammering = this.hammerCount - 1 <= (this.lynches[target] ? this.lynches[target].count : 0); if (target === player.id && !hammering && this.selfEnabled === 'hammer') { return this.sendUser(userid, `|error|You may only vote yourself when placing the hammer vote.`); } if (player.hammerRestriction !== null) { this.sendUser(userid, `${this.hammerCount - 1} <= ${(this.lynches[target] ? this.lynches[target].count : 0)}`); if (player.hammerRestriction && !hammering) { return this.sendUser(userid, `|error|You can only vote when placing the hammer vote.`); } if (!player.hammerRestriction && hammering) return this.sendUser(userid, `|error|You cannot place the hammer vote.`); } if (player.lastLynch + 2000 >= Date.now()) { return this.sendUser( userid, `|error|You must wait another ${Chat.toDurationString((player.lastLynch + 2000) - Date.now()) || '1 second'} before you can change your vote.` ); } const previousLynch = player.lynching; if (previousLynch) this.unlynch(userid, true); let lynch = this.lynches[target]; if (!lynch) { this.lynches[target] = { count: 1, trueCount: this.getLynchValue(userid), lastLynch: Date.now(), dir: 'up', lynchers: [userid], }; lynch = this.lynches[target]; } else { lynch.count++; lynch.trueCount += this.getLynchValue(userid); lynch.lastLynch = Date.now(); lynch.dir = 'up'; lynch.lynchers.push(userid); } player.lynching = target; const name = player.lynching === 'nolynch' ? 'No Vote' : this.playerTable[player.lynching].name; const targetUser = Users.get(userid); if (previousLynch) { this.sendTimestamp(`${(targetUser ? targetUser.name : userid)} has shifted their vote from ${previousLynch === 'nolynch' ? 'No Vote' : this.playerTable[previousLynch].name} to ${name}`); } else { this.sendTimestamp( name === 'No Vote' ? `${(targetUser ? targetUser.name : userid)} has abstained from voting.` : `${(targetUser ? targetUser.name : userid)} has voted ${name}.` ); } player.lastLynch = Date.now(); this.hasPlurality = null; if (this.getHammerValue(target) <= lynch.trueCount) { // HAMMER this.sendDeclare(`Hammer! ${target === 'nolynch' ? 'Nobody' : Utils.escapeHTML(name)} was voted out!`); this.sendRoom(`|raw|<div class="infobox">${this.lynchBox()}</div>`); if (target !== 'nolynch') this.eliminate(this.playerTable[target], 'kill'); this.night(true); return; } this.updatePlayersLynches(); } unlynch(userid: ID, force = false) { if (this.phase !== 'day' && !force) return this.sendUser(userid, `|error|You can only vote during the day.`); let player = this.playerTable[userid]; // autoselflynch blocking doesn't apply to restless spirits if (player && this.forceLynch && !force) { return this.sendUser(userid, `|error|You can only shift your vote, not unvote.`); } if (!player && this.dead[userid] && this.dead[userid].restless) player = this.dead[userid]; if (!player?.lynching) return this.sendUser(userid, `|error|You are not voting anyone.`); if (player.lastLynch + 2000 >= Date.now() && !force) { return this.sendUser( userid, `|error|You must wait another ${Chat.toDurationString((player.lastLynch + 2000) - Date.now()) || '1 second'} before you can change your vote.` ); } const lynch = this.lynches[player.lynching]; lynch.count--; lynch.trueCount -= this.getLynchValue(userid); if (lynch.count <= 0) { delete this.lynches[player.lynching]; } else { lynch.lastLynch = Date.now(); lynch.dir = 'down'; lynch.lynchers.splice(lynch.lynchers.indexOf(userid), 1); } const targetUser = Users.get(userid); if (!force) { this.sendTimestamp( player.lynching === 'nolynch' ? `${(targetUser ? targetUser.name : userid)} is no longer abstaining from voting.` : `${(targetUser ? targetUser.name : userid)} has unvoted ${this.playerTable[player.lynching].name}.` ); } player.lynching = ''; player.lastLynch = Date.now(); this.hasPlurality = null; this.updatePlayersLynches(); } /** * Returns HTML code that contains information on the current lynch vote. */ lynchBox() { if (!this.started) return `<strong>The game has not started yet.</strong>`; let buf = `<strong>Votes (Hammer: ${this.hammerCount || "Disabled"})</strong><br />`; const plur = this.getPlurality(); const list = Utils.sortBy(Object.entries(this.lynches), ([key, lynch]) => [ key === plur, -lynch.count, ]); for (const [key, lynch] of list) { buf += `${lynch.count}${plur === key ? '*' : ''} ${this.playerTable[key]?.safeName || 'No Vote'} (${lynch.lynchers.map(a => this.playerTable[a]?.safeName || a).join(', ')})<br />`; } return buf; } lynchBoxFor(userid: ID) { let buf = ''; buf += `<h3>Votes (Hammer: ${this.hammerCount || 'Disabled'}) <button class="button" name="send" value="/msgroom ${this.roomid},/mafia refreshlynches"><i class="fa fa-refresh"></i> Refresh</button></h3>`; const plur = this.getPlurality(); for (const key of Object.keys(this.playerTable).concat((this.enableNL ? ['nolynch'] : [])) as ID[]) { if (this.lynches[key]) { buf += `<p style="font-weight:bold">${this.lynches[key].count}${plur === key ? '*' : ''} ${this.playerTable[key] ? `${this.playerTable[key].safeName} ${this.playerTable[key].revealed ? `[${this.playerTable[key].revealed}]` : ''}` : 'No Vote'} (${this.lynches[key].lynchers.map(a => this.playerTable[a] ? this.playerTable[a].safeName : a).join(', ')}) `; } else { buf += `<p style="font-weight:bold">0 ${this.playerTable[key] ? `${this.playerTable[key].safeName} ${this.playerTable[key].revealed ? `[${this.playerTable[key].revealed}]` : ''}` : 'No Vote'} `; } const isPlayer = (this.playerTable[userid]); const isSpirit = (this.dead[userid] && this.dead[userid].restless); if (isPlayer || isSpirit) { if (isPlayer && this.playerTable[userid].lynching === key || isSpirit && this.dead[userid].lynching === key) { buf += `<button class="button" name="send" value="/msgroom ${this.roomid},/mafia unlynch">Unvote ${this.playerTable[key] ? this.playerTable[key].safeName : 'No Vote'}</button>`; } else if ((this.selfEnabled && !isSpirit) || userid !== key) { buf += `<button class="button" name="send" value="/msgroom ${this.roomid},/mafia lynch ${key}">Vote ${this.playerTable[key] ? this.playerTable[key].safeName : 'No Vote'}</button>`; } } else if (userid === this.hostid || this.cohostids.includes(userid)) { const lynch = this.lynches[key]; if (lynch && lynch.count !== lynch.trueCount) buf += `(${lynch.trueCount})`; if (this.hammerModifiers[key]) buf += `(${this.getHammerValue(key)} to hammer)`; } buf += `</p>`; } return buf; } applyLynchModifier(user: User, target: ID, mod: number) { const targetPlayer = this.playerTable[target] || this.dead[target]; if (!targetPlayer) return this.sendUser(user, `|error|${target} is not in the game of mafia.`); if (target in this.dead && !targetPlayer.restless) { return this.sendUser(user, `|error|${target} is not alive or a restless spirit, and therefore cannot vote.`); } const oldMod = this.lynchModifiers[target]; if (mod === oldMod || ((isNaN(mod) || mod === 1) && oldMod === undefined)) { if (isNaN(mod) || mod === 1) return this.sendUser(user, `|error|${target} already has no vote modifier.`); return this.sendUser(user, `|error|${target} already has a vote modifier of ${mod}`); } const newMod = isNaN(mod) ? 1 : mod; if (targetPlayer.lynching) { this.lynches[targetPlayer.lynching].trueCount += oldMod - newMod; if (this.getHammerValue(targetPlayer.lynching) <= this.lynches[targetPlayer.lynching].trueCount) { this.sendRoom(`${targetPlayer.lynching} has been voted out due to a modifier change! They have not been eliminated.`); this.night(true); } } if (newMod === 1) { delete this.lynchModifiers[target]; return this.sendUser(user, `${targetPlayer.name} has had their vote modifier removed.`); } else { this.lynchModifiers[target] = newMod; return this.sendUser(user, `${targetPlayer.name} has been given a vote modifier of ${newMod}`); } } applyHammerModifier(user: User, target: ID, mod: number) { if (!(target in this.playerTable || target === 'nolynch')) { return this.sendUser(user, `|error|${target} is not in the game of mafia.`); } const oldMod = this.hammerModifiers[target]; if (mod === oldMod || ((isNaN(mod) || mod === 0) && oldMod === undefined)) { if (isNaN(mod) || mod === 0) return this.sendUser(user, `|error|${target} already has no hammer modifier.`); return this.sendUser(user, `|error|${target} already has a hammer modifier of ${mod}`); } const newMod = isNaN(mod) ? 0 : mod; if (this.lynches[target]) { // do this manually since we havent actually changed the value yet if (this.hammerCount + newMod <= this.lynches[target].trueCount) { // make sure these strings are the same this.sendRoom(`${target} has been voted due to a modifier change! They have not been eliminated.`); this.night(true); } } if (newMod === 0) { delete this.hammerModifiers[target]; return this.sendUser(user, `${target} has had their hammer modifier removed.`); } else { this.hammerModifiers[target] = newMod; return this.sendUser(user, `${target} has been given a hammer modifier of ${newMod}`); } } clearLynchModifiers(user: User) { for (const player of [...Object.keys(this.playerTable), ...Object.keys(this.dead)] as ID[]) { if (this.lynchModifiers[player]) this.applyLynchModifier(user, player, 1); } } clearHammerModifiers(user: User) { for (const player of ['nolynch', ...Object.keys(this.playerTable)] as ID[]) { if (this.hammerModifiers[player]) this.applyHammerModifier(user, player, 0); } } getLynchValue(userid: ID) { const mod = this.lynchModifiers[userid]; return (mod === undefined ? 1 : mod); } getHammerValue(userid: ID) { const mod = this.hammerModifiers[userid]; return (mod === undefined ? this.hammerCount : this.hammerCount + mod); } resetHammer() { this.setHammer(Math.floor(Object.keys(this.playerTable).length / 2) + 1); } setHammer(count: number) { this.hammerCount = count; if (isNaN(count)) { this.sendDeclare(`Hammering has been disabled, and votes have been reset.`); } else { this.sendDeclare(`The hammer count has been set at ${this.hammerCount}, and votes have been reset.`); } this.clearLynches(); } shiftHammer(count: number) { this.hammerCount = count; if (isNaN(count)) { this.sendDeclare(`Hammering has been disabled. Votes have not been reset.`); } else { this.sendDeclare(`The hammer count has been shifted to ${this.hammerCount}. Votes have not been reset.`); } const hammered = []; for (const lynch in this.lynches) { if (this.lynches[lynch].trueCount >= this.getHammerValue(lynch as ID)) { hammered.push(lynch === 'nolynch' ? 'Nobody' : lynch); } } if (hammered.length) { this.sendDeclare(`${Chat.count(hammered, "players have")} been hammered: ${hammered.join(', ')}. They have not been removed from the game.`); this.night(true); } } getPlurality() { if (this.hasPlurality) return this.hasPlurality; if (!Object.keys(this.lynches).length) return null; let max = 0; let topLynches: [ID, MafiaLynch][] = []; for (const [key, lynch] of Object.entries(this.lynches)) { if (lynch.count > max) { max = lynch.count; topLynches = [[key as ID, lynch]]; } else if (lynch.count === max) { topLynches.push([key as ID, lynch]); } } if (topLynches.length <= 1) { [this.hasPlurality] = topLynches[0]; return this.hasPlurality; } topLynches = Utils.sortBy(topLynches, ([key, lynch]) => [ lynch.dir === 'down', lynch.dir === 'up' ? lynch.lastLynch : -lynch.lastLynch, ]); [this.hasPlurality] = topLynches[0]; return this.hasPlurality; } eliminate(player: MafiaPlayer, ability = 'kill') { if (!(player.id in this.playerTable)) return; if (!this.started) { // Game has not started, simply kick the player this.sendDeclare(`${player.safeName} was kicked from the game!`); if (this.hostRequestedSub.includes(player.id)) { this.hostRequestedSub.splice(this.hostRequestedSub.indexOf(player.id), 1); } if (this.requestedSub.includes(player.id)) { this.requestedSub.splice(this.requestedSub.indexOf(player.id), 1); } delete this.playerTable[player.id]; this.playerCount--; player.updateHtmlRoom(); player.destroy(); return; } this.dead[player.id] = player; let msg = `${player.safeName}`; switch (ability) { case 'treestump': this.dead[player.id].treestump = true; msg += ` has been treestumped`; break; case 'spirit': this.dead[player.id].restless = true; msg += ` became a restless spirit`; break; case 'spiritstump': this.dead[player.id].treestump = true; this.dead[player.id].restless = true; msg += ` became a restless treestump`; break; case 'kick': msg += ` was kicked from the game`; break; default: msg += ` was eliminated`; } if (player.lynching) this.unlynch(player.id, true); this.sendDeclare(`${msg}! ${!this.noReveal && toID(ability) === 'kill' ? `${player.safeName}'s role was ${player.getRole()}.` : ''}`); if (player.role && !this.noReveal && toID(ability) === 'kill') player.revealed = player.getRole()!; const targetRole = player.role; if (targetRole) { for (const [roleIndex, role] of this.roles.entries()) { if (role.id === targetRole.id) { this.roles.splice(roleIndex, 1); break; } } } this.clearLynches(player.id); delete this.playerTable[player.id]; let subIndex = this.requestedSub.indexOf(player.id); if (subIndex !== -1) this.requestedSub.splice(subIndex, 1); subIndex = this.hostRequestedSub.indexOf(player.id); if (subIndex !== -1) this.hostRequestedSub.splice(subIndex, 1); this.playerCount--; this.updateRoleString(); this.updatePlayers(); player.updateHtmlRoom(); } revealRole(user: User, toReveal: MafiaPlayer, revealAs: string) { if (!this.started) { return user.sendTo(this.room, `|error|You may only reveal roles once the game has started.`); } if (!toReveal.role) { return user.sendTo(this.room, `|error|The user ${toReveal.id} is not assigned a role.`); } toReveal.revealed = revealAs; this.sendDeclare(`${toReveal.safeName}'s role ${toReveal.id in this.playerTable ? `is` : `was`} ${revealAs}.`); this.updatePlayers(); } revive(user: User, toRevive: string, force = false) { if (this.phase === 'IDEApicking') { return user.sendTo(this.room, `|error|You cannot add or remove players while IDEA roles are being picked.`); } if (toRevive in this.playerTable) { user.sendTo(this.room, `|error|The user ${toRevive} is already a living player.`); return; } if (toRevive in this.dead) { const deadPlayer = this.dead[toRevive]; if (deadPlayer.treestump) deadPlayer.treestump = false; if (deadPlayer.restless) deadPlayer.restless = false; this.sendDeclare(`${deadPlayer.safeName} was revived!`); this.playerTable[deadPlayer.id] = deadPlayer; const targetRole = deadPlayer.role; if (targetRole) { this.roles.push(targetRole); } else { // Should never happen deadPlayer.role = { name: `Unknown`, safeName: `Unknown`, id: `unknown`, alignment: 'solo', image: '', memo: [ `You were revived, but had no role. Please let a Mafia Room Owner know this happened. To learn about your role, PM the host (${this.host}).`, ], }; this.roles.push(deadPlayer.role); } Utils.sortBy(this.roles, r => [r.alignment, r.name]); delete this.dead[deadPlayer.id]; } else { const targetUser = Users.get(toRevive); if (!targetUser) return; this.canJoin(targetUser, false, force); const player = this.makePlayer(targetUser); if (this.started) { player.role = { name: `Unknown`, safeName: `Unknown`, id: `unknown`, alignment: 'solo', image: '', memo: [`You were added to the game after it had started. To learn about your role, PM the host (${this.host}).`], }; this.roles.push(player.role); this.played.push(targetUser.id); } else { this.originalRoles = []; this.originalRoleString = ''; this.roles = []; this.roleString = ''; } if (this.subs.includes(targetUser.id)) this.subs.splice(this.subs.indexOf(targetUser.id), 1); this.playerTable[targetUser.id] = player; this.sendDeclare(Utils.html`${targetUser.name} has been added to the game by ${user.name}!`); } this.playerCount++; this.updateRoleString(); this.updatePlayers(); return true; } setDeadline(minutes: number, silent = false) { if (isNaN(minutes)) return; if (!minutes) { if (!this.timer) return; clearTimeout(this.timer); this.timer = null; this.dlAt = 0; if (!silent) this.sendTimestamp(`**The deadline has been cleared.**`); return; } if (minutes < 1 || minutes > 20) return; if (this.timer) clearTimeout(this.timer); this.dlAt = Date.now() + (minutes * 60000); if (minutes > 3) { this.timer = setTimeout(() => { this.sendTimestamp(`**3 minutes left!**`); this.timer = setTimeout(() => { this.sendTimestamp(`**1 minute left!**`); this.timer = setTimeout(() => { this.sendTimestamp(`**Time is up!**`); this.night(); }, 60000); }, 2 * 60000); }, (minutes - 3) * 60000); } else if (minutes > 1) { this.timer = setTimeout(() => { this.sendTimestamp(`**1 minute left!**`); this.timer = setTimeout(() => { this.sendTimestamp(`**Time is up!**`); if (this.phase === 'day') this.night(); }, 60000); }, (minutes - 1) * 60000); } else { this.timer = setTimeout(() => { this.sendTimestamp(`**Time is up!**`); if (this.phase === 'day') this.night(); }, minutes * 60000); } this.sendTimestamp(`**The deadline has been set for ${minutes} minute${minutes === 1 ? '' : 's'}.**`); } sub(player: string, replacement: string) { const oldPlayer = this.playerTable[player]; if (!oldPlayer) return; // should never happen const newUser = Users.get(replacement); if (!newUser) return; // should never happen const newPlayer = this.makePlayer(newUser); newPlayer.role = oldPlayer.role; newPlayer.IDEA = oldPlayer.IDEA; if (oldPlayer.lynching) { // Dont change plurality const lynch = this.lynches[oldPlayer.lynching]; lynch.lynchers.splice(lynch.lynchers.indexOf(oldPlayer.id), 1); lynch.lynchers.push(newPlayer.id); newPlayer.lynching = oldPlayer.lynching; oldPlayer.lynching = ''; } this.playerTable[newPlayer.id] = newPlayer; // Transfer lynches on the old player to the new one if (this.lynches[oldPlayer.id]) { this.lynches[newPlayer.id] = this.lynches[oldPlayer.id]; delete this.lynches[oldPlayer.id]; for (const p in this.playerTable) { if (this.playerTable[p].lynching === oldPlayer.id) this.playerTable[p].lynching = newPlayer.id; } for (const p in this.dead) { if (this.dead[p].restless && this.dead[p].lynching === oldPlayer.id) this.dead[p].lynching = newPlayer.id; } } if (this.hasPlurality === oldPlayer.id) this.hasPlurality = newPlayer.id; if (newUser?.connected) { for (const conn of newUser.connections) { void Chat.resolvePage(`view-mafia-${this.room.roomid}`, newUser, conn); } newUser.send(`>${this.room.roomid}\n|notify|You have been substituted in the mafia game for ${oldPlayer.safeName}.`); } if (this.started) this.played.push(newPlayer.id); this.sendDeclare(`${oldPlayer.safeName} has been subbed out. ${newPlayer.safeName} has joined the game.`); delete this.playerTable[oldPlayer.id]; oldPlayer.destroy(); this.updatePlayers(); if (this.room.roomid === 'mafia' && this.started) { const month = new Date().toLocaleString("en-us", {month: "numeric", year: "numeric"}); if (!logs.leavers[month]) logs.leavers[month] = {}; if (!logs.leavers[month][player]) logs.leavers[month][player] = 0; logs.leavers[month][player]++; writeFile(LOGS_FILE, logs); } } nextSub(userid: ID | null = null) { if (!this.subs.length || (!this.hostRequestedSub.length && ((!this.requestedSub.length || !this.autoSub)) && !userid)) { return; } const nextSub = this.subs.shift(); if (!nextSub) return; const sub = Users.get(nextSub, true); if (!sub?.connected || !sub.named || !this.room.users[sub.id]) return; // should never happen, just to be safe const toSubOut = userid || this.hostRequestedSub.shift() || this.requestedSub.shift(); if (!toSubOut) { // Should never happen this.subs.unshift(nextSub); return; } if (this.hostRequestedSub.includes(toSubOut)) { this.hostRequestedSub.splice(this.hostRequestedSub.indexOf(toSubOut), 1); } if (this.requestedSub.includes(toSubOut)) { this.requestedSub.splice(this.requestedSub.indexOf(toSubOut), 1); } this.sub(toSubOut, sub.id); } customIdeaInit(user: User, choices: number, picks: string[], rolesString: string) { this.originalRoles = []; this.originalRoleString = ''; this.roles = []; this.roleString = ''; const roles = Utils.stripHTML(rolesString); let roleList = roles.split('\n'); if (roleList.length === 1) { roleList = roles.split(',').map(r => r.trim()); } this.IDEA.data = { name: `${this.host}'s custom IDEA`, // already escaped untrusted: true, roles: roleList, picks, choices, }; return this.ideaDistributeRoles(user); } ideaInit(user: User, moduleID: ID) { this.originalRoles = []; this.originalRoleString = ''; this.roles = []; this.roleString = ''; if (moduleID in MafiaData.aliases) moduleID = MafiaData.aliases[moduleID]; this.IDEA.data = MafiaData.IDEAs[moduleID]; if (!this.IDEA.data) return user.sendTo(this.room, `|error|${moduleID} is not a valid IDEA.`); return this.ideaDistributeRoles(user); } ideaDistributeRoles(user: User) { if (!this.IDEA.data) return user.sendTo(this.room, `|error|No IDEA module loaded`); if (this.phase !== 'locked' && this.phase !== 'IDEAlocked') { return user.sendTo(this.room, `|error|The game must be in a locked state to distribute IDEA roles.`); } const neededRoles = this.IDEA.data.choices * this.playerCount; if (neededRoles > this.IDEA.data.roles.length) { return user.sendTo(this.room, `|error|Not enough roles in the IDEA module.`); } const roles = []; const selectedIndexes: number[] = []; for (let i = 0; i < neededRoles; i++) { let randomIndex; do { randomIndex = Math.floor(Math.random() * this.IDEA.data.roles.length); } while (selectedIndexes.includes(randomIndex)); roles.push(this.IDEA.data.roles[randomIndex]); selectedIndexes.push(randomIndex); } Utils.shuffle(roles); this.IDEA.waitingPick = []; for (const p in this.playerTable) { const player = this.playerTable[p]; player.role = null; player.IDEA = { choices: roles.splice(0, this.IDEA.data.choices), originalChoices: [], // MAKE SURE TO SET THIS picks: {}, }; player.IDEA.originalChoices = player.IDEA.choices.slice(); for (const pick of this.IDEA.data.picks) { player.IDEA.picks[pick] = null; this.IDEA.waitingPick.push(p); } const u = Users.get(p); if (u?.connected) u.send(`>${this.room.roomid}\n|notify|Pick your role in the IDEA module.`); } this.phase = 'IDEApicking'; this.updatePlayers(); this.sendDeclare(`${this.IDEA.data.name} roles have been distributed. You will have ${IDEA_TIMER / 1000} seconds to make your picks.`); this.IDEA.timer = setTimeout(() => { this.ideaFinalizePicks(); }, IDEA_TIMER); return ``; } ideaPick(user: User, selection: string[]) { let buf = ''; if (this.phase !== 'IDEApicking') return 'The game is not in the IDEA picking phase.'; if (!this.IDEA?.data) { return this.sendRoom(`Trying to pick an IDEA role with no module running, target: ${JSON.stringify(selection)}. Please report this to a mod.`); } const player = this.playerTable[user.id]; if (!player.IDEA) { return this.sendRoom(`Trying to pick an IDEA role with no player IDEA object, user: ${user.id}. Please report this to a mod.`); } selection = selection.map(toID); if (selection.length === 1 && this.IDEA.data.picks.length === 1) selection = [this.IDEA.data.picks[0], selection[0]]; if (selection.length !== 2) return user.sendTo(this.room, `|error|Invalid selection.`); // input is formatted as ['selection', 'role'] // eg: ['role', 'bloodhound'] // ['alignment', 'alien'] // ['selection', ''] deselects if (selection[1]) { const roleIndex = player.IDEA.choices.map(toID).indexOf(selection[1] as ID); if (roleIndex === -1) { return user.sendTo(this.room, `|error|${selection[1]} is not an available role, perhaps it is already selected?`); } selection[1] = player.IDEA.choices.splice(roleIndex, 1)[0]; } else { selection[1] = ''; } const selected = player.IDEA.picks[selection[0]]; if (selected) { buf += `You have deselected ${selected}. `; player.IDEA.choices.push(selected); } if (player.IDEA.picks[selection[0]] && !selection[1]) { this.IDEA.waitingPick.push(player.id); } else if (!player.IDEA.picks[selection[0]] && selection[1]) { this.IDEA.waitingPick.splice(this.IDEA.waitingPick.indexOf(player.id), 1); } player.IDEA.picks[selection[0]] = selection[1]; if (selection[1]) buf += `You have selected ${selection[0]}: ${selection[1]}.`; player.updateHtmlRoom(); if (!this.IDEA.waitingPick.length) { if (this.IDEA.timer) clearTimeout(this.IDEA.timer); this.ideaFinalizePicks(); return; } return user.sendTo(this.room, buf); } ideaFinalizePicks() { if (!this.IDEA?.data) { return this.sendRoom(`Tried to finalize IDEA picks with no IDEA module running, please report this to a mod.`); } const randed = []; for (const p in this.playerTable) { const player = this.playerTable[p]; if (!player.IDEA) { return this.sendRoom(`Trying to pick an IDEA role with no player IDEA object, user: ${player.id}. Please report this to a mod.`); } let randPicked = false; const role = []; for (const choice of this.IDEA.data.picks) { if (!player.IDEA.picks[choice]) { randPicked = true; const randomChoice = player.IDEA.choices.shift(); if (randomChoice) { player.IDEA.picks[choice] = randomChoice; } else { throw new Error(`No roles left to randomly assign from IDEA module choices.`); } this.sendUser(player.id, `You were randomly assigned ${choice}: ${randomChoice}`); } role.push(`${choice}: ${player.IDEA.picks[choice]}`); } if (randPicked) randed.push(p); // if there's only one option, it's their role, parse it properly let roleName = ''; if (this.IDEA.data.picks.length === 1) { const pick = player.IDEA.picks[this.IDEA.data.picks[0]]; if (!pick) throw new Error('Pick not found when parsing role selected in IDEA module.'); const parsedRole = Mafia.parseRole(pick); if (parsedRole.problems.length) { this.sendRoom(`Problems found when parsing IDEA role ${player.IDEA.picks[this.IDEA.data.picks[0]]}. Please report this to a mod.`); } player.role = parsedRole.role; } else { roleName = role.join('; '); player.role = { name: roleName, safeName: Utils.escapeHTML(roleName), id: toID(roleName), alignment: 'solo', memo: [`(Your role was set from an IDEA.)`], image: '', }; // hardcoding this because it makes GestI so much nicer if (!this.IDEA.data.untrusted) { for (const pick of role) { if (pick.substr(0, 10) === 'alignment:') { const parsedRole = Mafia.parseRole(pick.substr(9)); if (parsedRole.problems.length) { this.sendRoom(`Problems found when parsing IDEA role ${pick}. Please report this to a mod.`); } player.role.alignment = parsedRole.role.alignment; } } } } } this.IDEA.discardsHTML = `<b>Discards:</b><br />`; for (const p of Object.keys(this.playerTable).sort()) { const IDEA = this.playerTable[p].IDEA; if (!IDEA) return this.sendRoom(`No IDEA data for player ${p} when finalising IDEAs. Please report this to a mod.`); this.IDEA.discardsHTML += `<b>${this.playerTable[p].safeName}:</b> ${IDEA.choices.join(', ')}<br />`; } this.phase = 'IDEAlocked'; if (randed.length) { this.sendDeclare(`${randed.join(', ')} did not pick a role in time and were randomly assigned one.`); } this.sendDeclare(`IDEA picks are locked!`); this.sendRoom(`To start, use /mafia start, or to reroll use /mafia ideareroll`); this.updatePlayers(); } sendPlayerList() { this.room.add(`|c:|${(Math.floor(Date.now() / 1000))}|~|**Players (${this.playerCount})**: ${Object.values(this.playerTable).map(p => p.name).sort().join(', ')}`).update(); } updatePlayers() { for (const p in this.playerTable) { this.playerTable[p].updateHtmlRoom(); } for (const p in this.dead) { if (this.dead[p].restless || this.dead[p].treestump) this.dead[p].updateHtmlRoom(); } // Now do the host this.updateHost(); } updatePlayersLynches() { for (const p in this.playerTable) { this.playerTable[p].updateHtmlLynches(); } for (const p in this.dead) { if (this.dead[p].restless || this.dead[p].treestump) this.dead[p].updateHtmlLynches(); } } updateHost(...hosts: ID[]) { if (!hosts.length) hosts = [...this.cohostids, this.hostid]; for (const hostid of hosts) { const host = Users.get(hostid); if (!host?.connected) return; for (const conn of host.connections) { void Chat.resolvePage(`view-mafia-${this.room.roomid}`, host, conn); } } } updateRoleString() { this.roleString = this.roles.map( r => `<span style="font-weight:bold;color:${MafiaData.alignments[r.alignment].color || '#FFF'}">${r.safeName}</span>` ).join(', '); } sendRoom(message: string) { this.room.add(message).update(); } sendHTML(message: string) { this.room.add(`|uhtml|mafia|${message}`).update(); } sendDeclare(message: string) { this.room.add(`|raw|<div class="broadcast-blue">${message}</div>`).update(); } sendStrong(message: string) { this.room.add(`|raw|<strong>${message}</strong>`).update(); } sendTimestamp(message: string) { this.room.add(`|c:|${(Math.floor(Date.now() / 1000))}|~|${message}`).update(); } logAction(user: User, message: string) { if (user.id === this.hostid || this.cohostids.includes(user.id)) return; this.room.sendModsByUser(user, `(${user.name}: ${message})`); } secretLogAction(user: User, message: string) { if (user.id === this.hostid || this.cohostids.includes(user.id)) return; this.room.roomlog(`(${user.name}: ${message})`); } roomWindow() { if (this.ended) return `<div class="infobox">The game of ${this.title} has ended.</div>`; let output = `<div class="broadcast-blue">`; if (this.phase === 'signups') { output += `<h1 style="text-align: center">A game of ${this.title} was created</h2><p style="text-align: center"><button class="button" name="send" value="/mafia join">Join the game</button> <button class="button" name="send" value="/join view-mafia-${this.room.roomid}">Spectate the game</button> <button class="button" name="send" value="/help mafia">Mafia Commands</button></p>`; } else { output += `<p style="font-weight: bold">A game of ${this.title} is in progress.</p><p><button class="button" name="send" value="/msgroom ${this.room.roomid},/mafia sub in">Become a substitute</button> <button class="button" name="send" value="/join view-mafia-${this.room.roomid}">Spectate the game</button> <button class="button" name="send" value="/help mafia">Mafia Commands</button></p>`; } output += `</div>`; return output; } canJoin(user: User, self = false, force = false) { if (!user?.connected) return `User not found.`; const targetString = self ? `You are` : `${user.id} is`; if (!this.room.users[user.id]) return `${targetString} not in the room.`; for (const id of [user.id, ...user.previousIDs]) { if (this.playerTable[id] || this.dead[id]) throw new Chat.ErrorMessage(`${targetString} already in the game.`); if (!force && this.played.includes(id)) { throw new Chat.ErrorMessage(`${self ? `You were` : `${user.id} was`} already in the game.`); } if (Mafia.isGameBanned(this.room, user)) { throw new Chat.ErrorMessage(`${self ? `You are` : `${user.id} is`} banned from joining mafia games.`); } if (this.hostid === id) throw new Chat.ErrorMessage(`${targetString} the host.`); if (this.cohostids.includes(id)) throw new Chat.ErrorMessage(`${targetString} a cohost.`); } if (!force) { for (const alt of user.getAltUsers(true)) { if (this.playerTable[alt.id] || this.played.includes(alt.id)) { throw new Chat.ErrorMessage(`${self ? `You already have` : `${user.id} already has`} an alt in the game.`); } if (this.hostid === alt.id || this.cohostids.includes(alt.id)) { throw new Chat.ErrorMessage(`${self ? `You have` : `${user.id} has`} an alt as a game host.`); } } } } sendUser(user: User | string | null, message: string) { const userObject = (typeof user === 'string' ? Users.get(user) : user); if (!userObject?.connected) return; userObject.sendTo(this.room, message); } setSelfLynch(user: User, setting: boolean | 'hammer') { const from = this.selfEnabled; if (from === setting) { return user.sendTo( this.room, `|error|Selfvoting is already ${setting ? `set to Self${setting === 'hammer' ? 'hammering' : 'lynching'}` : 'disabled'}.` ); } if (from) { this.sendDeclare(`Self${from === 'hammer' ? 'hammering' : 'lynching'} has been ${setting ? `changed to Self${setting === 'hammer' ? 'hammering' : 'lynching'}` : 'disabled'}.`); } else { this.sendDeclare(`Self${setting === 'hammer' ? 'hammering' : 'lynching'} has been ${setting ? 'enabled' : 'disabled'}.`); } this.selfEnabled = setting; if (!setting) { for (const player of Object.values(this.playerTable)) { if (player.lynching === player.id) this.unlynch(player.id, true); } } this.updatePlayers(); } setNoLynch(user: User, setting: boolean) { if (this.enableNL === setting) { return user.sendTo(this.room, `|error|No Vote is already ${setting ? 'enabled' : 'disabled'}.`); } this.enableNL = setting; this.sendDeclare(`No Vote has been ${setting ? 'enabled' : 'disabled'}.`); if (!setting) this.clearLynches('nolynch'); this.updatePlayers(); } clearLynches(target = '') { if (target) delete this.lynches[target]; if (!target) this.lynches = Object.create(null); for (const player of Object.values(this.playerTable)) { if (this.forceLynch) { if (!target || (player.lynching === target)) { player.lynching = player.id; this.lynches[player.id] = { count: 1, trueCount: this.getLynchValue(player.id), lastLynch: Date.now(), dir: 'up', lynchers: [player.id], }; } } else { if (!target || (player.lynching === target)) player.lynching = ''; } } for (const player of Object.values(this.dead)) { if (player.restless && (!target || player.lynching === target)) player.lynching = ''; } this.hasPlurality = null; } onChatMessage(message: string, user: User) { const subIndex = this.hostRequestedSub.indexOf(user.id); if (subIndex !== -1) { this.hostRequestedSub.splice(subIndex, 1); for (const hostid of [...this.cohostids, this.hostid]) { this.sendUser(hostid, `${user.id} has spoken and been removed from the host sublist.`); } } // Hosts can always talk if (this.hostid === user.id || this.cohostids.includes(user.id) || !this.started) { return; } let dead = false; let player = this.playerTable[user.id]; if (!player) { player = this.dead[user.id]; dead = !!player; } const staff = user.can('mute', null, this.room); if (!player) { if (staff) { // Uninvolved staff can talk anytime return; } else { return `You cannot talk while a game of ${this.title} is going on.`; } } if (player.silenced) { return `You are silenced and cannot speak.${staff ? " You can remove this with /mafia unsilence." : ''}`; } if (dead) { if (!player.treestump) { return `You are dead.${staff ? " You can treestump yourself with /mafia treestump." : ''}`; } } if (this.phase === 'night') { if (!player.nighttalk) { return `You cannot talk at night.${staff ? " You can bypass this using /mafia nighttalk." : ''}`; } } } onConnect(user: User) { user.sendTo(this.room, `|uhtml|mafia|${this.roomWindow()}`); } onJoin(user: User) { if (user.id in this.playerTable) { return this.playerTable[user.id].updateHtmlRoom(); } if (user.id === this.hostid || this.cohostids.includes(user.id)) return this.updateHost(user.id); } removeBannedUser(user: User) { // Player was banned, attempt to sub now // If we can't sub now, make subbing them out the top priority if (!(user.id in this.playerTable)) return; this.requestedSub.unshift(user.id); this.nextSub(); } forfeit(user: User) { // Add the player to the sub list. if (!(user.id in this.playerTable)) return; this.requestedSub.push(user.id); this.nextSub(); } end() { this.ended = true; this.sendHTML(this.roomWindow()); this.updatePlayers(); if (this.room.roomid === 'mafia' && this.started) { // Intead of using this.played, which shows players who have subbed out as well // We check who played through to the end when recording playlogs const played = Object.keys(this.playerTable).concat(Object.keys(this.dead)); const month = new Date().toLocaleString("en-us", {month: "numeric", year: "numeric"}); if (!logs.plays[month]) logs.plays[month] = {}; for (const player of played) { if (!logs.plays[month][player]) logs.plays[month][player] = 0; logs.plays[month][player]++; } if (!logs.hosts[month]) logs.hosts[month] = {}; for (const hostid of [...this.cohostids, this.hostid]) { if (!logs.hosts[month][hostid]) logs.hosts[month][hostid] = 0; logs.hosts[month][hostid]++; } writeFile(LOGS_FILE, logs); } if (this.timer) { clearTimeout(this.timer); this.timer = null; } this.destroy(); } destroy() { // Slightly modified to handle dead players if (this.timer) clearTimeout(this.timer); if (this.IDEA.timer) clearTimeout(this.IDEA.timer); this.room.game = null; // @ts-ignore readonly this.room = null; for (const i in this.playerTable) { this.playerTable[i].destroy(); } for (const i in this.dead) { this.dead[i].destroy(); } } } export const pages: Chat.PageTable = { mafia(query, user) { if (!user.named) return Rooms.RETRY_AFTER_LOGIN; if (!query.length) return this.close(); let roomid = query.shift(); if (roomid === 'groupchat') roomid += `-${query.shift()}-${query.shift()}`; const room = Rooms.get(roomid); const game = room?.getGame(Mafia); if (!room?.users[user.id] || !game || game.ended) { return this.close(); } const isPlayer = user.id in game.playerTable; const isHost = user.id === game.hostid || game.cohostids.includes(user.id); this.title = game.title; let buf = `<div class="pad broadcast-blue">`; buf += `<button class="button" name="send" value="/join view-mafia-${room.roomid}" style="float:left"><i class="fa fa-refresh"></i> Refresh</button>`; buf += `<br/><br/><h1 style="text-align:center;">${game.title}</h1><h3>Host: ${game.host}</h3>${game.cohostids[0] ? `<h3>Cohosts: ${game.cohosts.sort().join(', ')}</h3>` : ''}`; buf += `<p style="font-weight:bold;">Players (${game.playerCount}): ${Object.values(game.playerTable).map(p => p.safeName).sort().join(', ')}</p>`; if (game.started && Object.keys(game.dead).length > 0) { buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">Dead Players</summary>`; for (const d in game.dead) { const dead = game.dead[d]; buf += `<p style="font-weight:bold;">${dead.safeName} ${dead.revealed ? '(' + dead.revealed + ')' : ''}`; if (dead.treestump) buf += ` (is a Treestump)`; if (dead.restless) buf += ` (is a Restless Spirit)`; if (isHost && !dead.revealed) { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia revealrole ${dead.id}";">Reveal</button>`; } buf += `</p>`; } buf += `</details></p>`; } buf += `<hr/>`; if (isPlayer && game.phase === 'IDEApicking') { buf += `<p><b>IDEA information:</b><br />`; const IDEA = game.playerTable[user.id].IDEA; if (!IDEA) { return game.sendRoom(`IDEA picking phase but no IDEA object for user: ${user.id}. Please report this to a mod.`); } for (const key in IDEA.picks) { const pick = IDEA.picks[key]; buf += `<b>${key}:</b> `; if (!pick) { buf += `<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">clear</button>`; } else { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia ideapick ${key},">clear</button>`; } const selectedIndex = pick ? IDEA.originalChoices.indexOf(pick) : -1; for (let i = 0; i < IDEA.originalChoices.length; i++) { const choice = IDEA.originalChoices[i]; if (i === selectedIndex) { buf += `<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">${choice}</button>`; } else { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia ideapick ${key}, ${toID(choice)}">${choice}</button>`; } } buf += `<br />`; } buf += `</p>`; buf += `<p><details><summary class="button" style="display:inline-block"><b>Role details:</b></summary><p>`; for (const role of IDEA.originalChoices) { const roleObject = Mafia.parseRole(role); buf += `<details><summary>${role}</summary>`; buf += `<table><tr><td style="text-align:center;"><td style="text-align:left;width:100%"><ul>${roleObject.role.memo.map(m => `<li>${m}</li>`).join('')}</ul></td></tr></table>`; buf += `</details>`; } buf += `</p></details></p>`; } if (game.IDEA.data) { buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">${game.IDEA.data.name} information</summary>`; if (game.IDEA.discardsHTML && (!game.IDEA.discardsHidden || isHost)) { buf += `<details><summary class="button" style="text-align:left; display:inline-block">Discards:</summary><p>${game.IDEA.discardsHTML}</p></details>`; } buf += `<details><summary class="button" style="text-align:left; display:inline-block">Role list</summary><p>${game.IDEA.data.roles.join('<br />')}</p></details>`; buf += `</details></p>`; } else { if (!game.closedSetup || isHost) { if (game.theme) { buf += `<p><span style="font-weight:bold;">Theme</span>: ${game.theme.name}</p>`; buf += `<p>${game.theme.desc}</p>`; } if (game.noReveal) { buf += `<p><span style="font-weight:bold;">Original Rolelist${game.closedSetup ? ' (CS)' : ''}</span>: ${game.originalRoleString}</p>`; } else { buf += `<p><span style="font-weight:bold;">Rolelist${game.closedSetup ? ' (CS)' : ''}</span>: ${game.roleString}</p>`; } } } if (isPlayer) { const role = game.playerTable[user.id].role; if (role) { buf += `<h3>${game.playerTable[user.id].safeName}, you are a ${game.playerTable[user.id].getRole()}</h3>`; if (!['town', 'solo'].includes(role.alignment)) { buf += `<p><span style="font-weight:bold">Partners</span>: ${game.getPartners(role.alignment, game.playerTable[user.id])}</p>`; } buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">Role Details</summary>`; buf += `<table><tr><td style="text-align:center;"><img width="75" height="75" src="//${Config.routes.client}/fx/mafia-${role.image || 'villager'}.png"></td><td style="text-align:left;width:100%"><ul>${role.memo.map(m => `<li>${m}</li>`).join('')}</ul></td></tr></table>`; buf += `</details></p>`; } } if (game.phase === "day") { buf += `<span id="mafia-lynches">`; buf += game.lynchBoxFor(user.id); buf += `</span>`; } else if (game.phase === "night" && isPlayer) { if (!game.takeIdles) { buf += `<p style="font-weight:bold;">PM the host (${game.host}) the action you want to use tonight, and who you want to use it on. Or PM the host "idle".</p>`; } else { buf += `<b>Night Actions:</b>`; if (game.playerTable[user.id].idle === null) { buf += `<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">clear</button>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia action">action</button>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia idle">idle</button>`; } else { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia noresponse">clear</button>`; if (game.playerTable[user.id].idle === false) { buf += `<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">action</button>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia idle">idle</button>`; } else { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia action">action</button>`; buf += `<button class="button disabled" style="font-weight:bold; color:#575757; font-weight:bold; background-color:#d3d3d3;">idle</button>`; } } buf += `<br/>`; } } if (isHost) { if (game.phase === "night" && isHost && game.takeIdles) { buf += `<h3>Night Responses</h3>`; let actions = ``; let idles = ``; let noResponses = ``; for (const p in game.playerTable) { const player = game.playerTable[p]; if (player.idle === true) { idles += `${player.safeName}<br/>`; } else if (player.idle === false) { actions += `${player.safeName}<br/>`; } else { noResponses += `${player.safeName}<br/>`; } } buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">Idles</summary>${idles}</span></details></p>`; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">Actions</summary>${actions}</span></details></p>`; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">No Response</summary>${noResponses}</span></details></p>`; } buf += `<h3>Host options</h3>`; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">General Options</summary>`; buf += `<h3>General Options</h3>`; if (!game.started) { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia closedsetup ${game.closedSetup ? 'off' : 'on'}">${game.closedSetup ? 'Disable' : 'Enable'} Closed Setup</button>`; if (game.phase === 'locked' || game.phase === 'IDEAlocked') { buf += ` <button class="button" name="send" value="/msgroom ${room.roomid},/mafia start">Start Game</button>`; } else { buf += ` <button class="button" name="send" value="/msgroom ${room.roomid},/mafia close">Close Signups</button>`; } } else if (game.phase === 'day') { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia night">Go to Night ${game.dayNum}</button>`; } else if (game.phase === 'night') { buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia day">Go to Day ${game.dayNum + 1}</button> <button class="button" name="send" value="/msgroom ${room.roomid},/mafia extend">Return to Day ${game.dayNum}</button>`; } buf += ` <button class="button" name="send" value="/msgroom ${room.roomid},/mafia selflynch ${game.selfEnabled === true ? 'off' : 'on'}">${game.selfEnabled === true ? 'Disable' : 'Enable'} self lynching</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia ${game.enableNL ? 'disable' : 'enable'}nl">${game.enableNL ? 'Disable' : 'Enable'} No Vote</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia reveal ${game.noReveal ? 'on' : 'off'}">${game.noReveal ? 'Enable' : 'Disable'} revealing of roles</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia autosub ${game.autoSub ? 'off' : 'on'}">${game.autoSub ? "Disable" : "Enable"} automatic subbing of players</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia end">End Game</button>`; buf += `<p>To set a deadline, use <strong>/mafia deadline [minutes]</strong>.<br />To clear the deadline use <strong>/mafia deadline off</strong>.</p><hr/></details></p>`; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">Player Options</summary>`; buf += `<h3>Player Options</h3>`; for (const p in game.playerTable) { const player = game.playerTable[p]; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block"><span style="font-weight:bold;">`; buf += `${player.safeName} (${player.role ? player.getRole(true) : ''})`; buf += game.lynchModifiers[p] !== undefined ? `(votes worth ${game.getLynchValue(p as ID)})` : ''; buf += player.hammerRestriction !== null ? `(${player.hammerRestriction ? 'actor' : 'priest'})` : ''; buf += player.silenced ? '(silenced)' : ''; buf += player.nighttalk ? '(insomniac)' : ''; buf += `</summary>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia kill ${player.id}">Kill</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia treestump ${player.id}">Make a Treestump (Kill)</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia spirit ${player.id}">Make a Restless Spirit (Kill)</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia spiritstump ${player.id}">Make a Restless Treestump (Kill)</button> `; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia sub next, ${player.id}">Force sub</button></span></details></p>`; } for (const d in game.dead) { const dead = game.dead[d]; buf += `<p style="font-weight:bold;">${dead.safeName} (${dead.role ? dead.getRole() : ''})`; if (dead.treestump) buf += ` (is a Treestump)`; if (dead.restless) buf += ` (is a Restless Spirit)`; if (game.lynchModifiers[d] !== undefined) buf += ` (votes worth ${game.getLynchValue(d as ID)})`; buf += dead.hammerRestriction !== null ? `(${dead.hammerRestriction ? 'actor' : 'priest'})` : ''; buf += dead.silenced ? '(silenced)' : ''; buf += dead.nighttalk ? '(insomniac)' : ''; buf += `: <button class="button" name="send" value="/msgroom ${room.roomid},/mafia revive ${dead.id}">Revive</button></p>`; } buf += `<hr/></details></p>`; buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">How to setup roles</summary>`; buf += `<h3>Setting the roles</h3>`; buf += `<p>To set the roles, use /mafia setroles [comma seperated list of roles] OR /mafia setroles [theme] in ${room.title}.</p>`; buf += `<p>If you set the roles from a theme, the role parser will get all the correct roles for you. (Not all themes are supported).</p>`; buf += `<p>The following key words determine a role's alignment (If none are found, the default alignment is town):</p>`; buf += `<p style="font-weight:bold">${Object.values(MafiaData.alignments).map(a => `<span style="color:${a.color || '#FFF'}">${a.name}</span>`).join(', ')}</p>`; buf += `<p>Please note that anything inside (parentheses) is ignored by the role parser.</p>`; buf += `<p>If you have roles that have conflicting alignments or base roles, you can use /mafia forcesetroles [comma seperated list of roles] to forcibly set the roles.</p>`; buf += `<p>Please note that you will have to PM all the players their alignment, partners (if any), and other information about their role because the server will not provide it.</p>`; buf += `<hr/></details></p>`; buf += `<p style="font-weight:bold;">Players who will be subbed unless they talk: ${game.hostRequestedSub.join(', ')}</p>`; buf += `<p style="font-weight:bold;">Players who are requesting a sub: ${game.requestedSub.join(', ')}</p>`; } buf += `<p style="font-weight:bold;">Sub List: ${game.subs.join(', ')}</p>`; if (!isHost) { if (game.phase === 'signups') { if (isPlayer) { buf += `<p><button class="button" name="send" value="/msgroom ${room.roomid},/mafia leave">Leave game</button></p>`; } else { buf += `<p><button class="button" name="send" value="/msgroom ${room.roomid},/mafia join">Join game</button></p>`; } } else if ((!isPlayer && game.subs.includes(user.id)) || (isPlayer && !game.requestedSub.includes(user.id))) { buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">${isPlayer ? 'Request to be subbed out' : 'Cancel sub request'}</summary>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia sub out">${isPlayer ? 'Confirm request to be subbed out' : 'Confirm cancelation of sub request'}</button></details></p>`; } else { buf += `<p><details><summary class="button" style="text-align:left; display:inline-block">${isPlayer ? 'Cancel sub request' : 'Join the game as a sub'}</summary>`; buf += `<button class="button" name="send" value="/msgroom ${room.roomid},/mafia sub in">${isPlayer ? 'Confirm cancelation of sub request' : 'Confirm that you want to join the game'}</button></details></p>`; } } buf += `</div>`; return buf; }, mafialadder(query, user) { if (!user.named) return Rooms.RETRY_AFTER_LOGIN; const mafiaRoom = Rooms.get('mafia'); if (!query.length || !mafiaRoom) return this.close(); const headers: {[k: string]: {title: string, type: string, section: MafiaLogSection}} = { leaderboard: {title: 'Leaderboard', type: 'Points', section: 'leaderboard'}, mvpladder: {title: 'MVP Ladder', type: 'MVPs', section: 'mvps'}, hostlogs: {title: 'Host Logs', type: 'Hosts', section: 'hosts'}, playlogs: {title: 'Play Logs', type: 'Plays', section: 'plays'}, leaverlogs: {title: 'Leaver Logs', type: 'Leavers', section: 'leavers'}, }; const date = new Date(); if (query[1] === 'prev') date.setMonth(date.getMonth() - 1); const month = date.toLocaleString("en-us", {month: "numeric", year: "numeric"}); const ladder = headers[query[0]]; if (!ladder) return this.close(); if (['hosts', 'plays', 'leavers'].includes(ladder.section)) this.checkCan('mute', null, mafiaRoom); this.title = `Mafia ${ladder.title} (${date.toLocaleString("en-us", {month: 'long'})} ${date.getFullYear()})`; let buf = `<div class="pad ladder">`; buf += `${query[1] === 'prev' ? '' : `<button class="button" name="send" value="/join view-mafialadder-${query[0]}" style="float:left"><i class="fa fa-refresh"></i> Refresh</button> <button class="button" name="send" value="/join view-mafialadder-${query[0]}-prev" style="float:left">View last month's ${ladder.title}</button>`}`; buf += `<br /><br />`; const section = ladder.section; if (!logs[section][month] || !Object.keys(logs[section][month]).length) { buf += `${ladder.title} for ${date.toLocaleString("en-us", {month: 'long'})} ${date.getFullYear()} not found.</div>`; return buf; } const entries = Utils.sortBy(Object.entries(logs[section][month]), ([key, value]) => ( -value )); buf += `<table style="margin-left: auto; margin-right: auto"><tbody><tr><th colspan="2"><h2 style="margin: 5px auto">Mafia ${ladder.title} for ${date.toLocaleString("en-us", {month: 'long'})} ${date.getFullYear()}</h1></th></tr>`; buf += `<tr><th>User</th><th>${ladder.type}</th></tr>`; for (const [key, value] of entries) { buf += `<tr><td>${key}</td><td>${value}</td></tr>`; } return buf + `</table></div>`; }, }; export const commands: Chat.ChatCommands = { mafia: { ''(target, room, user) { room = this.requireRoom(); const game = room.getGame(Mafia); if (game) { if (!this.runBroadcast()) return; return this.sendReply(`|html|${game.roomWindow()}`); } return this.parse('/help mafia'); }, forcehost: 'host', nexthost: 'host', host(target, room, user, connection, cmd) { room = this.requireRoom(); if (room.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); this.checkChat(); if (room.type !== 'chat') return this.errorReply(`This command is only meant to be used in chat rooms.`); if (room.game) return this.errorReply(`There is already a game of ${room.game.title} in progress in this room.`); const nextHost = room.roomid === 'mafia' && cmd === 'nexthost'; if (nextHost || !room.auth.has(user.id)) this.checkCan('show', null, room); let targetUser!: User | null; let targetUsername!: string; if (nextHost) { if (!hostQueue.length) return this.errorReply(`Nobody is on the host queue.`); const skipped = []; let hostid; while ((hostid = hostQueue.shift())) { ({targetUser, targetUsername} = this.splitUser(hostid, {exactName: true})); if (!targetUser?.connected || !room.users[targetUser.id] || Mafia.isHostBanned(room, targetUser)) { skipped.push(hostid); targetUser = null; } else { // found a host break; } } if (skipped.length) { this.sendReply(`${skipped.join(', ')} ${Chat.plural(skipped.length, 'were', 'was')} not online, not in the room, or are host banned and were removed from the host queue.`); } if (!targetUser) return this.errorReply(`Nobody on the host queue could be hosted.`); } else { ({targetUser, targetUsername} = this.splitUser(target, {exactName: true})); if (room.roomid === 'mafia' && hostQueue.length && toID(targetUsername) !== hostQueue[0]) { if (!cmd.includes('force')) { return this.errorReply(`${targetUsername} isn't the next host on the queue. Use /mafia forcehost if you're sure.`); } } } if (!targetUser?.connected) { return this.errorReply(`The user "${targetUsername}" was not found.`); } if (!nextHost && targetUser.id !== user.id) this.checkCan('mute', null, room); if (!room.users[targetUser.id]) { return this.errorReply(`${targetUsername} is not in this room, and cannot be hosted.`); } if (Mafia.isHostBanned(room, targetUser)) { return this.errorReply(`${targetUsername} is banned from hosting mafia games.`); } room.game = new Mafia(room, targetUser); for (const conn of targetUser.connections) { void Chat.resolvePage(`view-mafia-${room.roomid}`, targetUser, conn); } room.addByUser(user, `${targetUser.name} was appointed the mafia host by ${user.name}.`); if (room.roomid === 'mafia') { const queueIndex = hostQueue.indexOf(targetUser.id); if (queueIndex > -1) hostQueue.splice(queueIndex, 1); room.add(`|c:|${(Math.floor(Date.now() / 1000))}|~|**Mafiasignup!**`).update(); } this.modlog('MAFIAHOST', targetUser, null, {noalts: true, noip: true}); }, hosthelp: [ `/mafia host [user] - Create a game of Mafia with [user] as the host. Requires whitelist + % @ # &, drivers+ can host other people.`, ], q: 'queue', queue(target, room, user) { room = this.requireRoom('mafia' as RoomID); if (room.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); const [command, targetUserID] = target.split(',').map(toID); switch (command) { case 'forceadd': case 'add': this.checkChat(); // any rank can selfqueue if (targetUserID === user.id) { if (!room.auth.has(user.id)) this.checkCan('show', null, room); } else { this.checkCan('mute', null, room); } if (!targetUserID) return this.parse(`/help mafia queue`); const targetUser = Users.get(targetUserID); if ((!targetUser?.connected) && !command.includes('force')) { return this.errorReply(`User ${targetUserID} not found. To forcefully add the user to the queue, use /mafia queue forceadd, ${targetUserID}`); } if (hostQueue.includes(targetUserID)) return this.errorReply(`User ${targetUserID} is already on the host queue.`); if (targetUser && Mafia.isHostBanned(room, targetUser)) { return this.errorReply(`User ${targetUserID} is banned from hosting mafia games.`); } hostQueue.push(targetUserID); room.add(`User ${targetUserID} has been added to the host queue by ${user.name}.`).update(); break; case 'del': case 'delete': case 'remove': // anyone can self remove if (targetUserID !== user.id) this.checkCan('mute', null, room); const index = hostQueue.indexOf(targetUserID); if (index === -1) return this.errorReply(`User ${targetUserID} is not on the host queue.`); hostQueue.splice(index, 1); room.add(`User ${targetUserID} has been removed from the host queue by ${user.name}.`).update(); break; case '': case 'show': case 'view': if (!this.runBroadcast()) return; this.sendReplyBox(`<strong>Host Queue:</strong> ${hostQueue.join(', ')}`); break; default: this.parse('/help mafia queue'); } }, queuehelp: [ `/mafia queue - Shows the upcoming users who are going to host.`, `/mafia queue add, (user) - Adds the user to the hosting queue. Requires whitelist + % @ # &`, `/mafia queue remove, (user) - Removes the user from the hosting queue. Requires whitelist + % @ # &`, ], qadd: 'queueadd', qforceadd: 'queueadd', queueforceadd: 'queueadd', queueadd(target, room, user, connection, cmd) { this.parse(`/mafia queue ${cmd.includes('force') ? `forceadd` : `add`}, ${target}`); }, qdel: 'queueremove', qdelete: 'queueremove', qremove: 'queueremove', queueremove(target, room, user) { this.parse(`/mafia queue remove, ${target}`); }, join(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkChat(null, room); game.join(user); }, joinhelp: [`/mafia join - Join the game.`], leave(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); game.leave(user); }, leavehelp: [`/mafia leave - Leave the game. Can only be done while signups are open.`], playercap(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (game.phase !== 'signups') return this.errorReply(`Signups are already closed.`); if (toID(target) === 'none') target = '20'; const num = parseInt(target); if (isNaN(num) || num > 20 || num < 2) return this.parse('/help mafia playercap'); if (num < game.playerCount) { return this.errorReply(`Player cap has to be equal or more than the amount of players in game.`); } if (num === game.playerCap) return this.errorReply(`Player cap is already set at ${game.playerCap}.`); game.playerCap = num; game.sendDeclare(`Player cap has been set to ${game.playerCap}`); game.logAction(user, `set playercap to ${num}`); }, playercaphelp: [ `/mafia playercap [cap|none]- Limit the number of players being able to join the game. Player cap cannot be more than 20 or less than 2. Requires host % @ # &`, ], close(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (game.phase !== 'signups') return this.errorReply(`Signups are already closed.`); if (game.playerCount < 2) return this.errorReply(`You need at least 2 players to start.`); game.phase = 'locked'; game.sendHTML(game.roomWindow()); game.updatePlayers(); game.logAction(user, `closed signups`); }, closehelp: [`/mafia close - Closes signups for the current game. Requires host % @ # &`], cs: 'closedsetup', closedsetup(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const action = toID(target); if (!['on', 'off'].includes(action)) return this.parse('/help mafia closedsetup'); if (game.started) { return this.errorReply(`You can't ${action === 'on' ? 'enable' : 'disable'} closed setup because the game has already started.`); } if ((action === 'on' && game.closedSetup) || (action === 'off' && !game.closedSetup)) { return this.errorReply(`Closed setup is already ${game.closedSetup ? 'enabled' : 'disabled'}.`); } game.closedSetup = action === 'on'; game.sendDeclare(`The game is ${action === 'on' ? 'now' : 'no longer'} a closed setup.`); game.updateHost(); game.logAction(user, `${game.closedSetup ? 'enabled' : 'disabled'} closed setup`); }, closedsetuphelp: [ `/mafia closedsetup [on|off] - Sets if the game is a closed setup. Closed setups don't show the role list to players. Requires host % @ # &`, ], reveal(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const action = toID(target); if (!['on', 'off'].includes(action)) return this.parse('/help mafia reveal'); if ((action === 'off' && game.noReveal) || (action === 'on' && !game.noReveal)) { return user.sendTo( room, `|error|Revealing of roles is already ${game.noReveal ? 'disabled' : 'enabled'}.` ); } game.noReveal = action === 'off'; game.sendDeclare(`Revealing of roles has been ${action === 'off' ? 'disabled' : 'enabled'}.`); game.updatePlayers(); game.logAction(user, `${game.noReveal ? 'disabled' : 'enabled'} reveals`); }, revealhelp: [`/mafia reveal [on|off] - Sets if roles reveal on death or not. Requires host % @ # &`], takeidles(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const action = toID(target); if (!['on', 'off'].includes(action)) return this.parse('/help mafia takeidles'); if ((action === 'off' && !game.takeIdles) || (action === 'on' && game.takeIdles)) { return this.errorReply(`Actions and idles are already ${game.takeIdles ? '' : 'not '}being accepted.`); } game.takeIdles = action === 'on'; game.sendDeclare(`Actions and idles are ${game.takeIdles ? 'now' : 'no longer'} being accepted.`); game.updatePlayers(); }, takeidleshelp: [`/mafia takeidles [on|off] - Sets if idles are accepted by the script or not. Requires host % @ # &`], resetroles: 'setroles', forceresetroles: 'setroles', forcesetroles: 'setroles', setroles(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const reset = cmd.includes('reset'); if (reset) { if (game.phase !== 'day' && game.phase !== 'night') return this.errorReply(`The game has not started yet.`); } else { if (game.phase !== 'locked' && game.phase !== 'IDEAlocked') { return this.errorReply(game.phase === 'signups' ? `You need to close signups first.` : `The game has already started.`); } } if (!target) return this.parse('/help mafia setroles'); game.setRoles(user, target, cmd.includes('force'), reset); game.logAction(user, `${reset ? 're' : ''}set roles`); }, setroleshelp: [ `/mafia setroles [comma separated roles] - Set the roles for a game of mafia. You need to provide one role per player.`, `/mafia forcesetroles [comma separated roles] - Forcibly set the roles for a game of mafia. No role PM information or alignment will be set.`, `/mafia resetroles [comma separated roles] - Reset the roles in an ongoing game.`, ], idea(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkCan('show', null, room); if (!user.can('mute', null, room) && game.hostid !== user.id && !game.cohostids.includes(user.id)) { return this.errorReply(`/mafia idea - Access denied.`); } if (game.started) return this.errorReply(`You cannot start an IDEA after the game has started.`); if (game.phase !== 'locked' && game.phase !== 'IDEAlocked') { return this.errorReply(`You need to close the signups first.`); } game.ideaInit(user, toID(target)); game.logAction(user, `started an IDEA`); }, ideahelp: [ `/mafia idea [idea] - starts the IDEA module [idea]. Requires + % @ # &, voices can only start for themselves`, `/mafia ideareroll - rerolls the IDEA module. Requires host % @ # &`, `/mafia ideapick [selection], [role] - selects a role`, `/mafia ideadiscards - shows the discarded roles`, ], customidea(target, room, user) { room = this.requireRoom(); this.checkCan('mute', null, room); const game = this.requireGame(Mafia); if (game.started) return this.errorReply(`You cannot start an IDEA after the game has started.`); if (game.phase !== 'locked' && game.phase !== 'IDEAlocked') { return this.errorReply(`You need to close the signups first.`); } const [options, roles] = Utils.splitFirst(target, '\n'); if (!options || !roles) return this.parse('/help mafia idea'); const [choicesStr, ...picks] = options.split(',').map(x => x.trim()); const choices = parseInt(choicesStr); if (!choices || choices <= picks.length) return this.errorReply(`You need to have more choices than picks.`); if (picks.some((value, index, arr) => arr.indexOf(value, index + 1) > 0)) { return this.errorReply(`Your picks must be unique.`); } game.customIdeaInit(user, choices, picks, roles); }, customideahelp: [ `/mafia customidea choices, picks (new line here, shift+enter)`, `(comma or newline separated rolelist) - Starts an IDEA module with custom roles. Requires % @ # &`, `choices refers to the number of roles you get to pick from. In GI, this is 2, in GestI, this is 3.`, `picks refers to what you choose. In GI, this should be 'role', in GestI, this should be 'role, alignment'`, ], ideapick(target, room, user) { room = this.requireRoom(); const args = target.split(','); const game = this.requireGame(Mafia); if (!(user.id in game.playerTable)) { return user.sendTo(room, '|error|You are not a player in the game.'); } if (game.phase !== 'IDEApicking') { return this.errorReply(`The game is not in the IDEA picking phase.`); } game.ideaPick(user, args); }, ideareroll(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); game.ideaDistributeRoles(user); game.logAction(user, `rerolled an IDEA`); }, idearerollhelp: [`/mafia ideareroll - rerolls the roles for the current IDEA module. Requires host % @ # &`], discards: 'ideadiscards', ideadiscards(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (!game.IDEA.data) return this.errorReply(`There is no IDEA module in the mafia game.`); if (target) { if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (this.meansNo(target)) { if (game.IDEA.discardsHidden) return this.errorReply(`IDEA discards are already hidden.`); game.IDEA.discardsHidden = true; } else if (this.meansYes(target)) { if (!game.IDEA.discardsHidden) return this.errorReply(`IDEA discards are already visible.`); game.IDEA.discardsHidden = false; } else { return this.parse('/help mafia ideadiscards'); } game.logAction(user, `${game.IDEA.discardsHidden ? 'hid' : 'unhid'} IDEA discards`); return this.sendReply(`IDEA discards are now ${game.IDEA.discardsHidden ? 'hidden' : 'visible'}.`); } if (game.IDEA.discardsHidden) return this.errorReply(`Discards are not visible.`); if (!game.IDEA.discardsHTML) return this.errorReply(`The IDEA module does not have finalised discards yet.`); if (!this.runBroadcast()) return; this.sendReplyBox(`<details><summary>IDEA discards:</summary>${game.IDEA.discardsHTML}</details>`); }, ideadiscardshelp: [ `/mafia ideadiscards - shows the discarded roles`, `/mafia ideadiscards off - hides discards from the players. Requires host % @ # &`, `/mafia ideadiscards on - shows discards to the players. Requires host % @ # &`, ], nightstart: 'start', start(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (target) { this.parse(`/mafia close`); this.parse(`/mafia setroles ${target}`); this.parse(`/mafia ${cmd}`); return; } game.start(user, cmd === 'nightstart'); game.logAction(user, `started the game`); }, starthelp: [`/mafia start - Start the game of mafia. Signups must be closed. Requires host % @ # &`], extend: 'day', night: 'day', day(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (cmd === 'night') { game.night(); } else { let extension = parseInt(toID(target)); if (isNaN(extension)) { extension = 0; } else { if (extension < 1) extension = 1; if (extension > 10) extension = 10; } game.day(cmd === 'extend' ? extension : null); } game.logAction(user, `set day/night`); }, dayhelp: [ `/mafia day - Move to the next game day. Requires host % @ # &`, `/mafia night - Move to the next game night. Requires host % @ # &`, `/mafia extend (minutes) - Return to the previous game day. If (minutes) is provided, set the deadline for (minutes) minutes. Requires host % @ # &`, ], v: 'lynch', vote: 'lynch', l: 'lynch', lynch(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkChat(null, room); if (!(user.id in game.playerTable) && (!(user.id in game.dead) || !game.dead[user.id].restless)) { return this.errorReply(`You are not in the game of ${game.title}.`); } game.lynch(user.id, toID(target)); }, lynchhelp: [`/mafia vote [player|novote] - Vote the specified player or abstain from voting.`], uv: 'unlynch', unv: 'unlynch', unvote: 'unlynch', ul: 'unlynch', unl: 'unlynch', unnolynch: 'unlynch', unlynch(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkChat(null, room); if (!(user.id in game.playerTable) && (!(user.id in game.dead) || !game.dead[user.id].restless)) { return this.errorReply(`You are not in the game of ${game.title}.`); } game.unlynch(user.id); }, unlynchhelp: [`/mafia unvote - Withdraw your vote. Fails if you're not voting anyone`], nv: 'nolynch', novote: 'nolynch', nl: 'nolynch', nolynch() { this.parse('/mafia lynch nolynch'); }, enableself: 'selflynch', selfvote: 'selflynch', selflynch(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const action = toID(target); if (!action) return this.parse(`/help mafia selflynch`); if (this.meansYes(action)) { game.setSelfLynch(user, true); } else if (this.meansNo(action)) { game.setSelfLynch(user, false); } else if (action === 'hammer') { game.setSelfLynch(user, 'hammer'); } else { return this.parse(`/help mafia selflynch`); } game.logAction(user, `changed selfvote`); }, selflynchhelp: [ `/mafia selfvote [on|hammer|off] - Allows players to self vote themselves either at hammer or anytime. Requires host % @ # &`, ], treestump: 'kill', spirit: 'kill', spiritstump: 'kill', kick: 'kill', kill(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (game.phase === 'IDEApicking') { return this.errorReply(`You cannot add or remove players while IDEA roles are being picked.`); // needs to be here since eliminate doesn't pass the user } if (!target) return this.parse('/help mafia kill'); const player = game.playerTable[toID(target)]; if (player) { game.eliminate(player, cmd); game.logAction(user, `killed ${player.name}`); } else { this.errorReply(`${target.trim()} is not a living player.`); } }, killhelp: [ `/mafia kill [player] - Kill a player, eliminating them from the game. Requires host % @ # &`, `/mafia treestump [player] - Kills a player, but allows them to talk during the day still.`, `/mafia spirit [player] - Kills a player, but allows them to vote still.`, `/mafia spiritstump [player] Kills a player, but allows them to talk and vote during the day.`, ], revealas: 'revealrole', revealrole(target, room, user, connection, cmd) { const args = target.split(','); room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); let revealAs = ''; let revealedRole = null; if (cmd === 'revealas') { if (!args[0]) { return this.parse('/help mafia revealas'); } else { revealedRole = Mafia.parseRole(args.pop()!); const color = MafiaData.alignments[revealedRole.role.alignment].color; revealAs = `<span style="font-weight:bold;color:${color}">${revealedRole.role.safeName}</span>`; } } if (!args[0]) return this.parse('/help mafia revealas'); for (const targetUsername of args) { let player = game.playerTable[toID(targetUsername)]; if (!player) player = game.dead[toID(targetUsername)]; if (player) { game.revealRole(user, player, `${cmd === 'revealas' ? revealAs : player.getRole()}`); game.logAction(user, `revealed ${player.name}`); if (cmd === 'revealas') { game.secretLogAction(user, `fakerevealed ${player.name} as ${revealedRole!.role.name}`); } } else { this.errorReply(`${targetUsername} is not a player.`); } } }, revealrolehelp: [ `/mafia revealrole [player] - Reveals the role of a player. Requires host % @ # &`, `/mafia revealas [player], [role] - Fakereveals the role of a player as a certain role. Requires host % @ # &`, ], unidle: 'idle', unaction: 'idle', noresponse: 'idle', action: 'idle', idle(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); const player = game.playerTable[user.id]; if (!player) return this.errorReply(`You are not in the game of ${game.title}.`); if (game.phase !== 'night') return this.errorReply(`You can only submit an action or idle during the night phase.`); if (!game.takeIdles) { return this.errorReply(`The host is not accepting idles through the script. Send your action or idle to the host.`); } switch (cmd) { case 'idle': player.idle = true; user.sendTo(room, `You have idled.`); break; case 'action': player.idle = false; if (target) { this.errorReply(`'/mafia action' should be sent alone, not followed by your action or target. Please PM your exact action to the host.`); } else { user.sendTo(room, `You have decided to use an action. DM the host your action.`); } break; case 'noresponse': case 'unidle': case 'unaction': player.idle = null; user.sendTo(room, `You are no longer submitting an action or idle.`); break; } player.updateHtmlRoom(); }, actionhelp: 'idlehelp', idlehelp: [`/mafia [action|idle] - Tells the host if you are using an action or idling.`], forceadd: 'revive', add: 'revive', revive(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!toID(target)) return this.parse('/help mafia revive'); let didSomething = false; if (game.revive(user, toID(target), cmd === 'forceadd')) { didSomething = true; } if (didSomething) game.logAction(user, `added players`); }, revivehelp: [ `/mafia revive [player] - Revive a player who died or add a new player to the game. Requires host % @ # &`, ], dl: 'deadline', deadline(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); target = toID(target); if (target && game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (target === 'off') { game.setDeadline(0); } else { const num = parseInt(target); if (isNaN(num)) { // hack to let hosts broadcast if (game.hostid === user.id || game.cohostids.includes(user.id)) { this.broadcastMessage = this.message.toLowerCase().replace(/[^a-z0-9\s!,]/g, ''); } if (!this.runBroadcast()) return false; if ((game.dlAt - Date.now()) > 0) { return this.sendReply(`|raw|<strong>The deadline is in ${Chat.toDurationString(game.dlAt - Date.now()) || '0 seconds'}.</strong>`); } else { return this.parse(`/help mafia deadline`); } } if (num < 1 || num > 20) return this.errorReply(`The deadline must be between 1 and 20 minutes.`); game.setDeadline(num); } game.logAction(user, `changed deadline`); }, deadlinehelp: [ `/mafia deadline [minutes|off] - Sets or removes the deadline for the game. Cannot be more than 20 minutes.`, ], applyvotemodifier: 'applyhammermodifier', applylynchmodifier: 'applyhammermodifier', applyhammermodifier(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); const [player, mod] = target.split(','); if (cmd === 'applyhammermodifier') { game.applyHammerModifier(user, toID(player), parseInt(mod)); game.secretLogAction(user, `changed a hammer modifier`); } else { game.applyLynchModifier(user, toID(player), parseInt(mod)); game.secretLogAction(user, `changed a vote modifier`); } }, clearvotemodifiers: 'clearhammermodifiers', clearlynchmodifiers: 'clearhammermodifiers', clearhammermodifiers(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); if (cmd === 'clearhammermodifiers') { game.clearHammerModifiers(user); game.secretLogAction(user, `cleared hammer modifiers`); } else { game.clearLynchModifiers(user); game.secretLogAction(user, `cleared vote modifiers`); } }, hate: 'love', unhate: 'love', unlove: 'love', removehammermodifier: 'love', love(target, room, user, connection, cmd) { let mod; switch (cmd) { case 'hate': mod = -1; break; case 'love': mod = 1; break; case 'unhate': case 'unlove': case 'removehammermodifier': mod = 0; break; } this.parse(`/mafia applyhammermodifier ${target}, ${mod}`); }, doublevoter: 'mayor', voteless: 'mayor', unvoteless: 'mayor', unmayor: 'mayor', removevotemodifier: 'mayor', removelynchmodifier: 'mayor', mayor(target, room, user, connection, cmd) { let mod; switch (cmd) { case 'doublevoter': case 'mayor': mod = 2; break; case 'voteless': mod = 0; break; case 'unvoteless': case 'unmayor': case 'removelynchmodifier': case 'removevotemodifier': mod = 1; break; } this.parse(`/mafia applylynchmodifier ${target}, ${mod}`); }, unsilence: 'silence', silence(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); target = toID(target); const targetPlayer = game.playerTable[target] || game.dead[target]; const silence = cmd === 'silence'; if (!targetPlayer) return this.errorReply(`${target} is not in the game of mafia.`); if (silence === targetPlayer.silenced) { return this.errorReply(`${targetPlayer.name} is already ${!silence ? 'not' : ''} silenced.`); } targetPlayer.silenced = silence; this.sendReply(`${targetPlayer.name} has been ${!silence ? 'un' : ''}silenced.`); game.logAction(user, `${!silence ? 'un' : ''}silenced a player`); }, silencehelp: [ `/mafia silence [player] - Silences [player], preventing them from talking at all. Requires host % @ # &`, `/mafia unsilence [player] - Removes a silence on [player], allowing them to talk again. Requires host % @ # &`, ], insomniac: 'nighttalk', uninsomniac: 'nighttalk', unnighttalk: 'nighttalk', nighttalk(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); target = toID(target); const targetPlayer = game.playerTable[target] || game.dead[target]; const nighttalk = !cmd.startsWith('un'); if (!targetPlayer) return this.errorReply(`${target} is not in the game of mafia.`); if (nighttalk === targetPlayer.nighttalk) { return this.errorReply(`${targetPlayer.name} is already ${!nighttalk ? 'not' : ''} able to talk during the night.`); } targetPlayer.nighttalk = nighttalk; this.sendReply(`${targetPlayer.name} can ${!nighttalk ? 'no longer' : 'now'} talk during the night.`); game.logAction(user, `${!nighttalk ? 'un' : ''}insomniacd a player`); }, nighttalkhelp: [ `/mafia nighttalk [player] - Makes [player] an insomniac, allowing them to talk freely during the night. Requires host % @ # &`, `/mafia unnighttalk [player] - Removes [player] as an insomniac, preventing them from talking during the night. Requires host % @ # &`, ], actor: 'priest', unactor: 'priest', unpriest: 'priest', priest(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); target = toID(target); const targetPlayer = game.playerTable[target] || game.dead[target]; if (!targetPlayer) return this.errorReply(`${target} is not in the game of mafia.`); const actor = cmd.endsWith('actor'); const remove = cmd.startsWith('un'); if (remove) { if (targetPlayer.hammerRestriction === null) { return this.errorReply(`${targetPlayer.name} already has no voting restrictions.`); } if (actor !== targetPlayer.hammerRestriction) { return this.errorReply(`${targetPlayer.name} is ${targetPlayer.hammerRestriction ? 'an actor' : 'a priest'}.`); } targetPlayer.hammerRestriction = null; return this.sendReply(`${targetPlayer}'s hammer restriction was removed.`); } if (actor === targetPlayer.hammerRestriction) { return this.errorReply(`${targetPlayer.name} is already ${targetPlayer.hammerRestriction ? 'an actor' : 'a priest'}.`); } targetPlayer.hammerRestriction = actor; this.sendReply(`${targetPlayer.name} is now ${targetPlayer.hammerRestriction ? "an actor (can only hammer)" : "a priest (can't hammer)"}.`); if (actor) { // target is an actor, remove their lynch because it's now impossible game.unlynch(targetPlayer.id, true); } game.logAction(user, `made a player actor/priest`); }, priesthelp: [ `/mafia (un)priest [player] - Makes [player] a priest, preventing them from placing the hammer vote. Requires host % @ # &`, `/mafia (un)actor [player] - Makes [player] an actor, preventing them from placing non-hammer votes. Requires host % @ # &`, ], shifthammer: 'hammer', resethammer: 'hammer', hammer(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (!game.started) return this.errorReply(`The game has not started yet.`); const hammer = parseInt(target); if (toID(cmd) !== `resethammer` && ((isNaN(hammer) && !this.meansNo(target)) || hammer < 1)) { return this.errorReply(`${target} is not a valid hammer count.`); } switch (cmd.toLowerCase()) { case 'shifthammer': game.shiftHammer(hammer); break; case 'hammer': game.setHammer(hammer); break; default: game.resetHammer(); break; } game.logAction(user, `changed the hammer`); }, hammerhelp: [ `/mafia hammer [hammer] - sets the hammer count to [hammer] and resets votes`, `/mafia hammer off - disables hammering`, `/mafia shifthammer [hammer] - sets the hammer count to [hammer] without resetting votes`, `/mafia resethammer - sets the hammer to the default, resetting votes`, ], enablenv: 'enablenl', disablenv: 'enablenl', disablenl: 'enablenl', enablenl(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (cmd === 'enablenl' || cmd === 'enablenv') { game.setNoLynch(user, true); } else { game.setNoLynch(user, false); } game.logAction(user, `changed novote status`); }, enablenlhelp: [ `/mafia [enablenv|disablenv] - Allows or disallows players abstain from voting. Requires host % @ # &`, ], forcevote: 'forcelynch', forcelynch(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); target = toID(target); if (this.meansYes(target)) { if (game.forceLynch) return this.errorReply(`Forcevoting is already enabled.`); game.forceLynch = true; if (game.started) game.resetHammer(); game.sendDeclare(`Forcevoting has been enabled. Your vote will start on yourself, and you cannot unvote!`); } else if (this.meansNo(target)) { if (!game.forceLynch) return this.errorReply(`Forcevoting is already disabled.`); game.forceLynch = false; game.sendDeclare(`Forcevoting has been disabled. You can vote normally now!`); } else { this.parse('/help mafia forcevote'); } game.logAction(user, `changed forcevote status`); }, forcelynchhelp: [ `/mafia forcevote [yes/no] - Forces players' votes onto themselves, and prevents unvoting. Requires host % @ # &`, ], votes: 'lynches', lynches(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (!game.started) return this.errorReply(`The game of mafia has not started yet.`); // hack to let hosts broadcast if (game.hostid === user.id || game.cohostids.includes(user.id)) { this.broadcastMessage = this.message.toLowerCase().replace(/[^a-z0-9\s!,]/g, ''); } if (!this.runBroadcast()) return false; this.sendReplyBox(game.lynchBox()); }, pl: 'players', players(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); // hack to let hosts broadcast if (game.hostid === user.id || game.cohostids.includes(user.id)) { this.broadcastMessage = this.message.toLowerCase().replace(/[^a-z0-9\s!,]/g, ''); } if (!this.runBroadcast()) return false; if (this.broadcasting) { game.sendPlayerList(); } else { this.sendReplyBox(`Players (${game.playerCount}): ${Object.values(game.playerTable).map(p => p.safeName).sort().join(', ')}`); } }, originalrolelist: 'rolelist', orl: 'rolelist', rl: 'rolelist', rolelist(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.closedSetup) return this.errorReply(`You cannot show roles in a closed setup.`); if (!this.runBroadcast()) return false; if (game.IDEA.data) { const buf = `<details><summary>IDEA roles:</summary>${game.IDEA.data.roles.join(`<br />`)}</details>`; return this.sendReplyBox(buf); } const showOrl = (['orl', 'originalrolelist'].includes(cmd) || game.noReveal); const roleString = Utils.sortBy((showOrl ? game.originalRoles : game.roles), role => ( role.alignment )).map(role => role.safeName).join(', '); this.sendReplyBox(`${showOrl ? `Original Rolelist: ` : `Rolelist: `}${roleString}`); }, playerroles(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) { return this.errorReply(`Only the host can view roles.`); } if (!game.started) return this.errorReply(`The game has not started.`); const players = [...Object.values(game.playerTable), ...Object.values(game.dead)]; this.sendReplyBox(players.map( p => `${p.safeName}: ${p.role ? (p.role.alignment === 'solo' ? 'Solo ' : '') + p.role.safeName : 'No role'}` ).join('<br/>')); }, spectate: 'view', view(target, room, user, connection) { room = this.requireRoom(); this.requireGame(Mafia); if (!this.runBroadcast()) return; if (this.broadcasting) { return this.sendReplyBox(`<button name="joinRoom" value="view-mafia-${room.roomid}" class="button"><strong>Spectate the game</strong></button>`); } return this.parse(`/join view-mafia-${room.roomid}`); }, refreshlynches(target, room, user, connection) { room = this.requireRoom(); const game = this.requireGame(Mafia); const lynches = game.lynchBoxFor(user.id); user.send(`>view-mafia-${game.room.roomid}\n|selectorhtml|#mafia-lynches|` + lynches); }, forcesub: 'sub', sub(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); const args = target.split(','); const action = toID(args.shift()); switch (action) { case 'in': if (user.id in game.playerTable) { // Check if they have requested to be subbed out. if (!game.requestedSub.includes(user.id)) { return this.errorReply(`You have not requested to be subbed out.`); } game.requestedSub.splice(game.requestedSub.indexOf(user.id), 1); this.errorReply(`You have cancelled your request to sub out.`); game.playerTable[user.id].updateHtmlRoom(); } else { this.checkChat(null, room); if (game.subs.includes(user.id)) return this.errorReply(`You are already on the sub list.`); if (game.played.includes(user.id)) return this.errorReply(`You cannot sub back into the game.`); game.canJoin(user, true); game.subs.push(user.id); game.nextSub(); // Update spectator's view this.parse(`/join view-mafia-${room.roomid}`); } break; case 'out': if (user.id in game.playerTable) { if (game.requestedSub.includes(user.id)) { return this.errorReply(`You have already requested to be subbed out.`); } game.requestedSub.push(user.id); game.playerTable[user.id].updateHtmlRoom(); game.nextSub(); } else { if (game.hostid === user.id || game.cohostids.includes(user.id)) { return this.errorReply(`The host cannot sub out of the game.`); } if (!game.subs.includes(user.id)) return this.errorReply(`You are not on the sub list.`); game.subs.splice(game.subs.indexOf(user.id), 1); // Update spectator's view this.parse(`/join view-mafia-${room.roomid}`); } break; case 'next': if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const toSub = args.shift(); if (!(toID(toSub) in game.playerTable)) return this.errorReply(`${toSub} is not in the game.`); if (!game.subs.length) { if (game.hostRequestedSub.includes(toID(toSub))) { return this.errorReply(`${toSub} is already on the list to be subbed out.`); } user.sendTo( room, `|error|There are no subs to replace ${toSub}, they will be subbed if a sub is available before they speak next.` ); game.hostRequestedSub.unshift(toID(toSub)); } else { game.nextSub(toID(toSub)); } game.logAction(user, `requested a sub for a player`); break; case 'remove': if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); for (const toRemove of args) { const toRemoveIndex = game.subs.indexOf(toID(toRemove)); if (toRemoveIndex === -1) { user.sendTo(room, `|error|${toRemove} is not on the sub list.`); continue; } game.subs.splice(toRemoveIndex, 1); user.sendTo(room, `${toRemove} has been removed from the sublist`); game.logAction(user, `removed a player from the sublist`); } break; case 'unrequest': if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const toUnrequest = toID(args.shift()); const userIndex = game.requestedSub.indexOf(toUnrequest); const hostIndex = game.hostRequestedSub.indexOf(toUnrequest); if (userIndex < 0 && hostIndex < 0) return user.sendTo(room, `|error|${toUnrequest} is not requesting a sub.`); if (userIndex > -1) { game.requestedSub.splice(userIndex, 1); user.sendTo(room, `${toUnrequest}'s sub request has been removed.`); } if (hostIndex > -1) { game.hostRequestedSub.splice(userIndex, 1); user.sendTo(room, `${toUnrequest} has been removed from the host sublist.`); } break; default: if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); const toSubOut = action; const toSubIn = toID(args.shift()); if (!(toSubOut in game.playerTable)) return this.errorReply(`${toSubOut} is not in the game.`); const targetUser = Users.get(toSubIn); if (!targetUser) return this.errorReply(`The user "${toSubIn}" was not found.`); game.canJoin(targetUser, false, cmd === 'forcesub'); if (game.subs.includes(targetUser.id)) { game.subs.splice(game.subs.indexOf(targetUser.id), 1); } if (game.hostRequestedSub.includes(toSubOut)) { game.hostRequestedSub.splice(game.hostRequestedSub.indexOf(toSubOut), 1); } if (game.requestedSub.includes(toSubOut)) { game.requestedSub.splice(game.requestedSub.indexOf(toSubOut), 1); } game.sub(toSubOut, toSubIn); game.logAction(user, `substituted a player`); } }, subhelp: [ `/mafia sub in - Request to sub into the game, or cancel a request to sub out.`, `/mafia sub out - Request to sub out of the game, or cancel a request to sub in.`, `/mafia sub next, [player] - Forcibly sub [player] out of the game. Requires host % @ # &`, `/mafia sub remove, [user] - Remove [user] from the sublist. Requres host % @ # &`, `/mafia sub unrequest, [player] - Remove's a player's request to sub out of the game. Requires host % @ # &`, `/mafia sub [player], [user] - Forcibly sub [player] for [user]. Requires host % @ # &`, ], autosub(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('mute', null, room); if (this.meansYes(toID(target))) { if (game.autoSub) return this.errorReply(`Automatic subbing of players is already enabled.`); game.autoSub = true; user.sendTo(room, `Automatic subbing of players has been enabled.`); game.nextSub(); } else if (this.meansNo(toID(target))) { if (!game.autoSub) return this.errorReply(`Automatic subbing of players is already disabled.`); game.autoSub = false; user.sendTo(room, `Automatic subbing of players has been disabled.`); } else { return this.parse(`/help mafia autosub`); } game.logAction(user, `changed autosub status`); }, autosubhelp: [ `/mafia autosub [yes|no] - Sets if players will automatically sub out if a user is on the sublist. Requires host % @ # &`, ], cohost: 'subhost', forcecohost: 'subhost', forcesubhost: 'subhost', subhost(target, room, user, connection, cmd) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkChat(); if (!target) return this.parse(`/help mafia ${cmd}`); this.checkCan('mute', null, room); const {targetUser} = this.requireUser(target); if (!room.users[targetUser.id]) return this.errorReply(`${targetUser.name} is not in this room, and cannot be hosted.`); if (game.hostid === targetUser.id) return this.errorReply(`${targetUser.name} is already the host.`); if (game.cohostids.includes(targetUser.id)) return this.errorReply(`${targetUser.name} is already a cohost.`); if (targetUser.id in game.playerTable) return this.errorReply(`The host cannot be ingame.`); if (targetUser.id in game.dead) { if (!cmd.includes('force')) { return this.errorReply(`${targetUser.name} could potentially be revived. To continue anyway, use /mafia force${cmd} ${target}.`); } if (game.dead[targetUser.id].lynching) game.unlynch(targetUser.id); game.dead[targetUser.id].destroy(); delete game.dead[targetUser.id]; } if (cmd.includes('cohost')) { game.cohostids.push(targetUser.id); game.cohosts.push(Utils.escapeHTML(targetUser.name)); game.sendDeclare(Utils.html`${targetUser.name} has been added as a cohost by ${user.name}`); for (const conn of targetUser.connections) { void Chat.resolvePage(`view-mafia-${room.roomid}`, targetUser, conn); } this.modlog('MAFIACOHOST', targetUser, null, {noalts: true, noip: true}); } else { const oldHostid = game.hostid; const oldHost = Users.get(game.hostid); if (oldHost) oldHost.send(`>view-mafia-${room.roomid}\n|deinit`); if (game.subs.includes(targetUser.id)) game.subs.splice(game.subs.indexOf(targetUser.id), 1); const queueIndex = hostQueue.indexOf(targetUser.id); if (queueIndex > -1) hostQueue.splice(queueIndex, 1); game.host = Utils.escapeHTML(targetUser.name); game.hostid = targetUser.id; game.played.push(targetUser.id); for (const conn of targetUser.connections) { void Chat.resolvePage(`view-mafia-${room.roomid}`, targetUser, conn); } game.sendDeclare(Utils.html`${targetUser.name} has been substituted as the new host, replacing ${oldHostid}.`); this.modlog('MAFIASUBHOST', targetUser, `replacing ${oldHostid}`, {noalts: true, noip: true}); } }, subhosthelp: [`/mafia subhost [user] - Substitues the user as the new game host.`], cohosthelp: [ `/mafia cohost [user] - Adds the user as a cohost. Cohosts can talk during the game, as well as perform host actions.`, ], uncohost: 'removecohost', removecohost(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); this.checkChat(); if (!target) return this.parse('/help mafia subhost'); this.checkCan('mute', null, room); const targetID = toID(target); const cohostIndex = game.cohostids.indexOf(targetID); if (cohostIndex < 0) { if (game.hostid === targetID) { return this.errorReply(`${target} is the host, not a cohost. Use /mafia subhost to replace them.`); } return this.errorReply(`${target} is not a cohost.`); } game.cohostids.splice(cohostIndex, 1); game.sendDeclare(Utils.html`${target} was removed as a cohost by ${user.name}`); this.modlog('MAFIAUNCOHOST', target, null, {noalts: true, noip: true}); }, end(target, room, user) { room = this.requireRoom(); const game = this.requireGame(Mafia); if (game.hostid !== user.id && !game.cohostids.includes(user.id)) this.checkCan('show', null, room); game.end(); this.modlog('MAFIAEND', null); }, endhelp: [`/mafia end - End the current game of mafia. Requires host + % @ # &`], role: 'data', alignment: 'data', theme: 'data', term: 'data', dt: 'data', data(target, room, user, connection, cmd) { if (room?.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); if (cmd === 'role' && !target && room) { // Support /mafia role showing your current role if you're in a game const game = room.getGame(Mafia); if (!game) { return this.errorReply(`There is no game of mafia running in this room. If you meant to display information about a role, use /mafia role [role name]`); } if (!(user.id in game.playerTable)) return this.errorReply(`You are not in the game of ${game.title}.`); const role = game.playerTable[user.id].role; if (!role) return this.errorReply(`You do not have a role yet.`); return this.sendReplyBox(`Your role is: ${role.safeName}`); } // hack to let hosts broadcast const game = room?.getGame(Mafia); if (game && (game.hostid === user.id || game.cohostids.includes(user.id))) { this.broadcastMessage = this.message.toLowerCase().replace(/[^a-z0-9\s!,]/g, ''); } if (!this.runBroadcast()) return false; if (!target) return this.parse(`/help mafia data`); target = toID(target); if (target in MafiaData.aliases) target = MafiaData.aliases[target]; let result: MafiaDataAlignment | MafiaDataRole | MafiaDataTheme | MafiaDataIDEA | MafiaDataTerm | null = null; let dataType = cmd; const cmdTypes: {[k: string]: keyof MafiaData} = { role: 'roles', alignment: 'alignments', theme: 'themes', term: 'terms', idea: 'IDEAs', }; if (cmd in cmdTypes) { const toSearch = MafiaData[cmdTypes[cmd]]; // @ts-ignore guaranteed not an alias result = toSearch[target]; } else { // search everything for (const [cmdType, dataKey] of Object.entries(cmdTypes)) { if (target in MafiaData[dataKey]) { // @ts-ignore guaranteed not an alias result = MafiaData[dataKey][target]; dataType = cmdType; break; } } } if (!result) return this.errorReply(`"${target}" is not a valid mafia alignment, role, theme, or IDEA.`); // @ts-ignore let buf = `<h3${result.color ? ' style="color: ' + result.color + '"' : ``}>${result.name}</h3><b>Type</b>: ${dataType}<br/>`; if (dataType === 'theme') { if ((result as MafiaDataTheme).desc) { buf += `<b>Description</b>: ${(result as MafiaDataTheme).desc}<br/><details><summary class="button" style="font-weight: bold; display: inline-block">Setups:</summary>`; } for (const i in result) { const num = parseInt(i); if (isNaN(num)) continue; buf += `${i}: `; const count: {[k: string]: number} = {}; const roles = []; for (const role of (result as MafiaDataTheme)[num].split(',').map((x: string) => x.trim())) { count[role] = count[role] ? count[role] + 1 : 1; } for (const role in count) { roles.push(count[role] > 1 ? `${count[role]}x ${role}` : role); } buf += `${roles.join(', ')}<br/>`; } } else if (dataType === 'idea') { if ((result as MafiaDataIDEA).picks && (result as MafiaDataIDEA).choices) { buf += `<b>Number of Picks</b>: ${(result as MafiaDataIDEA).picks.length} (${(result as MafiaDataIDEA).picks.join(', ')})<br/>`; buf += `<b>Number of Choices</b>: ${(result as MafiaDataIDEA).choices}<br/>`; } buf += `<details><summary class="button" style="font-weight: bold; display: inline-block">Roles:</summary>`; for (const idearole of (result as MafiaDataIDEA).roles) { buf += `${idearole}<br/>`; } } else { // @ts-ignore if (result.memo) buf += `${result.memo.join('<br/>')}`; } return this.sendReplyBox(buf); }, datahelp: [ `/mafia data [alignment|role|modifier|theme|term] - Get information on a mafia alignment, role, modifier, theme, or term.`, ], winfaction: 'win', unwinfaction: 'win', unwin: 'win', win(target, room, user, connection, cmd) { const isUnwin = cmd.startsWith('unwin'); room = this.requireRoom('mafia' as RoomID); if (!room || room.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); this.checkCan('mute', null, room); const args = target.split(','); let points = parseInt(args[0]); if (isUnwin) { points *= -1; } if (isNaN(points)) { points = 10; if (isUnwin) { points *= -1; } } else { if (points > 100 || points < -100) { return this.errorReply(`You cannot give or take more than 100 points at a time.`); } // shift out the point count args.shift(); } if (!args.length) return this.parse('/help mafia win'); const month = new Date().toLocaleString("en-us", {month: "numeric", year: "numeric"}); if (!logs.leaderboard[month]) logs.leaderboard[month] = {}; let toGiveTo = []; let buf = `${points < 0 ? points * -1 : points} point${Chat.plural(points, 's were', ' was')} ${points <= 0 ? 'taken from ' : 'awarded to '} `; if (cmd === 'winfaction' || cmd === 'unwinfaction') { const game = this.requireGame(Mafia); for (let faction of args) { faction = toID(faction); const inFaction = []; for (const player of [...Object.values(game.playerTable), ...Object.values(game.dead)]) { if (player.role && toID(player.role.alignment) === faction) { toGiveTo.push(player.id); inFaction.push(player.id); } } if (inFaction.length) buf += ` the ${faction} faction: ${inFaction.join(', ')};`; } } else { toGiveTo = args; buf += toGiveTo.join(', '); } if (!toGiveTo.length) return this.parse('/help mafia win'); let gavePoints = false; for (let u of toGiveTo) { u = toID(u); if (!u) continue; if (!gavePoints) gavePoints = true; if (!logs.leaderboard[month][u]) logs.leaderboard[month][u] = 0; logs.leaderboard[month][u] += points; if (logs.leaderboard[month][u] === 0) delete logs.leaderboard[month][u]; } if (!gavePoints) return this.parse('/help mafia win'); writeFile(LOGS_FILE, logs); this.modlog(`MAFIAPOINTS`, null, `${points < 0 ? points * -1 : points} points were ${points < 0 ? 'taken from' : 'awarded to'} ${Chat.toListString(toGiveTo)}`); room.add(buf).update(); }, winhelp: [ `/mafia (un)win (points), [user1], [user2], [user3], ... - Award the specified users points to the mafia leaderboard for this month. The amount of points can be negative to take points. Defaults to 10 points.`, `/mafia (un)winfaction (points), [faction] - Award the specified points to all the players in the given faction.`, ], unmvp: 'mvp', mvp(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); if (!room || room.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); this.checkCan('mute', null, room); const args = target.split(','); if (!args.length) return this.parse('/help mafia mvp'); const month = new Date().toLocaleString("en-us", {month: "numeric", year: "numeric"}); if (!logs.mvps[month]) logs.mvps[month] = {}; if (!logs.leaderboard[month]) logs.leaderboard[month] = {}; let gavePoints = false; for (let u of args) { u = toID(u); if (!u) continue; if (!gavePoints) gavePoints = true; if (!logs.leaderboard[month][u]) logs.leaderboard[month][u] = 0; if (!logs.mvps[month][u]) logs.mvps[month][u] = 0; if (cmd === 'unmvp') { logs.mvps[month][u]--; logs.leaderboard[month][u] -= 10; if (logs.mvps[month][u] === 0) delete logs.mvps[month][u]; if (logs.leaderboard[month][u] === 0) delete logs.leaderboard[month][u]; } else { logs.mvps[month][u]++; logs.leaderboard[month][u] += 10; } } if (!gavePoints) return this.parse('/help mafia mvp'); writeFile(LOGS_FILE, logs); this.modlog(`MAFIA${cmd.toUpperCase()}`, null, `MVP and 10 points were ${cmd === 'unmvp' ? 'taken from' : 'awarded to'} ${Chat.toListString(args)}`); room.add(`MVP and 10 points were ${cmd === 'unmvp' ? 'taken from' : 'awarded to'}: ${Chat.toListString(args)}`).update(); }, mvphelp: [ `/mafia mvp [user1], [user2], ... - Gives a MVP point and 10 leaderboard points to the users specified.`, `/mafia unmvp [user1], [user2], ... - Takes away a MVP point and 10 leaderboard points from the users specified.`, ], hostlogs: 'leaderboard', playlogs: 'leaderboard', leaverlogs: 'leaderboard', mvpladder: 'leaderboard', lb: 'leaderboard', leaderboard(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); if (!room || room.settings.mafiaDisabled) return this.errorReply(`Mafia is disabled for this room.`); if (['hostlogs', 'playlogs', 'leaverlogs'].includes(cmd)) { this.checkCan('mute', null, room); } else { // Deny broadcasting host/playlogs if (!this.runBroadcast()) return; } if (cmd === 'lb') cmd = 'leaderboard'; if (this.broadcasting) { return this.sendReplyBox(`<button name="joinRoom" value="view-mafialadder-${cmd}" class="button"><strong>${cmd}</strong></button>`); } return this.parse(`/join view-mafialadder-${cmd}`); }, leaderboardhelp: [ `/mafia [leaderboard|mvpladder] - View the leaderboard or MVP ladder for the current or last month.`, `/mafia [hostlogs|playlogs|leaverlogs] - View the host, play, or leaver logs for the current or last month. Requires % @ # &`, ], gameban: 'hostban', hostban(target, room, user, connection, cmd) { if (!target) return this.parse('/help mafia hostban'); room = this.requireRoom(); this.checkCan('warn', null, room); const {targetUser, rest} = this.requireUser(target); const [string1, string2] = this.splitOne(rest); let duration, reason; if (parseInt(string1)) { duration = parseInt(string1); reason = string2; } else { duration = parseInt(string2); reason = string1; } if (!duration) duration = 2; if (!reason) reason = ''; if (reason.length > 300) { return this.errorReply("The reason is too long. It cannot exceed 300 characters."); } const userid = toID(targetUser); if (Punishments.hasRoomPunishType(room, userid, `MAFIA${this.cmd.toUpperCase()}`)) { return this.errorReply(`User '${targetUser.name}' is already ${this.cmd}ned in this room.`); } else if (Punishments.hasRoomPunishType(room, userid, `MAFIAGAMEBAN`)) { return this.errorReply(`User '${targetUser.name}' is already gamebanned in this room, which also means they can't host.`); } else if (Punishments.hasRoomPunishType(room, userid, `MAFIAHOSTBAN`)) { user.sendTo(room, `User '${targetUser.name}' is already hostbanned in this room, but they will now be gamebanned.`); this.parse(`/mafia unhostban ${targetUser.name}`); } if (cmd === 'hostban') { Mafia.hostBan(room, targetUser, reason, duration); } else { Mafia.gameBan(room, targetUser, reason, duration); } this.modlog(`MAFIA${cmd.toUpperCase()}`, targetUser, reason); this.privateModAction(`${targetUser.name} was banned from ${cmd === 'hostban' ? 'hosting' : 'playing'} mafia games by ${user.name}.`); }, hostbanhelp: [ `/mafia (un)hostban [user], [reason], [duration] - Ban a user from hosting games for [duration] days. Requires % @ # &`, `/mafia (un)gameban [user], [reason], [duration] - Ban a user from playing games for [duration] days. Requires % @ # &`, ], ban: 'gamebanhelp', banhelp: 'gamebanhelp', gamebanhelp() { this.parse('/mafia hostbanhelp'); }, ungameban: 'unhostban', unhostban(target, room, user, connection, cmd) { if (!target) return this.parse('/help mafia hostban'); room = this.requireRoom(); this.checkCan('warn', null, room); const {targetUser} = this.requireUser(target, {allowOffline: true}); if (!Mafia.isGameBanned(room, targetUser) && cmd === 'ungameban') { return this.errorReply(`User '${targetUser.name}' isn't banned from playing mafia games.`); } else if (!Mafia.isHostBanned(room, targetUser) && cmd === 'unhostban') { return this.errorReply(`User '${targetUser.name}' isn't banned from hosting mafia games.`); } if (cmd === 'unhostban') Mafia.unhostBan(room, targetUser); else Mafia.ungameBan(room, targetUser); this.privateModAction(`${targetUser.name} was unbanned from ${cmd === 'unhostban' ? 'hosting' : 'playing'} mafia games by ${user.name}.`); this.modlog(`MAFIA${cmd.toUpperCase()}`, targetUser, null, {noip: 1, noalts: 1}); }, overwriterole: 'addrole', addrole(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const overwrite = cmd === 'overwriterole'; const [name, alignment, image, ...memo] = target.split('|').map(e => e.trim()); const id = toID(name); if (!id || !memo.length) return this.parse(`/help mafia addrole`); if (alignment && !(alignment in MafiaData.alignments)) return this.errorReply(`${alignment} is not a valid alignment.`); if (image && !VALID_IMAGES.includes(image)) return this.errorReply(`${image} is not a valid image.`); if (!overwrite && id in MafiaData.roles) { return this.errorReply(`${name} is already a role. Use /mafia overwriterole to overwrite.`); } if (id in MafiaData.alignments) return this.errorReply(`${name} is already an alignment.`); if (id in MafiaData.aliases) { return this.errorReply(`${name} is already an alias (pointing to ${MafiaData.aliases[id]}).`); } const role: MafiaDataRole = {name, memo}; if (alignment) role.alignment = alignment; if (image) role.image = image; MafiaData.roles[id] = role; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDROLE`, null, id, {noalts: true, noip: true}); this.sendReply(`The role ${id} was added to the database.`); }, addrolehelp: [ `/mafia addrole name|alignment|image|memo1|memo2... - adds a role to the database. Name, memo are required. Requires % @ # &`, ], overwritealignment: 'addalignment', addalignment(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const overwrite = cmd === 'overwritealignment'; const [name, plural, color, buttonColor, image, ...memo] = target.split('|').map(e => e.trim()); const id = toID(name); if (!id || !plural || !memo.length) return this.parse(`/help mafia addalignment`); if (image && !VALID_IMAGES.includes(image)) return this.errorReply(`${image} is not a valid image.`); if (!overwrite && id in MafiaData.alignments) { return this.errorReply(`${name} is already an alignment. Use /mafia overwritealignment to overwrite.`); } if (id in MafiaData.roles) return this.errorReply(`${name} is already a role.`); if (id in MafiaData.aliases) { return this.errorReply(`${name} is already an alias (pointing to ${MafiaData.aliases[id]})`); } const alignment: MafiaDataAlignment = {name, plural, memo}; if (color) alignment.color = color; if (buttonColor) alignment.buttonColor = buttonColor; if (image) alignment.image = image; MafiaData.alignments[id] = alignment; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDALIGNMENT`, null, id, {noalts: true, noip: true}); this.sendReply(`The alignment ${id} was added to the database.`); }, addalignmenthelp: [ `/mafia addalignment name|plural|color|button color|image|memo1|memo2... - adds a memo to the database. Name, plural, memo are required. Requires % @ # &`, ], overwritetheme: 'addtheme', addtheme(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const overwrite = cmd === 'overwritetheme'; const [name, desc, ...rolelists] = target.split('|').map(e => e.trim()); const id = toID(name); if (!id || !desc || !rolelists.length) return this.parse(`/help mafia addtheme`); if (!overwrite && id in MafiaData.themes) { return this.errorReply(`${name} is already a theme. Use /mafia overwritetheme to overwrite.`); } if (id in MafiaData.IDEAs) return this.errorReply(`${name} is already an IDEA.`); if (id in MafiaData.aliases) { return this.errorReply(`${name} is already an alias (pointing to ${MafiaData.aliases[id]})`); } const rolelistsMap: {[players: number]: string} = {}; const uniqueRoles = new Set<string>(); for (const rolelist of rolelists) { const [players, roles] = Utils.splitFirst(rolelist, ':', 2).map(e => e.trim()); const playersNum = parseInt(players); for (const role of roles.split(',')) { uniqueRoles.add(role.trim()); } rolelistsMap[playersNum] = roles; } const problems = []; for (const role of uniqueRoles) { const parsedRole = Mafia.parseRole(role); if (parsedRole.problems.length) problems.push(...parsedRole.problems); } if (problems.length) return this.errorReply(`Problems found when parsing roles:\n${problems.join('\n')}`); const theme: MafiaDataTheme = {name, desc, ...rolelistsMap}; MafiaData.themes[id] = theme; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDTHEME`, null, id, {noalts: true, noip: true}); this.sendReply(`The theme ${id} was added to the database.`); }, addthemehelp: [ `/mafia addtheme name|description|players:rolelist|players:rolelist... - adds a theme to the database. Requires % @ # &`, ], overwriteidea: 'addidea', addidea(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const overwrite = cmd === 'overwriteidea'; let [meta, ...roles] = target.split('\n'); roles = roles.map(e => e.trim()); if (!meta || !roles.length) return this.parse(`/help mafia addidea`); const [name, choicesStr, ...picks] = meta.split('|'); const id = toID(name); const choices = parseInt(choicesStr); if (!id || !choices || !picks.length) return this.parse(`/help mafia addidea`); if (choices <= picks.length) return this.errorReply(`You need to have more choices than picks.`); if (!overwrite && id in MafiaData.IDEAs) { return this.errorReply(`${name} is already an IDEA. Use /mafia overwriteidea to overwrite.`); } if (id in MafiaData.themes) return this.errorReply(`${name} is already a theme.`); if (id in MafiaData.aliases) { return this.errorReply(`${name} is already an alias (pointing to ${MafiaData.aliases[id]})`); } const checkedRoles: string[] = []; const problems = []; for (const role of roles) { if (checkedRoles.includes(role)) continue; const parsedRole = Mafia.parseRole(role); if (parsedRole.problems.length) problems.push(...parsedRole.problems); checkedRoles.push(role); } if (problems.length) return this.errorReply(`Problems found when parsing roles:\n${problems.join('\n')}`); const IDEA: MafiaDataIDEA = {name, choices, picks, roles}; MafiaData.IDEAs[id] = IDEA; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDIDEA`, null, id, {noalts: true, noip: true}); this.sendReply(`The IDEA ${id} was added to the database.`); }, addideahelp: [ `/mafia addidea name|choices (number)|pick1|pick2... (new line here)`, `(newline separated rolelist) - Adds an IDEA to the database. Requires % @ # &`, ], overwriteterm: 'addterm', addterm(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const overwrite = cmd === 'overwriteterm'; const [name, ...memo] = target.split('|').map(e => e.trim()); const id = toID(name); if (!id || !memo.length) return this.parse(`/help mafia addterm`); if (!overwrite && id in MafiaData.terms) { return this.errorReply(`${name} is already a term. Use /mafia overwriteterm to overwrite.`); } if (id in MafiaData.aliases) { return this.errorReply(`${name} is already an alias (pointing to ${MafiaData.aliases[id]})`); } const term: MafiaDataTerm = {name, memo}; MafiaData.terms[id] = term; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDTERM`, null, id, {noalts: true, noip: true}); this.sendReply(`The term ${id} was added to the database.`); }, addtermhelp: [`/mafia addterm name|memo1|memo2... - Adds a term to the database. Requires % @ # &`], overwritealias: 'addalias', addalias(target, room, user, connection, cmd) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); const [from, to] = target.split(',').map(toID); if (!from || !to) return this.parse(`/help mafia addalias`); if (from in MafiaData.aliases) { return this.errorReply(`${from} is already an alias (pointing to ${MafiaData.aliases[from]})`); } let foundTarget = false; for (const entry of ['alignments', 'roles', 'themes', 'IDEAs', 'terms'] as (keyof MafiaData)[]) { const dataEntry = MafiaData[entry]; if (from in dataEntry) return this.errorReply(`${from} is already a ${entry.slice(0, -1)}`); if (to in dataEntry) foundTarget = true; } if (!foundTarget) return this.errorReply(`No database entry exists with the key ${to}.`); MafiaData.aliases[from] = to; writeFile(DATA_FILE, MafiaData); this.modlog(`MAFIAADDALIAS`, null, `${from}: ${to}`, {noalts: true, noip: true}); this.sendReply(`The alias ${from} was added, pointing to ${to}.`); }, addaliashelp: [ `/mafia addalias from,to - Adds an alias to the database, redirecting (from) to (to). Requires % @ # &`, ], deletedata(target, room, user) { room = this.requireRoom('mafia' as RoomID); this.checkCan('mute', null, room); let [source, entry] = target.split(','); entry = toID(entry); if (!(source in MafiaData)) { return this.errorReply(`Invalid source. Valid sources are ${Object.keys(MafiaData).join(', ')}`); } // @ts-ignore checked above const dataSource = MafiaData[source]; if (!(entry in dataSource)) return this.errorReply(`${entry} does not exist in ${source}.`); let buf = ''; if (dataSource === MafiaData.alignments) { if (entry === 'solo' || entry === 'town') return this.errorReply(`You cannot delete the solo or town alignments.`); for (const key in MafiaData.roles) { if (MafiaData.roles[key].alignment === entry) { buf += `Removed alignment of role ${key}.`; delete MafiaData.roles[key].alignment; } } } if (dataSource !== MafiaData.aliases) { // remove any aliases for (const key in MafiaData.aliases) { if (MafiaData.aliases[key] === entry) { buf += `Removed alias ${key}`; delete MafiaData.aliases[key]; } } } delete dataSource[entry]; writeFile(DATA_FILE, MafiaData); if (buf) this.sendReply(buf); this.modlog(`MAFIADELETEDATA`, null, `${entry} from ${source}`, {noalts: true, noip: true}); this.sendReply(`The entry ${entry} was deleted from the ${source} database.`); }, deletedatahelp: [`/mafia deletedata source,entry - Removes an entry from the database. Requires % @ # &`], listdata(target, room, user) { if (!(target in MafiaData)) { return this.errorReply(`Invalid source. Valid sources are ${Object.keys(MafiaData).join(', ')}`); } const dataSource = MafiaData[target as keyof MafiaData]; if (dataSource === MafiaData.aliases) { const aliases = Object.entries(MafiaData.aliases) .map(([from, to]) => `${from}: ${to}`) .join('<br/>'); return this.sendReplyBox(`Mafia aliases:<br/>${aliases}`); } else { const entries = Object.entries(dataSource) .map(([key, data]) => `<button class="button" name="send" value="/mafia dt ${key}">${data.name}</button>`) .join(''); return this.sendReplyBox(`Mafia ${target}:<br/>${entries}`); } }, disable(target, room, user) { room = this.requireRoom(); this.checkCan('gamemanagement', null, room); if (room.settings.mafiaDisabled) { return this.errorReply("Mafia is already disabled."); } room.settings.mafiaDisabled = true; room.saveSettings(); this.modlog('MAFIADISABLE', null); return this.sendReply("Mafia has been disabled for this room."); }, disablehelp: [`/mafia disable - Disables mafia in this room. Requires # &`], enable(target, room, user) { room = this.requireRoom(); this.checkCan('gamemanagement', null, room); if (!room.settings.mafiaDisabled) { return this.errorReply("Mafia is already enabled."); } room.settings.mafiaDisabled = false; room.saveSettings(); this.modlog('MAFIAENABLE', null); return this.sendReply("Mafia has been enabled for this room."); }, enablehelp: [`/mafia enable - Enables mafia in this room. Requires # &`], }, mafiahelp(target, room, user) { if (!this.runBroadcast()) return; let buf = `<strong>Commands for the Mafia Plugin</strong><br/>Most commands are used through buttons in the game screen.<br/><br/>`; buf += `<details><summary class="button">General Commands</summary>`; buf += [ `<br/><strong>General Commands for the Mafia Plugin</strong>:<br/>`, `/mafia host [user] - Create a game of Mafia with [user] as the host. Roomvoices can only host themselves. Requires + % @ # &`, `/mafia nexthost - Host the next user in the host queue. Only works in the Mafia Room. Requires + % @ # &`, `/mafia forcehost [user] - Bypass the host queue and host [user]. Only works in the Mafia Room. Requires % @ # &`, `/mafia sub [in|out] - Request to sub into the game, or cancel a request to sub out.`, `/mafia spectate - Spectate the game of mafia.`, `/mafia votes - Display the current vote count, and who's voting who.`, `/mafia players - Display the current list of players, will highlight players.`, `/mafia [rl|orl] - Display the role list or the original role list for the current game.`, `/mafia data [alignment|role|modifier|theme|term] - Get information on a mafia alignment, role, modifier, theme, or term.`, `/mafia subhost [user] - Substitues the user as the new game host. Requires % @ # &`, `/mafia (un)cohost [user] - Adds/removes the user as a cohost. Cohosts can talk during the game, as well as perform host actions. Requires % @ # &`, `/mafia [enable|disable] - Enables/disables mafia in this room. Requires # &`, ].join('<br/>'); buf += `</details><details><summary class="button">Player Commands</summary>`; buf += [ `<br/><strong>Commands that players can use</strong>:<br/>`, `/mafia [join|leave] - Joins/leaves the game. Can only be done while signups are open.`, `/mafia vote [player|novote] - Vote the specified player or abstain from voting.`, `/mafia unvote - Withdraw your vote. Fails if you're not voting anyone`, `/mafia deadline - View the deadline for the current game.`, `/mafia sub in - Request to sub into the game, or cancel a request to sub out.`, `/mafia sub out - Request to sub out of the game, or cancel a request to sub in.`, `/mafia [action|idle] - Tells the host if you are using an action or idling.`, ].join('<br/>'); buf += `</details><details><summary class="button">Host Commands</summary>`; buf += [ `<br/><strong>Commands for game hosts and Cohosts to use</strong>:<br/>`, `/mafia playercap [cap|none]- Limit the number of players able to join the game. Player cap cannot be more than 20 or less than 2. Requires host % @ # &`, `/mafia close - Closes signups for the current game. Requires host % @ # &`, `/mafia closedsetup [on|off] - Sets if the game is a closed setup. Closed setups don't show the role list to players. Requires host % @ # &`, `/mafia takeidles [on|off] - Sets if idles are accepted by the script or not. Requires host % @ # &`, `/mafia reveal [on|off] - Sets if roles reveal on death or not. Requires host % @ # &`, `/mafia selfvote [on|hammer|off] - Allows players to self vote either at hammer or anytime. Requires host % @ # &`, `/mafia [enablenl|disablenl] - Allows or disallows players abstain from voting. Requires host % @ # &`, `/mafia forcevote [yes/no] - Forces players' votes onto themselves, and prevents unvoting. Requires host % @ # &`, `/mafia setroles [comma seperated roles] - Set the roles for a game of mafia. You need to provide one role per player. Requires host % @ # &`, `/mafia forcesetroles [comma seperated roles] - Forcibly set the roles for a game of mafia. No role PM information or alignment will be set. Requires host % @ # &`, `/mafia start - Start the game of mafia. Signups must be closed. Requires host % @ # &`, `/mafia [day|night] - Move to the next game day or night. Requires host % @ # &`, `/mafia extend (minutes) - Return to the previous game day. If (minutes) is provided, set the deadline for (minutes) minutes. Requires host % @ # &`, `/mafia kill [player] - Kill a player, eliminating them from the game. Requires host % @ # &`, `/mafia treestump [player] - Kills a player, but allows them to talk during the day still. Requires host % @ # &`, `/mafia spirit [player] - Kills a player, but allows them to vote still. Requires host % @ # &`, `/mafia spiritstump [player] - Kills a player, but allows them to talk and vote during the day. Requires host % @ # &`, `/mafia kick [player] - Kicks a player from the game without revealing their role. Requires host % @ # &`, `/mafia revive [player] - Revive a player who died or add a new player to the game. Requires host % @ # &`, `/mafia revealrole [player] - Reveals the role of a player. Requires host % @ # &`, `/mafia revealas [player], [role] - Fakereveals the role of a player as a certain role. Requires host % @ # &`, `/mafia (un)silence [player] - Silences [player], preventing them from talking at all. Requires host % @ # &`, `/mafia (un)nighttalk [player] - Allows [player] to talk freely during the night. Requires host % @ # &`, `/mafia (un)[priest|actor] [player] - Makes [player] a priest (can't hammer) or actor (can only hammer). Requires host % @ # &`, `/mafia deadline [minutes|off] - Sets or removes the deadline for the game. Cannot be more than 20 minutes.`, `/mafia sub next, [player] - Forcibly sub [player] out of the game. Requires host % @ # &`, `/mafia sub remove, [user] - Forcibly remove [user] from the sublist. Requres host % @ # &`, `/mafia sub unrequest, [player] - Remove's a player's request to sub out of the game. Requires host % @ # &`, `/mafia sub [player], [user] - Forcibly sub [player] for [user]. Requires host % @ # &`, `/mafia autosub [yes|no] - Sets if players will automatically sub out if a user is on the sublist. Defaults to yes. Requires host % @ # &`, `/mafia (un)[love|hate] [player] - Makes it take 1 more (love) or less (hate) vote to hammer [player]. Requires host % @ # &`, `/mafia (un)[mayor|voteless] [player] - Makes [player]'s' vote worth 2 votes (mayor) or makes [player]'s vote worth 0 votes (voteless). Requires host % @ # &`, `/mafia hammer [hammer] - sets the hammer count to [hammer] and resets votes`, `/mafia hammer off - disables hammering`, `/mafia shifthammer [hammer] - sets the hammer count to [hammer] without resetting votes`, `/mafia resethammer - sets the hammer to the default, resetting votes`, `/mafia playerroles - View all the player's roles in chat. Requires host`, `/mafia end - End the current game of mafia. Requires host + % @ # &`, ].join('<br/>'); buf += `</details><details><summary class="button">IDEA Module Commands</summary>`; buf += [ `<br/><strong>Commands for using IDEA modules</strong><br/>`, `/mafia idea [idea] - starts the IDEA module [idea]. Requires + % @ # &, voices can only start for themselves`, `/mafia ideareroll - rerolls the IDEA module. Requires host % @ # &`, `/mafia ideapick [selection], [role] - selects a role`, `/mafia ideadiscards - shows the discarded roles`, `/mafia ideadiscards [off|on] - hides discards from the players. Requires host % @ # &`, `/mafia customidea choices, picks (new line here, shift+enter)`, `(comma or newline separated rolelist) - Starts an IDEA module with custom roles. Requires % @ # &`, ].join('<br/>'); buf += `</details>`; buf += `</details><details><summary class="button">Mafia Room Specific Commands</summary>`; buf += [ `<br/><strong>Commands that are only useable in the Mafia Room</strong>:<br/>`, `/mafia queue add, [user] - Adds the user to the host queue. Requires + % @ # &, voices can only add themselves.`, `/mafia queue remove, [user] - Removes the user from the queue. You can remove yourself regardless of rank. Requires % @ # &.`, `/mafia queue - Shows the list of users who are in queue to host.`, `/mafia win (points) [user1], [user2], [user3], ... - Award the specified users points to the mafia leaderboard for this month. The amount of points can be negative to take points. Defaults to 10 points.`, `/mafia winfaction (points), [faction] - Award the specified points to all the players in the given faction. Requires % @ # &`, `/mafia (un)mvp [user1], [user2], ... - Gives a MVP point and 10 leaderboard points to the users specified.`, `/mafia [leaderboard|mvpladder] - View the leaderboard or MVP ladder for the current or last month.`, `/mafia [hostlogs|playlogs] - View the host logs or play logs for the current or last month. Requires % @ # &`, `/mafia (un)hostban [user], [duration] - Ban a user from hosting games for [duration] days. Requires % @ # &`, `/mafia (un)gameban [user], [duration] - Ban a user from playing games for [duration] days. Requires % @ # &`, ].join('<br/>'); buf += `</details>`; return this.sendReplyBox(buf); }, }; export const roomSettings: Chat.SettingsHandler = room => ({ label: "Mafia", permission: 'editroom', options: [ [`disabled`, room.settings.mafiaDisabled || 'mafia disable'], [`enabled`, !room.settings.mafiaDisabled || 'mafia enable'], ], }); process.nextTick(() => { Chat.multiLinePattern.register('/mafia (custom|add|overwrite)idea'); });
mit
yogeshsaroya/new-cdnjs
ajax/libs/rome/0.11.2/rome.min.js
130
version https://git-lfs.github.com/spec/v1 oid sha256:e95cffe2d80d9d889c2129c41bd91a1e5ceff7e804f9c2946b363a81216f0aa8 size 58049
mit
compeoree/QtSDR
QtLogger/data.cpp
11594
/** * \file data.cpp * \brief Code files for the Data functions as part of the QtLogger program * \author David R. Larsen, KV0S * \version 1.0.2 * \date August 21, 2011 */ /* Copyright (C) 2011 - David R. Larsen, KV0S * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * 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, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * */ #include "data.h" Data::Data(QWidget *parent) : QWidget(parent) { model = new QStandardItemModel(); hdr = new QStringList(); } Data::~Data() { delete model; delete hdr; } void Data::setMinimumHeader() { *hdr << "CALL" << "NAME" << "QSO_DATE" << "TIME_ON"; *hdr << "FREQ" << "MODE" << "BAND"; *hdr << "TX_RST"<< "RX_RST" << "COUNTRY"; *hdr << "QTH" << "GRIDSQUARE" << "STATE" << "CNTY"; *hdr << "COMMENT" << "EVENT"; *hdr << "CONTACT" << "CHECK"; *hdr << "OPERATOR" << "HOME_QTH" << "HOME_GRID" << "STATION_CALL"; *hdr << "QSL_SENT" <<"QSL_SENT_VIA"; *hdr << "QSL_RCVD" << "QSL_RCVD_VIA"; //qDebug() << *hdr; } QStringList Data::getHeaders() { //qDebug() << "in getHeader"; //qDebug() << *selectedhdr; return QStringList(*hdr); } QStandardItemModel* Data::getModel() { return( model ); } void Data::setModel(QStandardItemModel *mod) { qDebug() << "in setModel before " << model->item(1,1) << mod->item(1,1); model = mod; qDebug() << "in setModel after " << model->item(1,1) << mod->item(1,1); } void Data::updateRowColumns() { rows = model->rowCount(); columns = model->columnCount(); } void Data::writeXmlData( QString filename ) { updateRowColumns(); QFile data(filename); if (data.open(QIODevice::WriteOnly)) { QTextStream stream(&data); stream << QString("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") << endl; stream << QString("<?xml-stylesheet type=\"text/xsl\" href=\"qtlogger.xsl\" ?>") << endl; stream << QString("<AmateurRadioLog>") << endl; stream << QString(" <header>") << endl; stream << QString(" <program>") << endl; stream << QString(" <author>Dave Larsen KV0S</author>") << endl; stream << QString(" <info>For more information see: http://openhpsdr.org</info>") << endl; stream << QString(" <created>"); stream << (date->currentDateTimeUtc()).toString("yyyyMMdd-hhmm"); stream << QString(" UTC</created>") << endl; stream << QString(" <program>QtLogger</program>") << endl; stream << QString(" <programversion>%1</programversion>").arg( "1.0.1" ) << endl; // fix to mainWindow version stream << QString(" </program>") << endl; stream << QString(" </header>") << endl; stream << QString(" <contacts>") << endl; for (int i = 0; i < rows; ++i) { stream << QString(" <record>") << endl; for (int j = 0; j < columns; ++j) { QStandardItem * it; QString value; QString name; //int size = 0; it = model->item(i,j); if( !(it == 0) ) { name = (model->horizontalHeaderItem(j))->text(); value = (model->item(i,j))->text(); value.remove(QRegExp(" $")); //size = value.length(); stream << QString(" <"); stream << name.toLower(); stream << QString(">"); stream << value.simplified(); stream << QString("</"); stream << name.toLower(); stream << QString(">") << endl; } } stream << QString(" </record>") << endl; } stream << QString(" </contacts>") << endl; stream << QString("</AmateurRadioLog>") << endl; } data.close(); } QString* Data::readData() { QString *filetype = new QString(); QString fname = settings.value("filename").toString(); filename = QFileDialog::getOpenFileName(this, tr("Open File"),fname,tr("Files (*.xml *.adif *.adi)")); //qDebug() << "in data::readData" << filename << " returned " << endl; settings.setValue("filename", filename ); if( filename.contains("xml")) { readXMLHeader( filename ); *filetype = "XML"; readXMLData(); }else{ readADIFHeader( filename ); *filetype = "ADIF"; readADIFData(); } return filetype; } void Data::readXMLHeader( QString filename ) { QFile *file = new QFile(filename); if( !file->open(QFile::ReadOnly) ) { qDebug() << "Open XML Header file failed."; }else{ qDebug() << "Open XML Header file success."; } QXmlSimpleReader logxmlReader; QXmlInputSource *source = new QXmlInputSource( file ); logHandler *loghandler = new logHandler(); loghandler->readHeader( true ); logxmlReader.setContentHandler(loghandler); logxmlReader.setErrorHandler(loghandler); bool ok = logxmlReader.parse(source); if( !ok ) { qDebug() << "Parsing XML Data file failed."; } hdr = loghandler->getHeaders(); hdr->removeDuplicates(); //qDebug() << hdr->size() << *hdr << endl; columns = hdr->size(); //*selectedhdr = QStringList(*hdr); //qDebug() << *selectedhdr << endl; file->close(); } void Data::readXMLData() { QFile *file = new QFile(filename); if( !file->open(QFile::ReadOnly) ) { qDebug() << "Open XML Data file failed."; }else{ qDebug() << "Open XML Data file success."; } QXmlSimpleReader logxmlReader; QXmlInputSource *source = new QXmlInputSource( file ); logHandler *loghandler = new logHandler( model, hdr ); loghandler->readHeader( false ); loghandler->setHeader( hdr ); logxmlReader.setContentHandler(loghandler); logxmlReader.setErrorHandler(loghandler); bool ok = logxmlReader.parse(source); if( !ok ) { qDebug() << "Parsing XML Data file failed." << endl; } //qDebug() << (model->item(1,1))->text(); //qDebug() << "from Loghandler " << loghandler->getModel()->item(1,1); //qDebug() << "in readXMLData " << model->item(1,1); rows = loghandler->getRows(); emit refresh(); file->close(); } /** * \brief ADIF code elements * */ void Data::writeADIFData( QString filename ) { updateRowColumns(); QFile data(filename); if (data.open(QIODevice::WriteOnly)) { QTextStream stream(&data); stream << QString("ADIF v2.2.6 Exported from QtLogger-0.1") << endl; stream << QString("For more information see: http://openhpsdr.org") << endl; stream << QString("Log File saved: "); stream << (date->currentDateTimeUtc()).toString("yyyyMMdd-hhmm"); stream << QString(" UTC") << endl; stream << QString("<PROGRAMID:8>QtLogger<PROGRAMVERSION:3>") << QString("0.1") << endl; stream << QString("<EOH>") << endl << endl; for (int i = 0; i < rows; ++i) { for (int j = 0; j < columns; ++j) { QStandardItem * it; QString value; QString name; int size; it = model->item(i,j); if( !(it == 0) ) { name = (model->horizontalHeaderItem(j))->text(); value = (model->item(i,j))->text(); value.remove(QRegExp(" $")); size = value.length(); stream << QString("<"); stream << name; stream << QString(":%1").arg(size); stream << QString(">"); stream << value; } } stream << QString("<EOR>") << endl; } }else{ qDebug() << "Could not open file " << filename ; } data.close(); } void Data::readADIFHeader( QString filename ) { Adif *log = new Adif(this); QFile data(filename); //parent->ui->statusBar->showMessage(QString("Opening: \"%1\"").arg(filename)); if (data.open(QFile::ReadOnly)) { QTextStream stream(&data); QString line; QString *record; QStringList *list; do { line = stream.readLine(); //qDebug() << line << endl; record = log->adifParseRecords(&line, false); list = log->adifParseToItem(record); //qDebug() << list->size() << *list << endl; for(int i = 0; i < list->size(); i++){ QStandardItem *it = new QStandardItem(); QString *name = new QString(); log->adifParseItem(list->at(i), it, name); *hdr << *name; } hdr->removeDuplicates(); }while(!line.isNull()); //qDebug() << "in loadHeader"; //qDebug() << hdr->size() << *hdr << endl; columns = hdr->size(); //*selectedhdr = QStringList(*hdr); //qDebug() << *selectedhdr; data.close(); } } void Data::readADIFData() { Adif *log = new Adif(this); QFile data(filename); //parent->ui->statusBar->showMessage(QString("Opening: \"%1\"").arg(filename)); if (data.open(QFile::ReadOnly)) { QTextStream stream(&data); QString line; QString *record; QStringList *list; int row = 0; int col = 0; do { line = stream.readLine(); //qDebug() << line << endl; if ( line.contains("CALL") ) { record = log->adifParseRecords(&line, false); list = log->adifParseToItem(record); //qDebug() << list->size() << *list << endl; for(int i = 0; i < list->size(); i++){ QStandardItem *it = new QStandardItem(); QString *name = new QString(); log->adifParseItem(list->at(i), it, name); model->setItem(row,hdr->indexOf(*name),it); col++; } row++; col = 0; } }while(!line.isNull()); rows = row; //qDebug() << hdr->size() << *hdr << endl; emit refresh(); }else{ qDebug() << " Could not open ADIF file " << filename << endl; } data.close(); } void Data::queryFilename() { QString dname = settings.value("directory").toString(); filename = QFileDialog::getOpenFileName(this, tr("Open File"),dname,tr("Files (*.adif *.adi)")); //qDebug() << filename << " returned " << endl; } void Data::setFilename( QString fname ) { filename = fname; } QString Data::getFilename() { return filename; } void Data::setDirname( QString dname ) { dirname = dname; } QString Data::getDirname() { return dirname; } void Data::updateHeaders() { // *selectedhdr = QStringList(coldat->getResult()); } int Data::getRows() { qDebug() << rows; return rows; } int Data::getColumns() { qDebug() << columns; return columns; } void Data::removeRow( QModelIndex idx ) { int row = idx.row(); model->removeRow(row, idx ); }
mit
uchicago-library/django-shibboleth-remoteuser
shibboleth/tests/test_shib.py
14484
# -*- coding: utf-8 -*- import os from django.conf import settings from django.contrib import auth from django.contrib.auth.middleware import AuthenticationMiddleware from django.contrib.auth.middleware import RemoteUserMiddleware from django.contrib.auth.models import User, Group from django.contrib.sessions.middleware import SessionMiddleware from django.db.utils import IntegrityError from django.test import TestCase, RequestFactory SAMPLE_HEADERS = { "REMOTE_USER": '[email protected]', "Shib-Application-ID": "default", "Shib-Authentication-Method": "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified", "Shib-AuthnContext-Class": "urn:oasis:names:tc:SAML:2.0:ac:classes:unspecified", "Shib-Identity-Provider": "https://sso.college.edu/idp/shibboleth", "Shib-Session-ID": "1", "Shib-Session-Index": "12", "Shibboleth-affiliation": "[email protected];[email protected]", "Shibboleth-schoolBarCode": "12345678", "Shibboleth-schoolNetId": "Sample_Developer", "Shibboleth-schoolStatus": "active", "Shibboleth-department": "University Library, Integrated Technology Services", "Shibboleth-displayName": "Sample Developer", "Shibboleth-eppn": "[email protected]", "Shibboleth-givenName": "Sample", "Shibboleth-isMemberOf": "SCHOOL:COMMUNITY:EMPLOYEE:ADMINISTRATIVE:BASE;SCHOOL:COMMUNITY:EMPLOYEE:STAFF:SAC:P;COMMUNITY:ALL;SCHOOL:COMMUNITY:EMPLOYEE:STAFF:SAC:M;", "Shibboleth-isMemberOf-multi-delimiter": "SCHOOL:COMMUNITY:EMPLOYEE:ADMINISTRATIVE:BASE,SCHOOL:COMMUNITY:EMPLOYEE:STAFF:SAC:P,COMMUNITY:ALL;SCHOOL:COMMUNITY:EMPLOYEE:STAFF:SAC:M,", "Shibboleth-mail": "[email protected]", "Shibboleth-persistent-id": "https://sso.college.edu/idp/shibboleth!https://server.college.edu/shibboleth-sp!sk1Z9qKruvXY7JXvsq4GRb8GCUk=", "Shibboleth-sn": "Developer", "Shibboleth-title": "Library Developer", "Shibboleth-unscoped-affiliation": "member;staff", } settings.SHIBBOLETH_ATTRIBUTE_MAP = { "Shib-Identity-Provider": (True, "idp"), "Shibboleth-mail": (True, "email"), "Shibboleth-eppn": (True, "username"), "Shibboleth-schoolStatus": (True, "status"), "Shibboleth-affiliation": (True, "affiliation"), "Shib-Session-ID": (True, "session_id"), "Shibboleth-givenName": (True, "first_name"), "Shibboleth-sn": (True, "last_name"), "Shibboleth-schoolBarCode": (False, "barcode") } settings.AUTHENTICATION_BACKENDS += ( 'shibboleth.backends.ShibbolethRemoteUserBackend', ) settings.MIDDLEWARE_CLASSES += ( 'shibboleth.middleware.ShibbolethRemoteUserMiddleware', ) settings.ROOT_URLCONF = 'shibboleth.urls' settings.SHIBBOLETH_LOGOUT_URL = 'https://sso.school.edu/logout?next=%s' settings.SHIBBOLETH_LOGOUT_REDIRECT_URL = 'http://school.edu/' # MUST be imported after the settings above from shibboleth import app_settings from shibboleth import middleware from shibboleth import backends try: from importlib import reload # python 3.4+ except ImportError: try: from imp import reload # for python 3.2/3.3 except ImportError: pass # this means we're on python 2, where reload is a builtin function class AttributesTest(TestCase): def test_decorator_not_authenticated(self): resp = self.client.get('/') self.assertEqual(resp.status_code, 302) # Test the context - shouldn't exist self.assertEqual(resp.context, None) def test_decorator_authenticated(self): resp = self.client.get('/', **SAMPLE_HEADERS) self.assertEqual(resp.status_code, 200) # Test the context user = resp.context.get('user') self.assertEqual(user.email, '[email protected]') self.assertEqual(user.first_name, 'Sample') self.assertEqual(user.last_name, 'Developer') self.assertTrue(user.is_authenticated()) self.assertFalse(user.is_anonymous()) class TestShibbolethRemoteUserMiddleware(TestCase): def setUp(self): self.request_factory = RequestFactory() self.smw = SessionMiddleware() self.amw = AuthenticationMiddleware() self.rmw = RemoteUserMiddleware() self.srmw = middleware.ShibbolethRemoteUserMiddleware() def _process_request_through_middleware(self, request): self.smw.process_request(request) self.amw.process_request(request) self.rmw.process_request(request) return self.srmw.process_request(request) def test_no_remote_user(self): test_request = self.request_factory.get('/') self._process_request_through_middleware(test_request) #shouldn't have done anything - just return because no REMOTE_USER self.assertTrue('shib' not in test_request.session) self.assertFalse(test_request.user.is_authenticated()) def test_remote_user_empty(self): test_request = self.request_factory.get('/', REMOTE_USER='') response = self._process_request_through_middleware(test_request) self.assertTrue('shib' not in test_request.session) self.assertFalse(test_request.user.is_authenticated()) class TestShibbolethRemoteUserBackend(TestCase): def _get_valid_shib_meta(self, location='/'): request_factory = RequestFactory() test_request = request_factory.get(location) test_request.META.update(**SAMPLE_HEADERS) shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(test_request) self.assertFalse(error, 'Generating shibboleth attribute mapping contains errors') return shib_meta def test_create_unknown_user_true(self): self.assertFalse(User.objects.all()) shib_meta = self._get_valid_shib_meta() user = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) self.assertEqual(user.username, '[email protected]') self.assertEqual(User.objects.all()[0].username, '[email protected]') def test_create_unknown_user_false(self): with self.settings(CREATE_UNKNOWN_USER=False): # reload our shibboleth.backends module, so it picks up the settings change reload(backends) shib_meta = self._get_valid_shib_meta() self.assertFalse(User.objects.all()) user = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) self.assertTrue(user is None) self.assertFalse(User.objects.all()) # now reload again, so it reverts to original settings reload(backends) def test_auth_inactive_user_false(self): shib_meta = self._get_valid_shib_meta() # Pre-create an inactive user User.objects.create(username='[email protected]', is_active=False) user = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) self.assertTrue(user is None) def test_ensure_user_attributes(self): shib_meta = self._get_valid_shib_meta() # Create / authenticate the test user and store another mail address user = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) user.email = '[email protected]' user.save() # The user must contain the invalid mail address user = User.objects.get(username='[email protected]') self.assertEqual(user.email, '[email protected]') # After authenticate the user again, the mail address must be set back to the shibboleth data user2 = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) self.assertEqual(user2.email, '[email protected]') def test_authenticate_with_exclude_field(self): shib_meta = self._get_valid_shib_meta() shib_meta['email'] = None # email is a required field at the ORM level, passing None throws an error with self.assertRaises(IntegrityError): auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) # using the exclude absent option works correctly shib_meta.pop('email') user = auth.authenticate(remote_user='[email protected]', shib_meta=shib_meta) self.assertEqual(user.email, '') class TestShibbolethParseAttributes(TestCase): def setUp(self): request_factory = RequestFactory() self.test_request = request_factory.get('/') self.test_request.META.update(**SAMPLE_HEADERS) def test_present_required_attribute(self): shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(self.test_request) self.assertEqual(shib_meta["last_name"], SAMPLE_HEADERS["Shibboleth-sn"]) self.assertFalse(error) def test_missing_required_attribute(self): self.test_request.META.pop("Shibboleth-sn") shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(self.test_request) self.assertTrue(error) def test_present_optional_attribute(self): shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(self.test_request) self.assertEqual(shib_meta["barcode"], SAMPLE_HEADERS["Shibboleth-schoolBarCode"]) self.assertFalse(error) def test_missing_optional_attribute(self): self.test_request.META.pop("Shibboleth-schoolBarCode") shib_meta, error = middleware.ShibbolethRemoteUserMiddleware.parse_attributes(self.test_request) self.assertFalse('barcode' in shib_meta.keys()) self.assertFalse(error) class TestShibbolethGroupAssignment(TestCase): def test_unconfigured_group(self): # by default SHIBBOLETH_GROUP_ATTRIBUTES = [] - so no groups will be touched with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=[]): reload(app_settings) reload(middleware) # After login the user will be created self.client.get('/', **SAMPLE_HEADERS) query = User.objects.filter(username='[email protected]') # Ensure the user was created self.assertEqual(len(query), 1) user = User.objects.get(username='[email protected]') # The user should have no groups self.assertEqual(len(user.groups.all()), 0) # Create a group and add the user g = Group(name='Testgroup') g.save() # Now we should have exactly one group self.assertEqual(len(Group.objects.all()), 1) g.user_set.add(user) # Now the user should be in exactly one group self.assertEqual(len(user.groups.all()), 1) self.client.get('/', **SAMPLE_HEADERS) # After a request the user should still be in the group. self.assertEqual(len(user.groups.all()), 1) def test_group_creation(self): # Test for group creation with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=['Shibboleth-affiliation']): reload(app_settings) reload(middleware) self.client.get('/', **SAMPLE_HEADERS) user = User.objects.get(username='[email protected]') self.assertEqual(len(Group.objects.all()), 2) self.assertEqual(len(user.groups.all()), 2) def test_group_creation_list(self): # Test for group creation from a list of group attributes with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=['Shibboleth-affiliation', 'Shibboleth-isMemberOf']): reload(app_settings) reload(middleware) self.client.get('/', **SAMPLE_HEADERS) user = User.objects.get(username='[email protected]') self.assertEqual(len(Group.objects.all()), 6) self.assertEqual(len(user.groups.all()), 6) def test_group_creation_list_comma(self): # Test for group creation from a list of group attributes with a different delimiter with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=['Shibboleth-isMemberOf-multi-delimiter'], SHIBBOLETH_GROUP_DELIMITERS=[',']): reload(app_settings) reload(middleware) self.client.get('/', **SAMPLE_HEADERS) user = User.objects.get(username='[email protected]') self.assertEqual(len(Group.objects.all()), 3) self.assertEqual(len(user.groups.all()), 3) def test_group_creation_list_mixed_comma_semicolon(self): # Test for group creation from a list of group attributes with multiple delimiters with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=['Shibboleth-affiliation', 'Shibboleth-isMemberOf-multi-delimiter'], SHIBBOLETH_GROUP_DELIMITERS=[',', ';']): reload(app_settings) reload(middleware) self.client.get('/', **SAMPLE_HEADERS) user = User.objects.get(username='[email protected]') self.assertEqual(len(Group.objects.all()), 6) self.assertEqual(len(user.groups.all()), 6) def test_empty_group_attribute(self): # Test everthing is working even if the group attribute is missing in the shibboleth data with self.settings(SHIBBOLETH_GROUP_ATTRIBUTES=['Shibboleth-not-existing-attribute']): reload(app_settings) reload(middleware) self.client.get('/', **SAMPLE_HEADERS) user = User.objects.get(username='[email protected]') self.assertEqual(len(Group.objects.all()), 0) self.assertEqual(len(user.groups.all()), 0) class LogoutTest(TestCase): def test_logout(self): # Login login = self.client.get('/', **SAMPLE_HEADERS) self.assertEqual(login.status_code, 200) # Check login login = self.client.get('/') self.assertEqual(login.status_code, 200) # Logout logout = self.client.get('/logout/', **SAMPLE_HEADERS) self.assertEqual(logout.status_code, 302) # Ensure redirect happened. self.assertEqual( logout['Location'], 'https://sso.school.edu/logout?next=http://school.edu/' ) # Load root url to see if user is in fact logged out. resp = self.client.get('/') self.assertEqual(resp.status_code, 302) # Make sure the context is empty. self.assertEqual(resp.context, None)
mit
saludnqn/consultorio
DalSic/generated/SysRelProfesionalEfectorController.cs
4216
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Controller class for Sys_RelProfesionalEfector /// </summary> [System.ComponentModel.DataObject] public partial class SysRelProfesionalEfectorController { // Preload our schema.. SysRelProfesionalEfector thisSchemaLoad = new SysRelProfesionalEfector(); private string userName = String.Empty; protected string UserName { get { if (userName.Length == 0) { if (System.Web.HttpContext.Current != null) { userName=System.Web.HttpContext.Current.User.Identity.Name; } else { userName=System.Threading.Thread.CurrentPrincipal.Identity.Name; } } return userName; } } [DataObjectMethod(DataObjectMethodType.Select, true)] public SysRelProfesionalEfectorCollection FetchAll() { SysRelProfesionalEfectorCollection coll = new SysRelProfesionalEfectorCollection(); Query qry = new Query(SysRelProfesionalEfector.Schema); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public SysRelProfesionalEfectorCollection FetchByID(object IdRelProfesionalEfector) { SysRelProfesionalEfectorCollection coll = new SysRelProfesionalEfectorCollection().Where("idRelProfesionalEfector", IdRelProfesionalEfector).Load(); return coll; } [DataObjectMethod(DataObjectMethodType.Select, false)] public SysRelProfesionalEfectorCollection FetchByQuery(Query qry) { SysRelProfesionalEfectorCollection coll = new SysRelProfesionalEfectorCollection(); coll.LoadAndCloseReader(qry.ExecuteReader()); return coll; } [DataObjectMethod(DataObjectMethodType.Delete, true)] public bool Delete(object IdRelProfesionalEfector) { return (SysRelProfesionalEfector.Delete(IdRelProfesionalEfector) == 1); } [DataObjectMethod(DataObjectMethodType.Delete, false)] public bool Destroy(object IdRelProfesionalEfector) { return (SysRelProfesionalEfector.Destroy(IdRelProfesionalEfector) == 1); } /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Insert, true)] public void Insert(int IdProfesional,int IdEfector,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn) { SysRelProfesionalEfector item = new SysRelProfesionalEfector(); item.IdProfesional = IdProfesional; item.IdEfector = IdEfector; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Save(UserName); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> [DataObjectMethod(DataObjectMethodType.Update, true)] public void Update(int IdRelProfesionalEfector,int IdProfesional,int IdEfector,string CreatedBy,DateTime CreatedOn,string ModifiedBy,DateTime ModifiedOn) { SysRelProfesionalEfector item = new SysRelProfesionalEfector(); item.MarkOld(); item.IsLoaded = true; item.IdRelProfesionalEfector = IdRelProfesionalEfector; item.IdProfesional = IdProfesional; item.IdEfector = IdEfector; item.CreatedBy = CreatedBy; item.CreatedOn = CreatedOn; item.ModifiedBy = ModifiedBy; item.ModifiedOn = ModifiedOn; item.Save(UserName); } } }
mit
Siliconrob/MultiGeocoder
tests/GeoTests/Properties/AssemblyInfo.cs
1349
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("GeoTests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("GeoTests")] [assembly: AssemblyCopyright("© 2013 - 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("3f4e9b22-e3ab-42b2-8729-c84c33706d02")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("0.0.0.1")] [assembly: AssemblyFileVersion("0.0.0.1")]
mit
bullhorn/career-portal
src/typings.d.ts
316
/* SystemJS module definition */ declare var module: NodeModule; interface NodeModule { id: string; } export interface ICategoryListResponse { idCount: number, publishedCategory: { id: number, name: string }; } interface IAddressListResponse { idCount: number, address: { city: string, state: string }; }
mit
superusercode/RTC3
Real-Time Corruptor/BizHawk_RTC/libgambatte/src/sound/channel3.cpp
6103
/*************************************************************************** * Copyright (C) 2007 by Sindre Aamås * * [email protected] * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License version 2 as * * published by the Free Software Foundation. * * * * 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 version 2 for more details. * * * * You should have received a copy of the GNU General Public License * * version 2 along with this program; if not, write to the * * Free Software Foundation, Inc., * * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * ***************************************************************************/ #include "channel3.h" #include "../savestate.h" #include <cstring> #include <algorithm> static inline unsigned toPeriod(const unsigned nr3, const unsigned nr4) { return 0x800 - ((nr4 << 8 & 0x700) | nr3); } namespace gambatte { Channel3::Channel3() : disableMaster(master, waveCounter), lengthCounter(disableMaster, 0xFF), cycleCounter(0), soMask(0), prevOut(0), waveCounter(SoundUnit::COUNTER_DISABLED), lastReadTime(0), nr0(0), nr3(0), nr4(0), wavePos(0), rShift(4), sampleBuf(0), master(false), cgb(false) {} void Channel3::setNr0(const unsigned data) { nr0 = data & 0x80; if (!(data & 0x80)) disableMaster(); } void Channel3::setNr2(const unsigned data) { rShift = (data >> 5 & 3U) - 1; if (rShift > 3) rShift = 4; } void Channel3::setNr4(const unsigned data) { lengthCounter.nr4Change(nr4, data, cycleCounter); nr4 = data & 0x7F; if (data & nr0/* & 0x80*/) { if (!cgb && waveCounter == cycleCounter + 1) { const unsigned pos = ((wavePos + 1) & 0x1F) >> 1; if (pos < 4) waveRam[0] = waveRam[pos]; else std::memcpy(waveRam, waveRam + (pos & ~3), 4); } master = true; wavePos = 0; lastReadTime = waveCounter = cycleCounter + toPeriod(nr3, data) + 3; } } void Channel3::setSo(const unsigned long soMask) { this->soMask = soMask; } void Channel3::reset() { cycleCounter = 0x1000 | (cycleCounter & 0xFFF); // cycleCounter >> 12 & 7 represents the frame sequencer position. // lengthCounter.reset(); sampleBuf = 0; } void Channel3::init(const bool cgb) { this->cgb = cgb; lengthCounter.init(cgb); } void Channel3::setStatePtrs(SaveState &state) { state.spu.ch3.waveRam.set(waveRam, sizeof waveRam); } void Channel3::loadState(const SaveState &state) { lengthCounter.loadState(state.spu.ch3.lcounter, state.spu.cycleCounter); cycleCounter = state.spu.cycleCounter; waveCounter = std::max(state.spu.ch3.waveCounter, state.spu.cycleCounter); lastReadTime = state.spu.ch3.lastReadTime; nr3 = state.spu.ch3.nr3; nr4 = state.spu.ch3.nr4; wavePos = state.spu.ch3.wavePos & 0x1F; sampleBuf = state.spu.ch3.sampleBuf; master = state.spu.ch3.master; nr0 = state.mem.ioamhram.get()[0x11A] & 0x80; setNr2(state.mem.ioamhram.get()[0x11C]); } void Channel3::updateWaveCounter(const unsigned long cc) { if (cc >= waveCounter) { const unsigned period = toPeriod(nr3, nr4); const unsigned long periods = (cc - waveCounter) / period; lastReadTime = waveCounter + periods * period; waveCounter = lastReadTime + period; wavePos += periods + 1; wavePos &= 0x1F; sampleBuf = waveRam[wavePos >> 1]; } } void Channel3::update(uint_least32_t *buf, const unsigned long soBaseVol, unsigned long cycles) { const unsigned long outBase = (nr0/* & 0x80*/) ? soBaseVol & soMask : 0; if (outBase && rShift != 4) { const unsigned long endCycles = cycleCounter + cycles; for (;;) { const unsigned long nextMajorEvent = lengthCounter.getCounter() < endCycles ? lengthCounter.getCounter() : endCycles; unsigned long out = outBase * (master ? ((sampleBuf >> (~wavePos << 2 & 4) & 0xF) >> rShift) * 2 - 15ul : 0 - 15ul); while (waveCounter <= nextMajorEvent) { *buf += out - prevOut; prevOut = out; buf += waveCounter - cycleCounter; cycleCounter = waveCounter; lastReadTime = waveCounter; waveCounter += toPeriod(nr3, nr4); ++wavePos; wavePos &= 0x1F; sampleBuf = waveRam[wavePos >> 1]; out = outBase * (/*master ? */((sampleBuf >> (~wavePos << 2 & 4) & 0xF) >> rShift) * 2 - 15ul/* : 0 - 15ul*/); } if (cycleCounter < nextMajorEvent) { *buf += out - prevOut; prevOut = out; buf += nextMajorEvent - cycleCounter; cycleCounter = nextMajorEvent; } if (lengthCounter.getCounter() == nextMajorEvent) { lengthCounter.event(); } else break; } } else { if (outBase) { const unsigned long out = outBase * (0 - 15ul); *buf += out - prevOut; prevOut = out; } cycleCounter += cycles; while (lengthCounter.getCounter() <= cycleCounter) { updateWaveCounter(lengthCounter.getCounter()); lengthCounter.event(); } updateWaveCounter(cycleCounter); } if (cycleCounter & SoundUnit::COUNTER_MAX) { lengthCounter.resetCounters(cycleCounter); if (waveCounter != SoundUnit::COUNTER_DISABLED) waveCounter -= SoundUnit::COUNTER_MAX; lastReadTime -= SoundUnit::COUNTER_MAX; cycleCounter -= SoundUnit::COUNTER_MAX; } } SYNCFUNC(Channel3) { NSS(waveRam); SSS(lengthCounter); NSS(cycleCounter); NSS(soMask); NSS(prevOut); NSS(waveCounter); NSS(lastReadTime); NSS(nr0); NSS(nr3); NSS(nr4); NSS(wavePos); NSS(rShift); NSS(sampleBuf); NSS(master); NSS(cgb); } }
mit
schahriar/blanc
superlog.js
6791
var eventEmmiter = require('events').EventEmitter; var util = require('util'); var StringDecoder = require('string_decoder').StringDecoder; var _ = require('lodash') var herb = require('herb'); var culinary = require('culinary'); var screen = culinary.size(); var fs = require('fs'); var path = require('path'); var notifier = require('node-notifier'); // Locals var notifierManager = {}; var logArray = []; // function time(noPadding) { var now = new Date(); return (((!noPadding)?" [":"[") + now.getHours() + ":" + ((now.getMinutes() < 10) ? ("0" + now.getMinutes()) : now.getMinutes()) + ":" + ((now.getSeconds() < 10) ? ("0" + now.getSeconds()) : now.getSeconds()) + ((!noPadding)?"] ":"]")); } var SuperLog = function(title, prefix, silent) { this.title = title; this.padding = { top: 3, bottom: 0 }; this.name = (prefix) ? prefix + ' ' + title : title; this.hush = !!silent; this.nCount = 0; this.templates = { header: herb.template('write', 'blue', 'white', 'dim', 'magenta', 'white', 'bold'), error: herb.template('write', 'yellow', 'dim', 'bgRed', 'red', 'bold') } this.hasError = false; this.solve = function() { for (i = 4; i <= screen.height; i++) { culinary.position(0, i).eraseLine() } culinary.position(0, 4); this.hasError = false; } eventEmmiter.call(this); } util.inherits(SuperLog, eventEmmiter); SuperLog.prototype.header = function() { if (this.hush === 'force') return false; var text = _.toArray(arguments).join(' '); culinary.position(0, 0).clearScreen(); herb.marker({ style: 'dim' }).line('~'); this.templates.header(this.name, '|', '[start]', text || ' '); herb.marker({ style: 'dim' }).line('~'); culinary.position(0, 4); process.on('exit', function(){ culinary.clearScreen().position(0,0); }); } SuperLog.prototype.task = function(plugin, task, status) { if (this.hush === 'force') return false; if (this.hasError) this.solve(); var type = { 'Less': 'yellow', 'Jade': 'magenta', 'Reso': 'cyan', 'Brow': 'blue' } culinary.save().position(0, 2).eraseLine(); try { this.templates.header(this.name, '|', time(), herb[type[plugin.substring(0, 4)]](plugin), task, status); } catch (e) { culinary.write(this.name, '|', time(), plugin, task); } culinary.restore(); this.addLog(herb.dim(time(true)), herb[type[plugin.substring(0, 4)]](plugin), task, status || '', 'done!'); this.notify('Task ' + plugin + ' ' + task + ' done!', plugin); } SuperLog.prototype.error = function(plugin, code) { if (this.hush === 'force') return false; if (this.hasError) this.solve(); culinary.save().position(0, 2).eraseLine(); this.templates.error(this.name, '|', time(), 'ERROR: ' + plugin, code); culinary.restore(); this.notify('ERROR: ' + plugin + ' ' + code, 'ERROR') } SuperLog.prototype.plumb = function(message) { if (this.hush === 'force') return false; this.hasError = true; culinary.position(0, 4); herb.marker({ color: 'dim' }).line('ERROR - '); _.each(message.split('\n'), function(line, index) { culinary.position(1, index + 5).eraseLine(); culinary.write(herb.yellow(line || ' ') + '\n'); }) culinary.position(0, 4); } SuperLog.prototype.addLog = function() { if (this.hush === 'force') return false; var startAt = 4; var available = screen.height - (this.padding.bottom+startAt); var type = { 'Less': 'yellow', 'Jade': 'magenta', 'Reso': 'cyan', 'Brow': 'blue' } if(logArray.length >= available) logArray.shift(); logArray.push(_.toArray(arguments).join(' ')); _.each(logArray, function(log, pos) { culinary.position(0, pos + startAt).eraseLine(); // Process log log = log.replace(require('ansi-regex')(), ''); // If time is prepended if (/\[.*?\]/.exec(log)) { _time = /\[.*?\]/.exec(log)[0]; }else{ _time = time(true) + ' '; // Keeps a constant time logArray[pos] = _time + log; } log = log.replace(/\[.*?\]/, ''); log = (type[log.substring(1,5)])?herb[type[log.substring(1,5)]](log):herb.bold(log); log = herb.dim(_time) + log; herb.write(log); }) } SuperLog.prototype.notify = function(message, type) { if (this.hush) return false; if (notifierManager[type] === true) return false; notifier.notify({ title: (type === 'ERROR') ? this.title + ' ERROR' : this.title, message: message, icon: path.resolve(__dirname, this.title, '.png'), }) notifierManager[type] = true; setTimeout(function() { notifierManager[type] = false; }, (type === 'ERROR') ? 6000 : 3500); } SuperLog.prototype.silent = function(type) { this.hush = type || true; } SuperLog.prototype.clear = function(x, y) { if (this.hush === 'force') return false; culinary.clearScreen().position(x || 0, y || 0); } SuperLog.prototype.line = function() { if (this.hush === 'force') return false; var args = _.toArray(arguments); var line = args.shift(); if (line.substring(0, 4) === 'last') { if(this.padding.bottom < 1) this.padding.bottom = 1; if (line.substring(4, 5) === '-') { this.padding.bottom = parseInt(line.split('-')[1]) + 1; line = screen.height - parseInt(line.split('-')[1]); } else line = screen.height + 1; }else if (line.substring(0, 5) === 'first') { if(this.padding.top < 1) this.padding.top = 1; if (line.substring(5, 6) === '+') { this.padding.top = parseInt(line.split('-')[1]) + 1; line = parseInt(line.split('-')[1]); } else line = 1; } culinary.save().position(0, line).eraseLine(); culinary.write(args.join(' ')); culinary.restore(); } SuperLog.prototype.progress = function(color, text) { var self = this; return function(callback) { if(self.hush) return (callback)?callback():false; self.line('last', herb.blue(' '+ self.title +' | ') + herb[color](text)); if(callback) setTimeout(callback, 1000); } } SuperLog.prototype.progressLog = function() { var self = this; var args = _.toArray(arguments); var time = args.shift(); var callback = args.pop(); if(self.hush) return (callback)?callback():false; setTimeout(function(){ console.log(args.join(' ')); callback(); }, time * self.nCount); self.nCount++; } module.exports = function(title, prefix, silent) { return new SuperLog(title, prefix, silent); };
mit
rsilveira79/RaspiFlow
face_land.py
1078
from imutils.video import VideoStream from imutils import face_utils import imutils import time import dlib import cv2 import argparse # Initialize face detector and create face landmark predictor print("[INFO] loading facial landmark predictor ...") detector = dlib.get_frontal_face_detector() predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat") # Initialize the video stream and allow camera sensor to warm up print("[INFO] camera sensor warming up ...") vs = VideoStream(usePiCamera=True).start() time.sleep(2.0) while True: frame=vs.read() frame = imutils.resize(frame, width=400) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # detect faces in grayscale rects = detector(gray,0) for rect in rects: shape = predictor(gray,rect) shape = face_utils.shape_to_np(shape) for (x,y) in shape: cv2.circle(frame,(x,y), 1, (0,0,255),-1) cv2.imshow("Frame", frame) key = cv2.waitKey(1)& 0xFF if key == ord("q"): break cv2.destroyAllWindows() vs.stop()
mit
Royal-Society-of-New-Zealand/NZ-ORCID-Hub
orcid_api_v3/models/activities_summary_v30_rc2.py
14235
# coding: utf-8 """ ORCID Member No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501 OpenAPI spec version: Latest Generated by: https://github.com/swagger-api/swagger-codegen.git """ import pprint import re # noqa: F401 import six from orcid_api_v3.models.distinctions_summary_v30_rc2 import DistinctionsSummaryV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.educations_summary_v30_rc2 import EducationsSummaryV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.employments_summary_v30_rc2 import EmploymentsSummaryV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.fundings_v30_rc2 import FundingsV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.invited_positions_v30_rc2 import InvitedPositionsV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.last_modified_date_v30_rc2 import LastModifiedDateV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.memberships_v30_rc2 import MembershipsV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.peer_reviews_v30_rc2 import PeerReviewsV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.qualifications_v30_rc2 import QualificationsV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.research_resources_v30_rc2 import ResearchResourcesV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.services_v30_rc2 import ServicesV30Rc2 # noqa: F401,E501 from orcid_api_v3.models.works_summary_v30_rc2 import WorksSummaryV30Rc2 # noqa: F401,E501 class ActivitiesSummaryV30Rc2(object): """NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ """ Attributes: swagger_types (dict): The key is attribute name and the value is attribute type. attribute_map (dict): The key is attribute name and the value is json key in definition. """ swagger_types = { 'last_modified_date': 'LastModifiedDateV30Rc2', 'distinctions': 'DistinctionsSummaryV30Rc2', 'educations': 'EducationsSummaryV30Rc2', 'employments': 'EmploymentsSummaryV30Rc2', 'fundings': 'FundingsV30Rc2', 'invited_positions': 'InvitedPositionsV30Rc2', 'memberships': 'MembershipsV30Rc2', 'peer_reviews': 'PeerReviewsV30Rc2', 'qualifications': 'QualificationsV30Rc2', 'research_resources': 'ResearchResourcesV30Rc2', 'services': 'ServicesV30Rc2', 'works': 'WorksSummaryV30Rc2', 'path': 'str' } attribute_map = { 'last_modified_date': 'last-modified-date', 'distinctions': 'distinctions', 'educations': 'educations', 'employments': 'employments', 'fundings': 'fundings', 'invited_positions': 'invited-positions', 'memberships': 'memberships', 'peer_reviews': 'peer-reviews', 'qualifications': 'qualifications', 'research_resources': 'research-resources', 'services': 'services', 'works': 'works', 'path': 'path' } def __init__(self, last_modified_date=None, distinctions=None, educations=None, employments=None, fundings=None, invited_positions=None, memberships=None, peer_reviews=None, qualifications=None, research_resources=None, services=None, works=None, path=None): # noqa: E501 """ActivitiesSummaryV30Rc2 - a model defined in Swagger""" # noqa: E501 self._last_modified_date = None self._distinctions = None self._educations = None self._employments = None self._fundings = None self._invited_positions = None self._memberships = None self._peer_reviews = None self._qualifications = None self._research_resources = None self._services = None self._works = None self._path = None self.discriminator = None if last_modified_date is not None: self.last_modified_date = last_modified_date if distinctions is not None: self.distinctions = distinctions if educations is not None: self.educations = educations if employments is not None: self.employments = employments if fundings is not None: self.fundings = fundings if invited_positions is not None: self.invited_positions = invited_positions if memberships is not None: self.memberships = memberships if peer_reviews is not None: self.peer_reviews = peer_reviews if qualifications is not None: self.qualifications = qualifications if research_resources is not None: self.research_resources = research_resources if services is not None: self.services = services if works is not None: self.works = works if path is not None: self.path = path @property def last_modified_date(self): """Gets the last_modified_date of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The last_modified_date of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: LastModifiedDateV30Rc2 """ return self._last_modified_date @last_modified_date.setter def last_modified_date(self, last_modified_date): """Sets the last_modified_date of this ActivitiesSummaryV30Rc2. :param last_modified_date: The last_modified_date of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: LastModifiedDateV30Rc2 """ self._last_modified_date = last_modified_date @property def distinctions(self): """Gets the distinctions of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The distinctions of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: DistinctionsSummaryV30Rc2 """ return self._distinctions @distinctions.setter def distinctions(self, distinctions): """Sets the distinctions of this ActivitiesSummaryV30Rc2. :param distinctions: The distinctions of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: DistinctionsSummaryV30Rc2 """ self._distinctions = distinctions @property def educations(self): """Gets the educations of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The educations of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: EducationsSummaryV30Rc2 """ return self._educations @educations.setter def educations(self, educations): """Sets the educations of this ActivitiesSummaryV30Rc2. :param educations: The educations of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: EducationsSummaryV30Rc2 """ self._educations = educations @property def employments(self): """Gets the employments of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The employments of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: EmploymentsSummaryV30Rc2 """ return self._employments @employments.setter def employments(self, employments): """Sets the employments of this ActivitiesSummaryV30Rc2. :param employments: The employments of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: EmploymentsSummaryV30Rc2 """ self._employments = employments @property def fundings(self): """Gets the fundings of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The fundings of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: FundingsV30Rc2 """ return self._fundings @fundings.setter def fundings(self, fundings): """Sets the fundings of this ActivitiesSummaryV30Rc2. :param fundings: The fundings of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: FundingsV30Rc2 """ self._fundings = fundings @property def invited_positions(self): """Gets the invited_positions of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The invited_positions of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: InvitedPositionsV30Rc2 """ return self._invited_positions @invited_positions.setter def invited_positions(self, invited_positions): """Sets the invited_positions of this ActivitiesSummaryV30Rc2. :param invited_positions: The invited_positions of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: InvitedPositionsV30Rc2 """ self._invited_positions = invited_positions @property def memberships(self): """Gets the memberships of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The memberships of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: MembershipsV30Rc2 """ return self._memberships @memberships.setter def memberships(self, memberships): """Sets the memberships of this ActivitiesSummaryV30Rc2. :param memberships: The memberships of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: MembershipsV30Rc2 """ self._memberships = memberships @property def peer_reviews(self): """Gets the peer_reviews of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The peer_reviews of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: PeerReviewsV30Rc2 """ return self._peer_reviews @peer_reviews.setter def peer_reviews(self, peer_reviews): """Sets the peer_reviews of this ActivitiesSummaryV30Rc2. :param peer_reviews: The peer_reviews of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: PeerReviewsV30Rc2 """ self._peer_reviews = peer_reviews @property def qualifications(self): """Gets the qualifications of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The qualifications of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: QualificationsV30Rc2 """ return self._qualifications @qualifications.setter def qualifications(self, qualifications): """Sets the qualifications of this ActivitiesSummaryV30Rc2. :param qualifications: The qualifications of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: QualificationsV30Rc2 """ self._qualifications = qualifications @property def research_resources(self): """Gets the research_resources of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The research_resources of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: ResearchResourcesV30Rc2 """ return self._research_resources @research_resources.setter def research_resources(self, research_resources): """Sets the research_resources of this ActivitiesSummaryV30Rc2. :param research_resources: The research_resources of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: ResearchResourcesV30Rc2 """ self._research_resources = research_resources @property def services(self): """Gets the services of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The services of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: ServicesV30Rc2 """ return self._services @services.setter def services(self, services): """Sets the services of this ActivitiesSummaryV30Rc2. :param services: The services of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: ServicesV30Rc2 """ self._services = services @property def works(self): """Gets the works of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The works of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: WorksSummaryV30Rc2 """ return self._works @works.setter def works(self, works): """Sets the works of this ActivitiesSummaryV30Rc2. :param works: The works of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: WorksSummaryV30Rc2 """ self._works = works @property def path(self): """Gets the path of this ActivitiesSummaryV30Rc2. # noqa: E501 :return: The path of this ActivitiesSummaryV30Rc2. # noqa: E501 :rtype: str """ return self._path @path.setter def path(self, path): """Sets the path of this ActivitiesSummaryV30Rc2. :param path: The path of this ActivitiesSummaryV30Rc2. # noqa: E501 :type: str """ self._path = path def to_dict(self): """Returns the model properties as a dict""" result = {} for attr, _ in six.iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value if issubclass(ActivitiesSummaryV30Rc2, dict): for key, value in self.items(): result[key] = value return result def to_str(self): """Returns the string representation of the model""" return pprint.pformat(self.to_dict()) def __repr__(self): """For `print` and `pprint`""" return self.to_str() def __eq__(self, other): """Returns true if both objects are equal""" if not isinstance(other, ActivitiesSummaryV30Rc2): return False return self.__dict__ == other.__dict__ def __ne__(self, other): """Returns true if both objects are not equal""" return not self == other
mit
stevebauman/maintenance
resources/views/emails/auth/password.blade.php
1319
@extends('orchestra/foundation::emails.layouts.action') @set_meta('title', 'Password Reset') @section('content') <table width="100%" cellpadding="0" cellspacing="0"> <tr> <td class="content-block aligncenter"> <h2>Password Reset</h2> </td> </tr> <tr> <td class="content-block"> To reset your password, complete this form: </td> </tr> <tr> <td class="content-block" itemprop="handler" itemscope itemtype="http://schema.org/HttpActionHandler"> <a href="{{ handles("orchestra::forgot/reset/{$token}") }}" class="btn-primary" itemprop="url">Reset Your Password</a> </td> </tr> <tr> <td class="content-block"> This link will expire in {{ config('auth.passwords.'.config('auth.defaults.passwords', 'users').'.expire', 60) }} minutes. </td> </tr> <tr> <td class="content-block"> &mdash; {{ memorize('site.name') }} </td> </tr> </table> @endsection @section('footer') <table width="100%"> <tr> <td class="aligncenter content-block"></td> </tr> </table> @overwrite
mit
aaroncox1234/NavMesh2
Assets/Scripts/Rx/EditablePolygon2.cs
3937
using UnityEngine; using System.Collections; public class EditablePolygon2 : MonoBehaviour { // todo: not public public Polygon2 polygon = new Polygon2(); protected int hoverVertexIndex = -1; protected int selectedVertexIndex = -1; protected const float sqVertexSelectionRange = 16.0f; protected Color vertexDrawColor = Color.grey; protected Color hoverVertexDrawColor = Color.grey; protected Color selectedVertexDrawColor = Color.white; protected Color edgeDrawColor = Color.grey; protected Color selectedEdgeDrawColor = Color.white; public Polygon2 GetCopyOfPolygon() { Polygon2 copy = new Polygon2(); foreach ( Vector2 vertex in polygon.Vertices ) { copy.vertices.Add( ToWorld2( vertex ) ); } return copy; } public void InsertVertex( Vector2 position ) { int index; if ( selectedVertexIndex != -1 ) { index = selectedVertexIndex + 1; } else { index = polygon.NumVertices; } polygon.InsertVertex( index, ToLocal2( position ) ); selectedVertexIndex = index; } public void DeleteSelectedVertex() { if ( selectedVertexIndex != -1 ) { polygon.RemoveVertex( selectedVertexIndex ); selectedVertexIndex = -1; } } public void SetSelectedVertexPosition( Vector2 position ) { if ( selectedVertexIndex != -1 ) { polygon.SetVertexPosition( selectedVertexIndex, ToLocal2( position ) ); } } public void UpdateHoverVertex( Vector2 mousePosition ) { hoverVertexIndex = polygon.IndexOfNearestVertex( ToLocal2( mousePosition ), sqVertexSelectionRange ); } public void UpdateSelectedVertex( Vector2 mousePosition ) { selectedVertexIndex = polygon.IndexOfNearestVertex( ToLocal2( mousePosition ), sqVertexSelectionRange ); } public void ReverseWinding() { selectedVertexIndex = polygon.NumVertices - selectedVertexIndex - 1; polygon.ReverseWinding(); } public virtual void OnDrawGizmosSelected() { if ( polygon.NumVertices >= 0 ) { DrawEdges(); DrawVertices(); } } private void DrawEdges() { Vector2 firstVertex = new Vector2( float.NaN, float.NaN ); Vector2 previousVertex = Vector2.zero; int index = 0; foreach ( Vector2 vertex in polygon.Vertices ) { if ( float.IsNaN( firstVertex.x ) ) { firstVertex = vertex; } else { Gizmos.color = edgeDrawColor; if ( ( index - 1 ) == selectedVertexIndex ) { Gizmos.color = selectedEdgeDrawColor; } Gizmos.DrawLine( ToWorld3( previousVertex ), ToWorld3( vertex ) ); } previousVertex = vertex; ++index; } if ( polygon.NumVertices >= 3 ) { Gizmos.color = edgeDrawColor; if ( ( index - 1 ) == selectedVertexIndex ) { Gizmos.color = selectedEdgeDrawColor; } Gizmos.DrawLine( ToWorld3( previousVertex ), ToWorld3( firstVertex ) ); } } private void DrawVertices() { Vector3 vertexDrawSize = new Vector3( 6.0f, 5.0f, 1.0f ); Vector3 selectedVertexDrawSize = new Vector3( 10.0f, 9.0f, 1.0f ); Vector3 drawSize; int index = 0; foreach ( Vector2 vertex in polygon.Vertices ) { if ( index == selectedVertexIndex ) { drawSize = selectedVertexDrawSize; Gizmos.color = selectedVertexDrawColor; } else if ( index == hoverVertexIndex ) { drawSize = selectedVertexDrawSize; Gizmos.color = hoverVertexDrawColor; } else { drawSize = vertexDrawSize; Gizmos.color = vertexDrawColor; } Gizmos.DrawCube( ToWorld3( vertex ), drawSize ); ++index; } } protected Vector2 ToLocal2( Vector2 worldPosition ) { return worldPosition - Helpers.AsVector2( transform.position ); } protected Vector2 ToWorld2( Vector2 localPosition ) { return localPosition + Helpers.AsVector2( transform.position ); } protected Vector3 ToWorld3( Vector2 localPosition ) { return Helpers.AsVector3( localPosition, 0.0f ) + transform.position; } }
mit
jamslatt/node_barcode
node_modules/realistic-structured-clone/test/test.js
5814
'use strict'; var assert = require('assert'); var structuredClone = require('..'); function assertSameEntries(xcontainer, ycontainer) { var x = xcontainer.entries(); var y = ycontainer.entries(); var xentry = x.next(); var yentry = y.next(); while (xentry.done === false) { assert.deepEqual(xentry.value[0], yentry.value[0]); assert.deepEqual(xentry.value[1], yentry.value[1]); xentry = x.next(); yentry = y.next(); } assert.equal(yentry.done, true); } function confirmContainerWorks(x) { var y = structuredClone(x); assertSameEntries(x, y); } describe('Valid Input', function () { var confirmWorks = function (x) { if (x !== x) { // Special case for NaN assert(structuredClone(x) !== structuredClone(x)); } else if (x instanceof RegExp) { var y = structuredClone(x); assert.equal(x.source, y.source); assert.equal(x.flags, y.flags); assert.equal(x.global, y.global); assert.equal(x.ignoreCase, y.ignoreCase); assert.equal(x.multiline, y.multiline); assert.equal(x.unicode, y.unicode); assert.equal(x.sticky, y.sticky); } else { assert.deepEqual(structuredClone(x), x); } }; it('Primitive Types', function () { confirmWorks('string'); confirmWorks(6); confirmWorks(NaN); confirmWorks(true); confirmWorks(undefined); confirmWorks(null); }); it('Date', function () { confirmWorks(new Date()); confirmWorks(new Date('2015-05-06T23:27:37.535Z')); }); it('RegExp', function () { confirmWorks(new RegExp('ab+c', 'i')); confirmWorks(/ab+c/i); confirmWorks(new RegExp('de+f', 'gm')); confirmWorks(new RegExp('gh.*i', 'yu')); }); it('ArrayBuffer', function () { var ab = new ArrayBuffer(5); var ab2 = structuredClone(ab); assertSameEntries(new Int8Array(ab), new Int8Array(ab2)); var shared = new ArrayBuffer(7); var obj = { wrapper1: new Uint8Array(shared), wrapper2: new Uint16Array(shared, 2, 2) }; obj.wrapper1[0] = 1; obj.wrapper2[1] = 0xffff; var obj2 = structuredClone(obj); assert(obj2.wrapper1.buffer === obj2.wrapper2.buffer); assertSameEntries(obj.wrapper1, obj2.wrapper1); confirmContainerWorks(new Int16Array(7)); confirmContainerWorks(new Int16Array(new ArrayBuffer(16), 2, 7)); confirmWorks(new DataView(new ArrayBuffer(16), 3, 13)); }); it('Array', function () { confirmContainerWorks([1, 2, 5, 3]); confirmContainerWorks(['a', 'g', 2, true, null]); }); it('Plain Object', function () { confirmWorks({ a: 1, b: 2, c: true, d: undefined, e: 'f' }); }); it('Map', function () { confirmContainerWorks(new Map([['a', 1], [{}, 2], [{}, 5], [0, 3]])); confirmContainerWorks(new Map()); }); it('Set', function () { confirmContainerWorks(new Set(['a', {}, {}, 0])); confirmContainerWorks(new Set()); }); it('Circular Reference', function () { var circular = []; circular.push(circular); // Can't use confirmWorks because deepEqual can't handle it var circular2 = structuredClone(circular); assert.equal(typeof circular, typeof circular2); assert.equal(circular.length, circular2.length); assert.equal(circular, circular[0]); assert.equal(circular2, circular2[0]); }); it('Big Nested Thing', function () { confirmWorks({ a: [1, 2, new Date()], b: { c: { d: 1, e: true, f: [1, 'a', undefined, {g: 6, h: 10}] } } }); }); it('getter', function () { var value; var obj = { get ref1() {return value;}, get ref2() {return value;} }; value = obj; assert.throws(function () { obj.ref1 = 1; }); assert.equal(obj, obj.ref1); assert.equal(obj, obj.ref2); var obj2 = structuredClone(obj); assert.equal(obj2, obj2.ref1); assert.equal(obj2, obj2.ref2); assert.doesNotThrow(function () { obj2.ref1 = 1; }); assert.equal(obj2.ref1, 1); assert.equal(obj2, obj2.ref2); }); /* disabled tests that don't pass yet it('POD class', function () { var MyClass = function () { this.x = 'x'; } confirmWorks(new MyClass()); }); it('class with method', function () { var MyClass = function () { this.x = 'y'; } MyClass.prototype = {method1() {}}; var obj = new MyClass(); assert.equal(typeof obj.method1, 'function'); confirmWorks(obj); }); */ }); describe('Invalid Input', function () { var confirmFails = function (x) { assert.throws(function () { structuredClone(x); }, /DataCloneError/); }; it('Function', function () { confirmFails(function () {}); }); it('Error', function () { confirmFails(new Error()); }); it('WeakMap', function () { confirmFails(new WeakMap()); }); it('WeakSet', function () { confirmFails(new WeakSet()); }); it('throwing getter', function () { var x = { get bad() {throw new RangeError();} }; assert.throws(function () { structuredClone(x); }, RangeError); }); });
mit
aitarget/aitarget-components
src/lib/components/targeting/targeting-form/geo/geo-dropdown/geo-dropdown.component.ts
2225
import { ChangeDetectionStrategy, ChangeDetectorRef, Component, EventEmitter, Input, OnChanges, OnDestroy, OnInit, Output } from '@angular/core'; import { GeoItem } from '../geo-item.interface'; import { Subject } from 'rxjs'; import { filter, mapTo, merge, takeUntil, tap } from 'rxjs/operators'; import { arrowDown$, arrowUp$, enter$ } from '../../../../../shared/constants/event-streams.constants'; @Component({ selector: 'app-geo-dropdown', templateUrl: 'geo-dropdown.component.html', styleUrls: ['geo-dropdown.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class GeoDropdownComponent implements OnInit, OnDestroy, OnChanges { destroy$ = new Subject(); @Input() items: GeoItem[]; @Input() isOpen; @Output() select = new EventEmitter(); activeItemIndex = 0; constructor (private changeDetectorRef: ChangeDetectorRef) { } ngOnChanges (changes) { if (changes.items.currentValue !== changes.items.previousValue || changes.isOpen.currentValue !== changes.isOpen.previousValue ) { this.activeItemIndex = 0; } this.changeDetectorRef.markForCheck(); this.changeDetectorRef.detectChanges(); } ngOnDestroy () { this.destroy$.next(); } ngOnInit () { arrowUp$ .pipe( takeUntil(this.destroy$), tap((e: KeyboardEvent) => e.preventDefault()), mapTo(-1), merge(arrowDown$ .pipe( tap((e: KeyboardEvent) => e.preventDefault()), mapTo(1) )), filter(() => this.isOpen) ) .subscribe((delta) => { this.activeItemIndex += delta; if (this.activeItemIndex < 0) { this.activeItemIndex = this.items.length - 1; } if (this.activeItemIndex > this.items.length - 1) { this.activeItemIndex = 0; } this.changeDetectorRef.markForCheck(); this.changeDetectorRef.detectChanges(); }); enter$ .pipe( takeUntil(this.destroy$), tap((e: KeyboardEvent) => e.preventDefault()), filter(() => this.isOpen) ) .subscribe(() => { this.select.emit(this.items[this.activeItemIndex]); }); } }
mit
appsngen/generator-appsngen-web-widget
app/templates/tests/specs/greeting.spec.js
1698
describe('Greeting module', function () { var widget = window.widget; it('sets correct number of greetings', function () { var uiMock = new widget.GreetingUI(); var prefsMock = { greeting: 'Hello, World!', numberOfGreetings: '3', changeColor: 'true', greetingCustomColor: '#FF0000' }; var target = new widget.Greeting({ ui: uiMock, prefs: prefsMock }); target.init(); expect(uiMock.setGreetings).toHaveBeenCalledWith([prefsMock.greeting, prefsMock.greeting, prefsMock.greeting]); }); it('sets custom greeting color', function () { var uiMock = new widget.GreetingUI(); var prefsMock = { greeting: 'Hello, World!', numberOfGreetings: '1', changeColor: 'true', greetingCustomColor: '#FF0000' }; var target = new widget.Greeting({ ui: uiMock, prefs: prefsMock }); target.init(); expect(uiMock.setGreetingsColor).toHaveBeenCalledWith(prefsMock.greetingCustomColor); }); it('doest\'t set custom greeting color', function () { var uiMock = new widget.GreetingUI(); var prefsMock = { greeting: 'Hello, World!', numberOfGreetings: '1', changeColor: 'false', greetingCustomColor: '#FF0000' }; var target = new widget.Greeting({ ui: uiMock, prefs: prefsMock }); uiMock.setGreetingsColor.calls.reset(); target.init(); expect(uiMock.setGreetingsColor).not.toHaveBeenCalled(); }); });
mit
jarib/rps
spec/rps/linux_process_spec.rb
1718
require "spec_helper" module RPS describe LinuxProcess do it "creates a process for each process in /proc" do Dir.stub!(:[]).with("/proc/*").and_return(["/proc/1", "/proc/2", "/proc/3", "/proc/uptime"]) procs = LinuxProcess.all procs.should be_instance_of(Array) procs.size.should == 3 procs.each { |proc| proc.should be_instance_of(LinuxProcess) } end it "returns the pid" do LinuxProcess.new("/proc/123").pid.should == 123 end it "returns the executable path" do File.stub!(:readlink).with("/proc/1/exe").and_return("/some/executable") LinuxProcess.new("/proc/1").exe.should == "/some/executable" end it "returns the command line" do File.stub!(:read).with("/proc/1/cmdline").and_return("ruby\000-e\000sleep\000") LinuxProcess.new("/proc/1").command_line.should == ["ruby", "-e", "sleep"] end it "knows if the process is a ruby process" do pe = LinuxProcess.new("/proc/1") pe.stub!(:exe).and_return "/path/to/ruby" pe.should be_ruby end it "knows if the process is not a ruby process" do pe = LinuxProcess.new("/proc/1") pe.stub!(:exe).and_return "/path/to/something else" pe.should_not be_ruby end it "knows if the process is readable" do File.should_receive(:readable?). with("/proc/1/exe"). and_return(true) pe = LinuxProcess.new("/proc/1") pe.should be_readable end it "knows if the process isn't readable" do File.should_receive(:readable?). with("/proc/1/exe"). and_return(false) pe = LinuxProcess.new("/proc/1") pe.should_not be_readable end end end
mit
conundrumer/musicpsych
test/spec/components/BipolarSlider.js
388
'use strict'; describe('BipolarSlider', function () { var React = require('react/addons'); var BipolarSlider, component; beforeEach(function () { BipolarSlider = require('components/BipolarSlider.js'); component = React.createElement(BipolarSlider); }); it('should create a new instance of BipolarSlider', function () { expect(component).toBeDefined(); }); });
mit
Azure/azure-sdk-for-python
sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_07_01/aio/operations/_vpn_connections_operations.py
22180
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is regenerated. # -------------------------------------------------------------------------- from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod from azure.mgmt.core.exceptions import ARMErrorFormat from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling from ... import models as _models T = TypeVar('T') ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]] class VpnConnectionsOperations: """VpnConnectionsOperations async operations. You should not instantiate this class directly. Instead, you should create a Client instance that instantiates it for you and attaches it as an attribute. :ivar models: Alias to model classes used in this operation group. :type models: ~azure.mgmt.network.v2019_07_01.models :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An object model deserializer. """ models = _models def __init__(self, client, config, serializer, deserializer) -> None: self._client = client self._serialize = serializer self._deserialize = deserializer self._config = config async def get( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs: Any ) -> "_models.VpnConnection": """Retrieves the details of a vpn connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the vpn connection. :type connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: VpnConnection, or the result of cls(response) :rtype: ~azure.mgmt.network.v2019_07_01.models.VpnConnection :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-07-01" accept = "application/json" # Construct URL url = self.get.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.get(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def _create_or_update_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs: Any ) -> "_models.VpnConnection": cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-07-01" content_type = kwargs.pop("content_type", "application/json") accept = "application/json" # Construct URL url = self._create_or_update_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str') header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') body_content_kwargs = {} # type: Dict[str, Any] body_content = self._serialize.body(vpn_connection_parameters, 'VpnConnection') body_content_kwargs['content'] = body_content request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 201]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if response.status_code == 200: deserialized = self._deserialize('VpnConnection', pipeline_response) if response.status_code == 201: deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized _create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def begin_create_or_update( self, resource_group_name: str, gateway_name: str, connection_name: str, vpn_connection_parameters: "_models.VpnConnection", **kwargs: Any ) -> AsyncLROPoller["_models.VpnConnection"]: """Creates a vpn connection to a scalable vpn gateway if it doesn't exist else updates the existing connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the connection. :type connection_name: str :param vpn_connection_parameters: Parameters supplied to create or Update a VPN Connection. :type vpn_connection_parameters: ~azure.mgmt.network.v2019_07_01.models.VpnConnection :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either VpnConnection or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2019_07_01.models.VpnConnection] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType["_models.VpnConnection"] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._create_or_update_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, vpn_connection_parameters=vpn_connection_parameters, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): deserialized = self._deserialize('VpnConnection', pipeline_response) if cls: return cls(pipeline_response, deserialized, {}) return deserialized path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def _delete_initial( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs: Any ) -> None: cls = kwargs.pop('cls', None) # type: ClsType[None] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-07-01" accept = "application/json" # Construct URL url = self._delete_initial.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') request = self._client.delete(url, query_parameters, header_parameters) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200, 202, 204]: map_error(status_code=response.status_code, response=response, error_map=error_map) error = self._deserialize.failsafe_deserialize(_models.Error, response) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) if cls: return cls(pipeline_response, None, {}) _delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore async def begin_delete( self, resource_group_name: str, gateway_name: str, connection_name: str, **kwargs: Any ) -> AsyncLROPoller[None]: """Deletes a vpn connection. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :param connection_name: The name of the connection. :type connection_name: str :keyword callable cls: A custom type or function that will be passed the direct response :keyword str continuation_token: A continuation token to restart a poller from a saved state. :keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for this operation to not poll, or pass in your own initialized polling object for a personal polling strategy. :paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod :keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present. :return: An instance of AsyncLROPoller that returns either None or the result of cls(response) :rtype: ~azure.core.polling.AsyncLROPoller[None] :raises ~azure.core.exceptions.HttpResponseError: """ polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod] cls = kwargs.pop('cls', None) # type: ClsType[None] lro_delay = kwargs.pop( 'polling_interval', self._config.polling_interval ) cont_token = kwargs.pop('continuation_token', None) # type: Optional[str] if cont_token is None: raw_result = await self._delete_initial( resource_group_name=resource_group_name, gateway_name=gateway_name, connection_name=connection_name, cls=lambda x,y,z: x, **kwargs ) kwargs.pop('error_map', None) kwargs.pop('content_type', None) def get_long_running_output(pipeline_response): if cls: return cls(pipeline_response, None, {}) path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), 'connectionName': self._serialize.url("connection_name", connection_name, 'str'), } if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs) elif polling is False: polling_method = AsyncNoPolling() else: polling_method = polling if cont_token: return AsyncLROPoller.from_continuation_token( polling_method=polling_method, continuation_token=cont_token, client=self._client, deserialization_callback=get_long_running_output ) else: return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method) begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections/{connectionName}'} # type: ignore def list_by_vpn_gateway( self, resource_group_name: str, gateway_name: str, **kwargs: Any ) -> AsyncIterable["_models.ListVpnConnectionsResult"]: """Retrieves all vpn connections for a particular virtual wan vpn gateway. :param resource_group_name: The resource group name of the VpnGateway. :type resource_group_name: str :param gateway_name: The name of the gateway. :type gateway_name: str :keyword callable cls: A custom type or function that will be passed the direct response :return: An iterator like instance of either ListVpnConnectionsResult or the result of cls(response) :rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2019_07_01.models.ListVpnConnectionsResult] :raises: ~azure.core.exceptions.HttpResponseError """ cls = kwargs.pop('cls', None) # type: ClsType["_models.ListVpnConnectionsResult"] error_map = { 401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError } error_map.update(kwargs.pop('error_map', {})) api_version = "2019-07-01" accept = "application/json" def prepare_request(next_link=None): # Construct headers header_parameters = {} # type: Dict[str, Any] header_parameters['Accept'] = self._serialize.header("accept", accept, 'str') if not next_link: # Construct URL url = self.list_by_vpn_gateway.metadata['url'] # type: ignore path_format_arguments = { 'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'), 'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'), 'gatewayName': self._serialize.url("gateway_name", gateway_name, 'str'), } url = self._client.format_url(url, **path_format_arguments) # Construct parameters query_parameters = {} # type: Dict[str, Any] query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str') request = self._client.get(url, query_parameters, header_parameters) else: url = next_link query_parameters = {} # type: Dict[str, Any] request = self._client.get(url, query_parameters, header_parameters) return request async def extract_data(pipeline_response): deserialized = self._deserialize('ListVpnConnectionsResult', pipeline_response) list_of_elem = deserialized.value if cls: list_of_elem = cls(list_of_elem) return deserialized.next_link or None, AsyncList(list_of_elem) async def get_next(next_link=None): request = prepare_request(next_link) pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs) response = pipeline_response.http_response if response.status_code not in [200]: error = self._deserialize.failsafe_deserialize(_models.Error, response) map_error(status_code=response.status_code, response=response, error_map=error_map) raise HttpResponseError(response=response, model=error, error_format=ARMErrorFormat) return pipeline_response return AsyncItemPaged( get_next, extract_data ) list_by_vpn_gateway.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/vpnGateways/{gatewayName}/vpnConnections'} # type: ignore
mit
Morwenn/cpp-sort
tests/adapters/every_adapter_internal_compare.cpp
4921
/* * Copyright (c) 2017-2022 Morwenn * SPDX-License-Identifier: MIT */ #include <algorithm> #include <functional> #include <iterator> #include <vector> #include <catch2/catch_test_macros.hpp> #include <cpp-sort/adapters.h> #include <cpp-sort/fixed_sorters.h> #include <cpp-sort/sorters/merge_sorter.h> #include <cpp-sort/sorters/poplar_sorter.h> #include <cpp-sort/sorters/selection_sorter.h> #include <testing-tools/algorithm.h> #include <testing-tools/distributions.h> #include <testing-tools/internal_compare.h> TEST_CASE( "test most adapters with a pointer to member function comparison", "[adapters][as_function]" ) { std::vector<internal_compare<int>> collection; collection.reserve(65); auto distribution = dist::shuffled{}; distribution(std::back_inserter(collection), 65, 0); SECTION( "counting_adapter" ) { using sorter = cppsort::counting_adapter< cppsort::selection_sorter >; // Sort and check it's sorted std::size_t res = sorter{}(collection, &internal_compare<int>::compare_to); CHECK( res == 2080 ); CHECK( std::is_sorted(collection.begin(), collection.end()) ); } SECTION( "hybrid_adapter" ) { using sorter = cppsort::hybrid_adapter< cppsort::merge_sorter, cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); } SECTION( "indirect_adapter" ) { using sorter = cppsort::indirect_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); } SECTION( "out_of_place_adapter" ) { using sorter = cppsort::out_of_place_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); std::list<internal_compare<int>> li; distribution(std::back_inserter(li), 65, 0); sorter{}(li, &internal_compare<int>::compare_to); CHECK( std::is_sorted(li.begin(), li.end()) ); } SECTION( "schwartz_adapter" ) { using sorter = cppsort::schwartz_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to, std::negate<>{}); CHECK( std::is_sorted(collection.begin(), collection.end(), std::greater<>{}) ); } SECTION( "self_sort_adapter" ) { using sorter = cppsort::self_sort_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); std::list<internal_compare<int>> li; distribution(std::back_inserter(li), 65, 0); sorter{}(li, &internal_compare<int>::compare_to); CHECK( std::is_sorted(li.begin(), li.end()) ); } SECTION( "stable_adapter<self_sort_adapter>" ) { using sorter = cppsort::stable_adapter< cppsort::self_sort_adapter<cppsort::poplar_sorter> >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); std::list<internal_compare<int>> li; distribution(std::back_inserter(li), 65, 0); sorter{}(li, &internal_compare<int>::compare_to); CHECK( std::is_sorted(li.begin(), li.end()) ); } SECTION( "small_array_adapter" ) { using namespace cppsort; std::array<internal_compare<int>, 6> arr = {{ {4}, {3}, {2}, {5}, {6}, {1} }}; auto to_sort = arr; small_array_adapter<low_comparisons_sorter>{}(to_sort, &internal_compare<int>::compare_to); CHECK( std::is_sorted(to_sort.begin(), to_sort.end()) ); to_sort = arr; small_array_adapter<low_moves_sorter>{}(to_sort, &internal_compare<int>::compare_to); CHECK( std::is_sorted(to_sort.begin(), to_sort.end()) ); to_sort = arr; small_array_adapter<sorting_network_sorter>{}(to_sort, &internal_compare<int>::compare_to); CHECK( std::is_sorted(to_sort.begin(), to_sort.end()) ); } SECTION( "stable_adapter" ) { using sorter = cppsort::stable_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); } SECTION( "verge_adapter" ) { using sorter = cppsort::verge_adapter< cppsort::poplar_sorter >; sorter{}(collection, &internal_compare<int>::compare_to); CHECK( std::is_sorted(collection.begin(), collection.end()) ); } }
mit
Widdershin/katana
katas/odd_indexed_integers.rb
239
# Tags: ruby, maths, array, each_with_index # Write a method to return the elements at odd indices i.e. 1, 3, 5, 7, etc. in an array def odd_indexed_integers(array) end Assert.equal([4,8,12], odd_indexed_integers([2, 4, 6, 8, 10, 12]))
mit
wieslawsoltes/Draw2D
src/Draw2D/ViewModels/Tools/PathTool.cs
16770
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Core2D.UI.Zoom.Input; using Draw2D.ViewModels.Containers; using Draw2D.ViewModels.Shapes; using Draw2D.ViewModels.Style; namespace Draw2D.ViewModels.Tools { internal class FigureContainerView : IContainerView { internal IToolContext _context; internal PathTool _pathTool; internal IPointShape _nextPoint; public FigureContainerView(IToolContext context, PathTool pathTool) { _context = context; _pathTool = pathTool; } public string Title { get => _context.DocumentContainer.ContainerView.Title; set => throw new InvalidOperationException($"Can not set {Title} property value."); } public double Width { get => _context.DocumentContainer.ContainerView.Width; set => throw new InvalidOperationException($"Can not set {Width} property value."); } public double Height { get => _context.DocumentContainer.ContainerView.Width; set => throw new InvalidOperationException($"Can not set {Height} property value."); } public IPaint PrintBackground { get => _context.DocumentContainer.ContainerView.PrintBackground; set => throw new InvalidOperationException($"Can not set {PrintBackground} property value."); } public IPaint WorkBackground { get => _context.DocumentContainer.ContainerView.WorkBackground; set => throw new InvalidOperationException($"Can not set {WorkBackground} property value."); } public IPaint InputBackground { get => _context.DocumentContainer.ContainerView.InputBackground; set => throw new InvalidOperationException($"Can not set {InputBackground} property value."); } public ICanvasContainer CurrentContainer { get => _pathTool._figure; set => throw new InvalidOperationException($"Can not set {CurrentContainer} property value."); } public ICanvasContainer WorkingContainer { get => _pathTool._figure; set => throw new InvalidOperationException($"Can not set {WorkingContainer} property value."); } public IContainerPresenter ContainerPresenter { get => _context.DocumentContainer.ContainerView.ContainerPresenter; set => throw new InvalidOperationException($"Can not set {ContainerPresenter} property value."); } public ISelectionState SelectionState { get => _context.DocumentContainer.ContainerView.SelectionState; set => throw new InvalidOperationException($"Can not set {SelectionState} property value."); } public IZoomServiceState ZoomServiceState { get => _context.DocumentContainer.ContainerView.ZoomServiceState; set => throw new InvalidOperationException($"Can not set {ZoomServiceState} property value."); } public IInputService InputService { get => _context.DocumentContainer.ContainerView?.InputService; set => throw new InvalidOperationException($"Can not set {InputService} property value."); } public IZoomService ZoomService { get => _context.DocumentContainer.ContainerView.ZoomService; set => throw new InvalidOperationException($"Can not set {ZoomService} property value."); } public IPointShape GetNextPoint(IToolContext context, double x, double y, bool connect, double radius, double scale, Modifier modifier) { if (_nextPoint != null) { var nextPointTemp = _nextPoint; _nextPoint = null; return nextPointTemp; } return _context.DocumentContainer.ContainerView.GetNextPoint(_context, x, y, connect, radius, scale, modifier); } public void Draw(object context, double width, double height, double dx, double dy, double zx, double zy, double renderScaling) { _context.DocumentContainer.ContainerView.Draw(context, width, height, dx, dy, zx, zy, renderScaling); } public void Add(IBaseShape shape) { _context.DocumentContainer.ContainerView.Add(shape); } public void Remove(IBaseShape shape) { _context.DocumentContainer.ContainerView.Remove(shape); } public void Reference(IBaseShape shape) { _context.DocumentContainer.ContainerView.Reference(shape); } public void Style(string styleId) { _context.DocumentContainer.ContainerView.Style(styleId); } public object Copy(Dictionary<object, object> shared) { return null; } } [DataContract(IsReference = true)] public class FigureDocumentContainer : IDocumentContainer { internal IToolContext _context; internal PathTool _pathTool; public FigureDocumentContainer(IToolContext context, PathTool pathTool) { _context = context; _pathTool = pathTool; } public string Title { get => _context.DocumentContainer.Title; set => throw new InvalidOperationException($"Can not set {Title} property value."); } public IStyleLibrary StyleLibrary { get => _context.DocumentContainer.StyleLibrary; set => throw new InvalidOperationException($"Can not set {StyleLibrary} property value."); } public IGroupLibrary GroupLibrary { get => _context.DocumentContainer.GroupLibrary; set => throw new InvalidOperationException($"Can not set {GroupLibrary} property value."); } public IBaseShape PointTemplate { get => _context.DocumentContainer.PointTemplate; set => throw new InvalidOperationException($"Can not set {PointTemplate} property value."); } public IList<IContainerView> ContainerViews { get => _context.DocumentContainer.ContainerViews; set => throw new InvalidOperationException($"Can not set {ContainerViews} property value."); } public IContainerView ContainerView { get => _pathTool._containerView; set => throw new InvalidOperationException($"Can not set {ContainerView} property value."); } public void Dispose() { } public virtual object Copy(Dictionary<object, object> shared) { return null; } } public partial class PathTool : IToolContext { internal IToolContext _context; internal FigureContainerView _containerView; internal FigureDocumentContainer _documentContainer; [IgnoreDataMember] public IDocumentContainer DocumentContainer { get => _documentContainer; set => throw new InvalidOperationException($"Can not set {DocumentContainer} property value."); } [IgnoreDataMember] public IHitTest HitTest { get => _context.HitTest; set => throw new InvalidOperationException($"Can not set {HitTest} property value."); } [IgnoreDataMember] public IPathConverter PathConverter { get => _context.PathConverter; set => throw new InvalidOperationException($"Can not set {PathConverter} property value."); } [IgnoreDataMember] public IList<ITool> Tools { get => _context.Tools; set => throw new InvalidOperationException($"Can not set {Tools} property value."); } [IgnoreDataMember] public ITool CurrentTool { get => _context.CurrentTool; set => throw new InvalidOperationException($"Can not set {CurrentTool} property value."); } [IgnoreDataMember] public EditMode EditMode { get => _context.EditMode; set => throw new InvalidOperationException($"Can not set {EditMode} property value."); } public void Dispose() { } private void SetNextPoint(IPointShape point) => _containerView._nextPoint = point; private void SetContext(IToolContext context) => _context = context; public void SetTool(string title) => _context.SetTool(title); public double GetWidth() => _context.GetWidth(); public double GetHeight() => _context.GetHeight(); public void LeftDown(double x, double y, Modifier modifier) => _context.LeftDown(x, y, modifier); public void LeftUp(double x, double y, Modifier modifier) => _context.LeftUp(x, y, modifier); public void RightDown(double x, double y, Modifier modifier) => _context.RightDown(x, y, modifier); public void RightUp(double x, double y, Modifier modifier) => _context.RightUp(x, y, modifier); public void Move(double x, double y, Modifier modifier) => _context.Move(x, y, modifier); } [DataContract(IsReference = true)] public partial class PathTool : BaseTool, ITool { private PathToolSettings _settings; internal PathShape _path; internal FigureShape _figure; [IgnoreDataMember] public new string Title => "Path"; [DataMember(IsRequired = false, EmitDefaultValue = false)] public PathToolSettings Settings { get => _settings; set => Update(ref _settings, value); } internal void Create(IToolContext context) { if (_containerView == null) { _containerView = new FigureContainerView(context, this); } if (_documentContainer == null) { _documentContainer = new FigureDocumentContainer(context, this); } _path = new PathShape() { Points = new ObservableCollection<IPointShape>(), Shapes = new ObservableCollection<IBaseShape>(), FillType = Settings.FillType, Text = new Text(), StyleId = context.DocumentContainer?.StyleLibrary?.CurrentItem?.Title }; context.DocumentContainer?.ContainerView?.WorkingContainer.Shapes.Add(_path); context.DocumentContainer?.ContainerView?.WorkingContainer.MarkAsDirty(true); context.DocumentContainer?.ContainerView?.SelectionState?.Select(_path); } internal void Move(IToolContext context) { _figure = new FigureShape() { Points = new ObservableCollection<IPointShape>(), Shapes = new ObservableCollection<IBaseShape>(), IsFilled = Settings.IsFilled, IsClosed = Settings.IsClosed }; _figure.Owner = _path; _path.Shapes.Add(_figure); context.DocumentContainer?.ContainerView?.WorkingContainer.MarkAsDirty(true); if (Settings.PreviousTool != null) { Settings.CurrentTool = Settings.PreviousTool; } } internal void CleanCurrentTool(IToolContext context) { SetContext(context); Settings.CurrentTool?.Clean(this); SetContext(null); } internal void UpdateCache(IToolContext context) { if (_path != null) { _figure.MarkAsDirty(true); _figure.MarkAsDirty(true); } } private void DownInternal(IToolContext context, double x, double y, Modifier modifier) { FiltersProcess(context, ref x, ref y); if (_path == null) { Create(context); Move(context); } SetContext(context); Settings.CurrentTool?.LeftDown(this, x, y, modifier); switch (Settings.CurrentTool) { case LineTool lineTool: { if (lineTool.CurrentState == LineTool.State.StartPoint) { SetNextPoint(_path?.GetLastPoint()); Settings.CurrentTool?.LeftDown(this, x, y, modifier); SetNextPoint(null); } } break; case CubicBezierTool cubicBezierTool: { if (cubicBezierTool.CurrentState == CubicBezierTool.State.StartPoint) { SetNextPoint(_path?.GetLastPoint()); Settings.CurrentTool?.LeftDown(this, x, y, modifier); SetNextPoint(null); } } break; case QuadraticBezierTool quadraticBezierTool: { if (quadraticBezierTool.CurrentState == QuadraticBezierTool.State.StartPoint) { SetNextPoint(_path?.GetLastPoint()); Settings.CurrentTool?.LeftDown(this, x, y, modifier); SetNextPoint(null); } } break; case ConicTool conicTool: { if (conicTool.CurrentState == ConicTool.State.StartPoint) { SetNextPoint(_path?.GetLastPoint()); Settings.CurrentTool?.LeftDown(this, x, y, modifier); SetNextPoint(null); } } break; } SetContext(null); } private void MoveInternal(IToolContext context, double x, double y, Modifier modifier) { FiltersClear(context); FiltersProcess(context, ref x, ref y); if (_containerView == null) { _containerView = new FigureContainerView(context, this); } if (_documentContainer == null) { _documentContainer = new FigureDocumentContainer(context, this); } SetContext(context); Settings.CurrentTool.Move(this, x, y, modifier); SetContext(null); } private void CleanInternal(IToolContext context) { CleanCurrentTool(context); FiltersClear(context); if (_path != null) { context.DocumentContainer?.ContainerView?.WorkingContainer.Shapes.Remove(_path); context.DocumentContainer?.ContainerView?.WorkingContainer.MarkAsDirty(true); context.DocumentContainer?.ContainerView?.SelectionState?.Deselect(_path); if (_path.Validate(true) == true) { context.DocumentContainer?.ContainerView?.CurrentContainer.Shapes.Add(_path); context.DocumentContainer?.ContainerView?.CurrentContainer.MarkAsDirty(true); } Settings.PreviousTool = null; SetNextPoint(null); SetContext(null); _path = null; _figure = null; _containerView = null; _documentContainer = null; } } public void LeftDown(IToolContext context, double x, double y, Modifier modifier) { DownInternal(context, x, y, modifier); } public void LeftUp(IToolContext context, double x, double y, Modifier modifier) { } public void RightDown(IToolContext context, double x, double y, Modifier modifier) { this.Clean(context); } public void RightUp(IToolContext context, double x, double y, Modifier modifier) { } public void Move(IToolContext context, double x, double y, Modifier modifier) { MoveInternal(context, x, y, modifier); } public void Clean(IToolContext context) { CleanInternal(context); } } }
mit
PHCNetworks/phc-scriptcdn
app/helpers/phcscriptcdn/script/listings_helper.rb
62
module Phcscriptcdn module Script::ListingsHelper end end
mit
RadoslavGYordanov/FMI-C-
Project2/main.cpp
545
#include <iostream> #include "date.h" int main() { //Use this when you want an array, but don't have a default constructor /*Date* arr[5]={NULL}; for(int i=0;i<5;i++) { int d,m,y; std::cin>>d>>m>>y; arr[i]=new Date(d,m,y); arr[i]->print(); } for(int i=0;i<5;i++) { delete arr[i]; } */ Date* arr=new Date[3]; delete[] arr; /* Date d; d.print(); Date d1(34,3,2017); d1.print(); */ return 0; }
mit
morontt/projecteuler-stat
src/Controller/Admin/SolutionController.php
5022
<?php /** * Created by PhpStorm. * User: morontt * Date: 05.06.16 * Time: 11:34 */ namespace MttProjecteuler\Controller\Admin; use Carbon\Carbon; use MttProjecteuler\Controller\BaseController; use MttProjecteuler\Model\Solution; use MttProjecteuler\Utils\Pygment; use Silex\Application; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpKernel\Exception\NotFoundHttpException; use Symfony\Component\Routing\Generator\UrlGeneratorInterface; class SolutionController extends BaseController { /** * @param Application $app * * @return string */ public function index(Application $app, $page) { $page = (int)$page; $entities = $app['pe_database.repository']->findAllSolutions($page); $countPages = $app['pe_database.repository']->getCountResults(); if ($page > $countPages) { throw new NotFoundHttpException(sprintf('WebController:index, page %d not found', $page)); } $urlRenerator = $app['url_generator']; $paginationMeta = $this->getPaginationMetadata($page, $countPages, function ($p) use ($urlRenerator) { return $urlRenerator->generate( 'admin_solutions_index', ['page' => $p], UrlGeneratorInterface::ABSOLUTE_PATH ); }); return $app['twig']->render('admin/solution/index.html.twig', compact('entities', 'paginationMeta')); } /** * @param Application $app * @param Request $request * * @return string|\Symfony\Component\HttpFoundation\RedirectResponse */ public function create(Application $app, Request $request) { $entity = new Solution(); $entity->setCreatedBy($app['user']->getId()); $form = $app['form.factory']->create( 'MttProjecteuler\Form\SolutionType', $entity, [ 'repository' => $app['pe_database.repository'], ] ); $form->handleRequest($request); if ($form->isValid()) { if ($form->get('generate')->getData() && $entity->getSourceLink()) { $lang = $app['pe_database.repository']->findLang((int)$entity->getLangId()); if ($lang && $lang->getLexer()) { $entity->setSourceHtml(Pygment::highlight($entity->getSourceLink(), $lang->getLexer())); } } $app['db']->insert('solutions', $entity->toArray()); $app['session']->getFlashBag()->add('success', 'Решение создано'); return $app->redirect($app['url_generator']->generate('admin_solutions_index')); } return $app['twig'] ->render( 'admin/solution/edit.html.twig', [ 'entity' => $entity, 'form' => $form->createView(), ] ); } /** * @param Application $app * @param Request $request * @param Solution $entity * * @return string|\Symfony\Component\HttpFoundation\RedirectResponse */ public function edit(Application $app, Request $request, Solution $entity) { $form = $app['form.factory']->create( 'MttProjecteuler\Form\SolutionType', $entity, [ 'repository' => $app['pe_database.repository'], ] ); $form->handleRequest($request); if ($form->isValid()) { $entity->setUpdatedAt(new Carbon()); if ($form->get('generate')->getData() && $entity->getSourceLink()) { $lang = $app['pe_database.repository']->findLang((int)$entity->getLangId()); if ($lang && $lang->getLexer()) { $entity->setSourceHtml(Pygment::highlight($entity->getSourceLink(), $lang->getLexer())); } } $app['db']->update('solutions', $entity->toArray(), ['id' => $entity->getId()]); $app['session']->getFlashBag()->add('success', sprintf('Решение ID: %s отредактировано', $entity->getId())); return $app->redirect($app['url_generator']->generate('admin_solutions_index')); } return $app['twig'] ->render( 'admin/solution/edit.html.twig', [ 'entity' => $entity, 'form' => $form->createView(), ] ); } /** * @param Application $app * @param Solution $entity * * @return \Symfony\Component\HttpFoundation\RedirectResponse */ public function delete(Application $app, Solution $entity) { $app['db']->delete('solutions', ['id' => $entity->getId()]); $app['session']->getFlashBag()->add('success', sprintf('Решение ID: %s удалено', $entity->getId())); return $app->redirect($app['url_generator']->generate('admin_solutions_index')); } }
mit
AkivaGreen/umasstransit.rodeo
app/assets/javascripts/scoreboard.js
883
$(document).ready(function(){ $('.scoreboard-sorting').on('click', 'button.scoreboard-order', function(){ $('img.scoreboard-sort-loading').removeClass('hidden'); $(this).removeClass('btn-secondary').addClass('btn-primary'); $(this).siblings('button').removeClass('btn-primary').addClass('btn-secondary'); var order = $(this).data('order'); $('.scoreboard-content').load('/participants/scoreboard_partial?sort_order=' + order, function(){ $('img.scoreboard-sort-loading').addClass('hidden'); }); }); $('.scoreboard').on('click', 'button.fullscreen', function(){ $('.scoreboard-content').get(0).webkitRequestFullscreen(); }); }); PrivatePub.subscribe('/scoreboard', function(){ var order = $('button.scoreboard-order.btn-primary').data('order'); $('.scoreboard-content').load('/participants/scoreboard_partial?sort_order=' + order); });
mit
wanelo/pause
lib/pause/configuration.rb
514
module Pause class Configuration attr_writer :redis_host, :redis_port, :redis_db, :resolution, :history, :sharded def configure yield self self end def redis_host @redis_host || '127.0.0.1' end def redis_port (@redis_port || 6379).to_i end def redis_db @redis_db || '1' end def resolution (@resolution || 600).to_i end def history (@history || 86400).to_i end def sharded !!@sharded end end end
mit
tonyxj/100daysofframer
39threeDHover.framer/framer/framer.generated.js
2881
// This is autogenerated by Framer if (!window.Framer && window._bridge) {window._bridge('runtime.error', {message:'[framer.js] Framer library missing or corrupt. Select File → Update Framer Library.'})} window.__imported__ = window.__imported__ || {}; window.__imported__["2001MovieAppleTV@1x/layers.json.js"] = [ { "objectId": "CFDFDAD0-0C21-4582-BD68-038672DD6CE6", "kind": "group", "name": "Group", "maskFrame": null, "layerFrame": { "x": 0, "y": 0, "width": 533, "height": 300 }, "visible": true, "metadata": { "opacity": 1 }, "children": [ { "objectId": "81DA87EE-A0F5-41E9-9579-1C86592C781C", "kind": "text", "name": "title", "maskFrame": null, "layerFrame": { "x": 58, "y": 230, "width": 429, "height": 27 }, "visible": true, "metadata": { "opacity": 1, "string": "2OO1: A SPACE ODYSSEY", "css": [ "/* 2OO1: A SPACE ODYSS: */", "font-family: GillSans-Light;", "font-size: 37.18px;", "color: #FFFFFF;", "letter-spacing: 0px;" ] }, "image": { "path": "images/Layer-title-odfeqtg3.png", "frame": { "x": 58, "y": 230, "width": 429, "height": 27 } }, "children": [], "time": 28 }, { "objectId": "E410839F-D3E4-433E-8460-BE3A92C024F4", "kind": "group", "name": "earth", "maskFrame": null, "layerFrame": { "x": 194, "y": 134, "width": 155, "height": 155 }, "visible": true, "metadata": { "opacity": 1 }, "image": { "path": "images/Layer-earth-rtqxmdgz.png", "frame": { "x": 194, "y": 134, "width": 155, "height": 155 } }, "children": [], "time": 28 }, { "objectId": "2460BA3D-581C-4080-B41D-B56C00A7DA82", "kind": "group", "name": "bg", "maskFrame": null, "layerFrame": { "x": 0, "y": 0, "width": 533, "height": 300 }, "visible": true, "metadata": { "opacity": 1 }, "image": { "path": "images/Layer-bg-mjq2mejb.png", "frame": { "x": 0, "y": 0, "width": 533, "height": 300 } }, "children": [], "time": 81 } ], "time": 163 } ] if (DeviceComponent) {DeviceComponent.Devices["iphone-6-silver"].deviceImageJP2 = false}; if (window.Framer) {window.Framer.Defaults.DeviceView = {"deviceScale":1,"selectedHand":"","deviceType":"fullscreen","contentScale":1,"orientation":0}; } if (window.Framer) {window.Framer.Defaults.DeviceComponent = {"deviceScale":1,"selectedHand":"","deviceType":"fullscreen","contentScale":1,"orientation":0}; } window.FramerStudioInfo = {"deviceImagesUrl":"\/_server\/resources\/DeviceImages","documentTitle":"39threeDHover.framer"}; Framer.Device = new Framer.DeviceView(); Framer.Device.setupContext();
mit
outdoorsy/cache
cache_test.go
4742
package cache import ( "errors" "sync" "testing" "time" "github.com/tylerb/is" ) func TestCacheSetGet(t *testing.T) { is := is.New(t) key := "key" val := "val" encodedVal := `"val"` mock := NewMock(false) c, err := NewClient(128, mock) is.NotErr(err) defer c.Close() // Test count functionality count := c.GetCount() is.Equal(count.Local, 0) is.Equal(count.Remote, 0) c.Set(key, val) time.Sleep(100 * time.Millisecond) var out string err = c.Get(key, &out) is.NotErr(err) is.Equal(out, val) exists, err := c.Exists(key) is.True(exists) is.NotErr(err) // Explicitly ensure it is set in each cache v, ok := c.cache.Get(key) is.True(ok) is.NotZero(v) b, err := mock.Get(key) is.NotNil(b) is.NotErr(err) is.NotZero(b) is.Equal(string(b), encodedVal) // Test count functionality count = c.GetCount() is.Equal(count.Local, 1) is.Equal(count.Remote, 1) } func TestCacheMissing(t *testing.T) { is := is.New(t) mock := NewMock(false) c, err := NewClient(128, mock) is.NotErr(err) defer c.Close() var out string err = c.Get("nope", &out) is.Equal(err, ErrNotFound) is.Zero(out) exists, err := c.Exists("nope") is.False(exists) is.NotErr(err) } func TestCachePopulateMissing(t *testing.T) { is := is.New(t) key := "key" val := "val" encodedVal := `"val"` mock := NewMock(false) c, err := NewClient(128, mock) is.NotErr(err) defer c.Close() c.Set(key, val) time.Sleep(100 * time.Millisecond) var out string err = c.Get(key, &out) is.NotErr(err) is.Equal(out, val) // Now delete "key" from the in-memory cache c.cache.Remove(key) is.Zero(c.cache.Len()) // Ensure it exists in the remote cache b, err := mock.Get(key) is.NotErr(err) is.Equal(string(b), encodedVal) // Fetch it again err = c.Get(key, &out) is.NotErr(err) is.Equal(out, val) // Ensure that it was populated to the local cache from the remote cache is.Equal(c.cache.Len(), 1) // Explicitly ensure it is set in each cache v, ok := c.cache.Get(key) is.True(ok) is.NotZero(v) b, err = mock.Get(key) is.NotNil(b) is.NotErr(err) is.NotZero(b) is.Equal(string(b), encodedVal) } // ─────────────────────────────────────────────────────────────────────────── // Mock implementation for testing remote storage // ─────────────────────────────────────────────────────────────────────────── type mockCache struct { shouldFail bool cache sync.Map updater Updater wg sync.WaitGroup stop chan struct{} } // NewMock creates a mock Backer implementation using a simple in-memory thread-safe // storage. func NewMock(shouldFail bool) Backer { return &mockCache{shouldFail: shouldFail, stop: make(chan struct{})} } func (m *mockCache) SetUpdater(updater Updater) { m.updater = updater } // StartMonitor does not monitor keys for the mockCache. It does properly handle // the signals, so you can block on it. func (m *mockCache) StartMonitor() error { m.wg.Add(1) go func() { <-m.stop m.wg.Done() }() return nil } // Close closes the mock Backer, shutting down any background processes and blocking // until shutdown is complete. func (m *mockCache) Close() { close(m.stop) m.wg.Wait() } // Set sets a value. func (m *mockCache) SetExpires(key string, value interface{}, expires time.Duration) error { if m.shouldFail { return errors.New("mock created to fail") } m.cache.Store(key, value) return nil } // This is a no-op for the mock cache func (m *mockCache) UpdateExpiration(key string, expires time.Duration) error { if m.shouldFail { return errors.New("mock created to fail") } return nil } // Get gets a value. func (m *mockCache) Get(key string) ([]byte, error) { v, ok := m.cache.Load(key) if !ok { return nil, ErrNotFound } switch conv := v.(type) { case []byte: return conv, nil case string: return []byte(conv), nil default: return nil, nil } } // Delete deletes a value. func (m *mockCache) Delete(key string) error { m.cache.Delete(key) return nil } // Exists checks if the key exists. func (m *mockCache) Exists(key string) (bool, error) { _, ok := m.cache.Load(key) if !ok { return false, nil } return true, nil } // GetCount returns the number of items in the cache func (m *mockCache) GetCount() (int, error) { length := 0 m.cache.Range(func(_, _ interface{}) bool { length++ return true }) return length, nil } // Health is a no-op func (m *mockCache) Health() error { return nil }
mit
goodwinxp/Yorozuya
YorozuyaGSLib/source/RACE_BOSS_MSG__CMsgListDetail.cpp
18627
#include <RACE_BOSS_MSG__CMsgListDetail.hpp> #include <common/ATFCore.hpp> START_ATF_NAMESPACE namespace RACE_BOSS_MSG { namespace Detail { Info::RACE_BOSS_MSG__CMsgListAddEmpty2_ptr RACE_BOSS_MSG__CMsgListAddEmpty2_next(nullptr); Info::RACE_BOSS_MSG__CMsgListAddEmpty2_clbk RACE_BOSS_MSG__CMsgListAddEmpty2_user(nullptr); Info::RACE_BOSS_MSG__CMsgListAddUse4_ptr RACE_BOSS_MSG__CMsgListAddUse4_next(nullptr); Info::RACE_BOSS_MSG__CMsgListAddUse4_clbk RACE_BOSS_MSG__CMsgListAddUse4_user(nullptr); Info::RACE_BOSS_MSG__CMsgListctor_CMsgList6_ptr RACE_BOSS_MSG__CMsgListctor_CMsgList6_next(nullptr); Info::RACE_BOSS_MSG__CMsgListctor_CMsgList6_clbk RACE_BOSS_MSG__CMsgListctor_CMsgList6_user(nullptr); Info::RACE_BOSS_MSG__CMsgListCancel8_ptr RACE_BOSS_MSG__CMsgListCancel8_next(nullptr); Info::RACE_BOSS_MSG__CMsgListCancel8_clbk RACE_BOSS_MSG__CMsgListCancel8_user(nullptr); Info::RACE_BOSS_MSG__CMsgListCleanUp10_ptr RACE_BOSS_MSG__CMsgListCleanUp10_next(nullptr); Info::RACE_BOSS_MSG__CMsgListCleanUp10_clbk RACE_BOSS_MSG__CMsgListCleanUp10_user(nullptr); Info::RACE_BOSS_MSG__CMsgListGetEmpty12_ptr RACE_BOSS_MSG__CMsgListGetEmpty12_next(nullptr); Info::RACE_BOSS_MSG__CMsgListGetEmpty12_clbk RACE_BOSS_MSG__CMsgListGetEmpty12_user(nullptr); Info::RACE_BOSS_MSG__CMsgListGetRemainCnt14_ptr RACE_BOSS_MSG__CMsgListGetRemainCnt14_next(nullptr); Info::RACE_BOSS_MSG__CMsgListGetRemainCnt14_clbk RACE_BOSS_MSG__CMsgListGetRemainCnt14_user(nullptr); Info::RACE_BOSS_MSG__CMsgListGetSendMsg16_ptr RACE_BOSS_MSG__CMsgListGetSendMsg16_next(nullptr); Info::RACE_BOSS_MSG__CMsgListGetSendMsg16_clbk RACE_BOSS_MSG__CMsgListGetSendMsg16_user(nullptr); Info::RACE_BOSS_MSG__CMsgListInit18_ptr RACE_BOSS_MSG__CMsgListInit18_next(nullptr); Info::RACE_BOSS_MSG__CMsgListInit18_clbk RACE_BOSS_MSG__CMsgListInit18_user(nullptr); Info::RACE_BOSS_MSG__CMsgListLoad20_ptr RACE_BOSS_MSG__CMsgListLoad20_next(nullptr); Info::RACE_BOSS_MSG__CMsgListLoad20_clbk RACE_BOSS_MSG__CMsgListLoad20_user(nullptr); Info::RACE_BOSS_MSG__CMsgListLoadIndexList22_ptr RACE_BOSS_MSG__CMsgListLoadIndexList22_next(nullptr); Info::RACE_BOSS_MSG__CMsgListLoadIndexList22_clbk RACE_BOSS_MSG__CMsgListLoadIndexList22_user(nullptr); Info::RACE_BOSS_MSG__CMsgListLoadMsgList24_ptr RACE_BOSS_MSG__CMsgListLoadMsgList24_next(nullptr); Info::RACE_BOSS_MSG__CMsgListLoadMsgList24_clbk RACE_BOSS_MSG__CMsgListLoadMsgList24_user(nullptr); Info::RACE_BOSS_MSG__CMsgListRefresh26_ptr RACE_BOSS_MSG__CMsgListRefresh26_next(nullptr); Info::RACE_BOSS_MSG__CMsgListRefresh26_clbk RACE_BOSS_MSG__CMsgListRefresh26_user(nullptr); Info::RACE_BOSS_MSG__CMsgListRelease28_ptr RACE_BOSS_MSG__CMsgListRelease28_next(nullptr); Info::RACE_BOSS_MSG__CMsgListRelease28_clbk RACE_BOSS_MSG__CMsgListRelease28_user(nullptr); Info::RACE_BOSS_MSG__CMsgListRollBack30_ptr RACE_BOSS_MSG__CMsgListRollBack30_next(nullptr); Info::RACE_BOSS_MSG__CMsgListRollBack30_clbk RACE_BOSS_MSG__CMsgListRollBack30_user(nullptr); Info::RACE_BOSS_MSG__CMsgListSave32_ptr RACE_BOSS_MSG__CMsgListSave32_next(nullptr); Info::RACE_BOSS_MSG__CMsgListSave32_clbk RACE_BOSS_MSG__CMsgListSave32_user(nullptr); Info::RACE_BOSS_MSG__CMsgListSaveIndexList34_ptr RACE_BOSS_MSG__CMsgListSaveIndexList34_next(nullptr); Info::RACE_BOSS_MSG__CMsgListSaveIndexList34_clbk RACE_BOSS_MSG__CMsgListSaveIndexList34_user(nullptr); Info::RACE_BOSS_MSG__CMsgListSaveMsgList36_ptr RACE_BOSS_MSG__CMsgListSaveMsgList36_next(nullptr); Info::RACE_BOSS_MSG__CMsgListSaveMsgList36_clbk RACE_BOSS_MSG__CMsgListSaveMsgList36_user(nullptr); Info::RACE_BOSS_MSG__CMsgListdtor_CMsgList40_ptr RACE_BOSS_MSG__CMsgListdtor_CMsgList40_next(nullptr); Info::RACE_BOSS_MSG__CMsgListdtor_CMsgList40_clbk RACE_BOSS_MSG__CMsgListdtor_CMsgList40_user(nullptr); void RACE_BOSS_MSG__CMsgListAddEmpty2_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, struct RACE_BOSS_MSG::CMsg* pkMsg) { RACE_BOSS_MSG__CMsgListAddEmpty2_user(_this, pkMsg, RACE_BOSS_MSG__CMsgListAddEmpty2_next); }; void RACE_BOSS_MSG__CMsgListAddUse4_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, struct RACE_BOSS_MSG::CMsg* pkMsg) { RACE_BOSS_MSG__CMsgListAddUse4_user(_this, pkMsg, RACE_BOSS_MSG__CMsgListAddUse4_next); }; void RACE_BOSS_MSG__CMsgListctor_CMsgList6_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, char ucRace, unsigned int uiSize) { RACE_BOSS_MSG__CMsgListctor_CMsgList6_user(_this, ucRace, uiSize, RACE_BOSS_MSG__CMsgListctor_CMsgList6_next); }; int RACE_BOSS_MSG__CMsgListCancel8_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, unsigned int dwMsgID, struct RACE_BOSS_MSG::CMsg** pkMsg) { return RACE_BOSS_MSG__CMsgListCancel8_user(_this, dwMsgID, pkMsg, RACE_BOSS_MSG__CMsgListCancel8_next); }; void RACE_BOSS_MSG__CMsgListCleanUp10_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { RACE_BOSS_MSG__CMsgListCleanUp10_user(_this, RACE_BOSS_MSG__CMsgListCleanUp10_next); }; struct RACE_BOSS_MSG::CMsg* RACE_BOSS_MSG__CMsgListGetEmpty12_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { return RACE_BOSS_MSG__CMsgListGetEmpty12_user(_this, RACE_BOSS_MSG__CMsgListGetEmpty12_next); }; char RACE_BOSS_MSG__CMsgListGetRemainCnt14_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { return RACE_BOSS_MSG__CMsgListGetRemainCnt14_user(_this, RACE_BOSS_MSG__CMsgListGetRemainCnt14_next); }; struct RACE_BOSS_MSG::CMsg* RACE_BOSS_MSG__CMsgListGetSendMsg16_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { return RACE_BOSS_MSG__CMsgListGetSendMsg16_user(_this, RACE_BOSS_MSG__CMsgListGetSendMsg16_next); }; bool RACE_BOSS_MSG__CMsgListInit18_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { return RACE_BOSS_MSG__CMsgListInit18_user(_this, RACE_BOSS_MSG__CMsgListInit18_next); }; bool RACE_BOSS_MSG__CMsgListLoad20_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, unsigned int dwCurTime) { return RACE_BOSS_MSG__CMsgListLoad20_user(_this, dwCurTime, RACE_BOSS_MSG__CMsgListLoad20_next); }; bool RACE_BOSS_MSG__CMsgListLoadIndexList22_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, int iType, struct CNetIndexList* kInxList) { return RACE_BOSS_MSG__CMsgListLoadIndexList22_user(_this, iType, kInxList, RACE_BOSS_MSG__CMsgListLoadIndexList22_next); }; bool RACE_BOSS_MSG__CMsgListLoadMsgList24_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, struct CNetIndexList* kInxList, unsigned int dwCurTime) { return RACE_BOSS_MSG__CMsgListLoadMsgList24_user(_this, kInxList, dwCurTime, RACE_BOSS_MSG__CMsgListLoadMsgList24_next); }; void RACE_BOSS_MSG__CMsgListRefresh26_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { RACE_BOSS_MSG__CMsgListRefresh26_user(_this, RACE_BOSS_MSG__CMsgListRefresh26_next); }; void RACE_BOSS_MSG__CMsgListRelease28_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, struct RACE_BOSS_MSG::CMsg* pkMsg) { RACE_BOSS_MSG__CMsgListRelease28_user(_this, pkMsg, RACE_BOSS_MSG__CMsgListRelease28_next); }; void RACE_BOSS_MSG__CMsgListRollBack30_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { RACE_BOSS_MSG__CMsgListRollBack30_user(_this, RACE_BOSS_MSG__CMsgListRollBack30_next); }; bool RACE_BOSS_MSG__CMsgListSave32_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { return RACE_BOSS_MSG__CMsgListSave32_user(_this, RACE_BOSS_MSG__CMsgListSave32_next); }; bool RACE_BOSS_MSG__CMsgListSaveIndexList34_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, int iType, struct CNetIndexList* kInxList) { return RACE_BOSS_MSG__CMsgListSaveIndexList34_user(_this, iType, kInxList, RACE_BOSS_MSG__CMsgListSaveIndexList34_next); }; bool RACE_BOSS_MSG__CMsgListSaveMsgList36_wrapper(struct RACE_BOSS_MSG::CMsgList* _this, struct CNetIndexList* kInxList) { return RACE_BOSS_MSG__CMsgListSaveMsgList36_user(_this, kInxList, RACE_BOSS_MSG__CMsgListSaveMsgList36_next); }; void RACE_BOSS_MSG__CMsgListdtor_CMsgList40_wrapper(struct RACE_BOSS_MSG::CMsgList* _this) { RACE_BOSS_MSG__CMsgListdtor_CMsgList40_user(_this, RACE_BOSS_MSG__CMsgListdtor_CMsgList40_next); }; ::std::array<hook_record, 19> CMsgList_functions = { _hook_record { (LPVOID)0x14029eb20L, (LPVOID *)&RACE_BOSS_MSG__CMsgListAddEmpty2_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListAddEmpty2_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListAddEmpty2_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)(struct RACE_BOSS_MSG::CMsg*))&RACE_BOSS_MSG::CMsgList::AddEmpty) }, _hook_record { (LPVOID)0x14029e9d0L, (LPVOID *)&RACE_BOSS_MSG__CMsgListAddUse4_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListAddUse4_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListAddUse4_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)(struct RACE_BOSS_MSG::CMsg*))&RACE_BOSS_MSG::CMsgList::AddUse) }, _hook_record { (LPVOID)0x14029e460L, (LPVOID *)&RACE_BOSS_MSG__CMsgListctor_CMsgList6_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListctor_CMsgList6_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListctor_CMsgList6_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)(char, unsigned int))&RACE_BOSS_MSG::CMsgList::ctor_CMsgList) }, _hook_record { (LPVOID)0x14029ec50L, (LPVOID *)&RACE_BOSS_MSG__CMsgListCancel8_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListCancel8_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListCancel8_wrapper), (LPVOID)cast_pointer_function((int(RACE_BOSS_MSG::CMsgList::*)(unsigned int, struct RACE_BOSS_MSG::CMsg**))&RACE_BOSS_MSG::CMsgList::Cancel) }, _hook_record { (LPVOID)0x14029f050L, (LPVOID *)&RACE_BOSS_MSG__CMsgListCleanUp10_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListCleanUp10_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListCleanUp10_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::CleanUp) }, _hook_record { (LPVOID)0x14029e880L, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetEmpty12_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetEmpty12_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListGetEmpty12_wrapper), (LPVOID)cast_pointer_function((struct RACE_BOSS_MSG::CMsg*(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::GetEmpty) }, _hook_record { (LPVOID)0x1402a2ae0L, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetRemainCnt14_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetRemainCnt14_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListGetRemainCnt14_wrapper), (LPVOID)cast_pointer_function((char(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::GetRemainCnt) }, _hook_record { (LPVOID)0x14029e920L, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetSendMsg16_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListGetSendMsg16_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListGetSendMsg16_wrapper), (LPVOID)cast_pointer_function((struct RACE_BOSS_MSG::CMsg*(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::GetSendMsg) }, _hook_record { (LPVOID)0x14029ee60L, (LPVOID *)&RACE_BOSS_MSG__CMsgListInit18_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListInit18_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListInit18_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::Init) }, _hook_record { (LPVOID)0x14029e790L, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoad20_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoad20_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListLoad20_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)(unsigned int))&RACE_BOSS_MSG::CMsgList::Load) }, _hook_record { (LPVOID)0x14029f450L, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoadIndexList22_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoadIndexList22_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListLoadIndexList22_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)(int, struct CNetIndexList*))&RACE_BOSS_MSG::CMsgList::LoadIndexList) }, _hook_record { (LPVOID)0x14029f780L, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoadMsgList24_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListLoadMsgList24_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListLoadMsgList24_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)(struct CNetIndexList*, unsigned int))&RACE_BOSS_MSG::CMsgList::LoadMsgList) }, _hook_record { (LPVOID)0x14029ed00L, (LPVOID *)&RACE_BOSS_MSG__CMsgListRefresh26_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListRefresh26_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListRefresh26_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::Refresh) }, _hook_record { (LPVOID)0x14029eba0L, (LPVOID *)&RACE_BOSS_MSG__CMsgListRelease28_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListRelease28_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListRelease28_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)(struct RACE_BOSS_MSG::CMsg*))&RACE_BOSS_MSG::CMsgList::Release) }, _hook_record { (LPVOID)0x14029ea60L, (LPVOID *)&RACE_BOSS_MSG__CMsgListRollBack30_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListRollBack30_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListRollBack30_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::RollBack) }, _hook_record { (LPVOID)0x14029e6b0L, (LPVOID *)&RACE_BOSS_MSG__CMsgListSave32_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListSave32_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListSave32_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::Save) }, _hook_record { (LPVOID)0x14029f120L, (LPVOID *)&RACE_BOSS_MSG__CMsgListSaveIndexList34_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListSaveIndexList34_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListSaveIndexList34_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)(int, struct CNetIndexList*))&RACE_BOSS_MSG::CMsgList::SaveIndexList) }, _hook_record { (LPVOID)0x14029f690L, (LPVOID *)&RACE_BOSS_MSG__CMsgListSaveMsgList36_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListSaveMsgList36_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListSaveMsgList36_wrapper), (LPVOID)cast_pointer_function((bool(RACE_BOSS_MSG::CMsgList::*)(struct CNetIndexList*))&RACE_BOSS_MSG::CMsgList::SaveMsgList) }, _hook_record { (LPVOID)0x14029e5a0L, (LPVOID *)&RACE_BOSS_MSG__CMsgListdtor_CMsgList40_user, (LPVOID *)&RACE_BOSS_MSG__CMsgListdtor_CMsgList40_next, (LPVOID)cast_pointer_function(RACE_BOSS_MSG__CMsgListdtor_CMsgList40_wrapper), (LPVOID)cast_pointer_function((void(RACE_BOSS_MSG::CMsgList::*)())&RACE_BOSS_MSG::CMsgList::dtor_CMsgList) }, }; }; // end namespace Detail }; // end namespace RACE_BOSS_MSG END_ATF_NAMESPACE
mit
cent89/segresta
Modules/Event/Database/Migrations/2018_03_22_223142_create_event_spec_values_table.php
816
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; class CreateEventSpecValuesTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('event_spec_values', function(Blueprint $table) { $table->increments('id'); $table->integer('id_eventspec')->unsigned()->index('event_spec_values_id_eventspec_foreign'); $table->integer('id_subscription')->unsigned()->index('id_subscription'); $table->string('valore'); $table->integer('id_week'); $table->decimal('costo', 5)->default(0.00); $table->boolean('pagato')->default(0); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('event_spec_values'); } }
mit
rosylilly/mount_doc
lib/mount_doc.rb
318
require 'rails' module MountDoc autoload :VERSION, "mount_doc/version" autoload :Config, "mount_doc/config" autoload :Document, "mount_doc/document" def self.config(&block) yield(MountDoc::Config) end end require 'mount_doc/string_patch' require 'mount_doc/rails' require 'mount_doc/rails/generators'
mit
xpharry/Leetcode
leetcode/cpp/138.cpp
1137
/** * Definition for singly-linked list with a random pointer. * struct RandomListNode { * int label; * RandomListNode *next, *random; * RandomListNode(int x) : label(x), next(NULL), random(NULL) {} * }; */ class Solution { public: RandomListNode *copyRandomList(RandomListNode *head) { // create copies RandomListNode *cur = head; while(cur) { RandomListNode *copy = new RandomListNode(cur->label); copy->next = cur->next; cur->next = copy; cur = copy->next; } // copy random pointers cur = head; while(cur) { RandomListNode *copy = cur->next; if(cur->random) copy->random = cur->random->next; cur = copy->next; } // decouple two link list cur = head; RandomListNode *newhead = (head == NULL) ? NULL : head->next; while(cur) { RandomListNode *temp = cur->next; cur->next = temp->next; if(temp->next) temp->next = temp->next->next; cur = cur->next; } return newhead; } };
mit
himanshu8426/himanshu8426.github.io
src/Components/Project.js
232
import React from "react"; import { Container } from "semantic-ui-react"; function Project() { return ( <Container> <h1 style={{ marginTop: "2rem" }}>Coming Soon...</h1> </Container> ); } export default Project;
mit
maxruby/OpenCV.jl
deps/usr/include/opencv2/imgproc.hpp
223198
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #ifndef OPENCV_IMGPROC_HPP #define OPENCV_IMGPROC_HPP #include "opencv2/core.hpp" /** @defgroup imgproc Image processing @{ @defgroup imgproc_filter Image Filtering Functions and classes described in this section are used to perform various linear or non-linear filtering operations on 2D images (represented as Mat's). It means that for each pixel location \f$(x,y)\f$ in the source image (normally, rectangular), its neighborhood is considered and used to compute the response. In case of a linear filter, it is a weighted sum of pixel values. In case of morphological operations, it is the minimum or maximum values, and so on. The computed response is stored in the destination image at the same location \f$(x,y)\f$. It means that the output image will be of the same size as the input image. Normally, the functions support multi-channel arrays, in which case every channel is processed independently. Therefore, the output image will also have the same number of channels as the input one. Another common feature of the functions and classes described in this section is that, unlike simple arithmetic functions, they need to extrapolate values of some non-existing pixels. For example, if you want to smooth an image using a Gaussian \f$3 \times 3\f$ filter, then, when processing the left-most pixels in each row, you need pixels to the left of them, that is, outside of the image. You can let these pixels be the same as the left-most image pixels ("replicated border" extrapolation method), or assume that all the non-existing pixels are zeros ("constant border" extrapolation method), and so on. OpenCV enables you to specify the extrapolation method. For details, see cv::BorderTypes @anchor filter_depths ### Depth combinations Input depth (src.depth()) | Output depth (ddepth) --------------------------|---------------------- CV_8U | -1/CV_16S/CV_32F/CV_64F CV_16U/CV_16S | -1/CV_32F/CV_64F CV_32F | -1/CV_32F/CV_64F CV_64F | -1/CV_64F @note when ddepth=-1, the output image will have the same depth as the source. @defgroup imgproc_transform Geometric Image Transformations The functions in this section perform various geometrical transformations of 2D images. They do not change the image content but deform the pixel grid and map this deformed grid to the destination image. In fact, to avoid sampling artifacts, the mapping is done in the reverse order, from destination to the source. That is, for each pixel \f$(x, y)\f$ of the destination image, the functions compute coordinates of the corresponding "donor" pixel in the source image and copy the pixel value: \f[\texttt{dst} (x,y)= \texttt{src} (f_x(x,y), f_y(x,y))\f] In case when you specify the forward mapping \f$\left<g_x, g_y\right>: \texttt{src} \rightarrow \texttt{dst}\f$, the OpenCV functions first compute the corresponding inverse mapping \f$\left<f_x, f_y\right>: \texttt{dst} \rightarrow \texttt{src}\f$ and then use the above formula. The actual implementations of the geometrical transformations, from the most generic remap and to the simplest and the fastest resize, need to solve two main problems with the above formula: - Extrapolation of non-existing pixels. Similarly to the filtering functions described in the previous section, for some \f$(x,y)\f$, either one of \f$f_x(x,y)\f$, or \f$f_y(x,y)\f$, or both of them may fall outside of the image. In this case, an extrapolation method needs to be used. OpenCV provides the same selection of extrapolation methods as in the filtering functions. In addition, it provides the method BORDER_TRANSPARENT. This means that the corresponding pixels in the destination image will not be modified at all. - Interpolation of pixel values. Usually \f$f_x(x,y)\f$ and \f$f_y(x,y)\f$ are floating-point numbers. This means that \f$\left<f_x, f_y\right>\f$ can be either an affine or perspective transformation, or radial lens distortion correction, and so on. So, a pixel value at fractional coordinates needs to be retrieved. In the simplest case, the coordinates can be just rounded to the nearest integer coordinates and the corresponding pixel can be used. This is called a nearest-neighbor interpolation. However, a better result can be achieved by using more sophisticated [interpolation methods](http://en.wikipedia.org/wiki/Multivariate_interpolation) , where a polynomial function is fit into some neighborhood of the computed pixel \f$(f_x(x,y), f_y(x,y))\f$, and then the value of the polynomial at \f$(f_x(x,y), f_y(x,y))\f$ is taken as the interpolated pixel value. In OpenCV, you can choose between several interpolation methods. See resize for details. @defgroup imgproc_misc Miscellaneous Image Transformations @defgroup imgproc_draw Drawing Functions Drawing functions work with matrices/images of arbitrary depth. The boundaries of the shapes can be rendered with antialiasing (implemented only for 8-bit images for now). All the functions include the parameter color that uses an RGB value (that may be constructed with the Scalar constructor ) for color images and brightness for grayscale images. For color images, the channel ordering is normally *Blue, Green, Red*. This is what imshow, imread, and imwrite expect. So, if you form a color using the Scalar constructor, it should look like: \f[\texttt{Scalar} (blue \_ component, green \_ component, red \_ component[, alpha \_ component])\f] If you are using your own image rendering and I/O functions, you can use any channel ordering. The drawing functions process each channel independently and do not depend on the channel order or even on the used color space. The whole image can be converted from BGR to RGB or to a different color space using cvtColor . If a drawn figure is partially or completely outside the image, the drawing functions clip it. Also, many drawing functions can handle pixel coordinates specified with sub-pixel accuracy. This means that the coordinates can be passed as fixed-point numbers encoded as integers. The number of fractional bits is specified by the shift parameter and the real point coordinates are calculated as \f$\texttt{Point}(x,y)\rightarrow\texttt{Point2f}(x*2^{-shift},y*2^{-shift})\f$ . This feature is especially effective when rendering antialiased shapes. @note The functions do not support alpha-transparency when the target image is 4-channel. In this case, the color[3] is simply copied to the repainted pixels. Thus, if you want to paint semi-transparent shapes, you can paint them in a separate buffer and then blend it with the main image. @defgroup imgproc_colormap ColorMaps in OpenCV The human perception isn't built for observing fine changes in grayscale images. Human eyes are more sensitive to observing changes between colors, so you often need to recolor your grayscale images to get a clue about them. OpenCV now comes with various colormaps to enhance the visualization in your computer vision application. In OpenCV you only need applyColorMap to apply a colormap on a given image. The following sample code reads the path to an image from command line, applies a Jet colormap on it and shows the result: @code #include <opencv2/core.hpp> #include <opencv2/imgproc.hpp> #include <opencv2/imgcodecs.hpp> #include <opencv2/highgui.hpp> using namespace cv; #include <iostream> using namespace std; int main(int argc, const char *argv[]) { // We need an input image. (can be grayscale or color) if (argc < 2) { cerr << "We need an image to process here. Please run: colorMap [path_to_image]" << endl; return -1; } Mat img_in = imread(argv[1]); if(img_in.empty()) { cerr << "Sample image (" << argv[1] << ") is empty. Please adjust your path, so it points to a valid input image!" << endl; return -1; } // Holds the colormap version of the image: Mat img_color; // Apply the colormap: applyColorMap(img_in, img_color, COLORMAP_JET); // Show the result: imshow("colorMap", img_color); waitKey(0); return 0; } @endcode @see cv::ColormapTypes @defgroup imgproc_subdiv2d Planar Subdivision The Subdiv2D class described in this section is used to perform various planar subdivision on a set of 2D points (represented as vector of Point2f). OpenCV subdivides a plane into triangles using the Delaunay’s algorithm, which corresponds to the dual graph of the Voronoi diagram. In the figure below, the Delaunay’s triangulation is marked with black lines and the Voronoi diagram with red lines. ![Delaunay triangulation (black) and Voronoi (red)](pics/delaunay_voronoi.png) The subdivisions can be used for the 3D piece-wise transformation of a plane, morphing, fast location of points on the plane, building special graphs (such as NNG,RNG), and so forth. @defgroup imgproc_hist Histograms @defgroup imgproc_shape Structural Analysis and Shape Descriptors @defgroup imgproc_motion Motion Analysis and Object Tracking @defgroup imgproc_feature Feature Detection @defgroup imgproc_object Object Detection @defgroup imgproc_c C API @defgroup imgproc_hal Hardware Acceleration Layer @{ @defgroup imgproc_hal_functions Functions @defgroup imgproc_hal_interface Interface @} @} */ namespace cv { /** @addtogroup imgproc @{ */ //! @addtogroup imgproc_filter //! @{ //! type of morphological operation enum MorphTypes{ MORPH_ERODE = 0, //!< see cv::erode MORPH_DILATE = 1, //!< see cv::dilate MORPH_OPEN = 2, //!< an opening operation //!< \f[\texttt{dst} = \mathrm{open} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \mathrm{erode} ( \texttt{src} , \texttt{element} ))\f] MORPH_CLOSE = 3, //!< a closing operation //!< \f[\texttt{dst} = \mathrm{close} ( \texttt{src} , \texttt{element} )= \mathrm{erode} ( \mathrm{dilate} ( \texttt{src} , \texttt{element} ))\f] MORPH_GRADIENT = 4, //!< a morphological gradient //!< \f[\texttt{dst} = \mathrm{morph\_grad} ( \texttt{src} , \texttt{element} )= \mathrm{dilate} ( \texttt{src} , \texttt{element} )- \mathrm{erode} ( \texttt{src} , \texttt{element} )\f] MORPH_TOPHAT = 5, //!< "top hat" //!< \f[\texttt{dst} = \mathrm{tophat} ( \texttt{src} , \texttt{element} )= \texttt{src} - \mathrm{open} ( \texttt{src} , \texttt{element} )\f] MORPH_BLACKHAT = 6, //!< "black hat" //!< \f[\texttt{dst} = \mathrm{blackhat} ( \texttt{src} , \texttt{element} )= \mathrm{close} ( \texttt{src} , \texttt{element} )- \texttt{src}\f] MORPH_HITMISS = 7 //!< "hit or miss" //!< .- Only supported for CV_8UC1 binary images. A tutorial can be found in the documentation }; //! shape of the structuring element enum MorphShapes { MORPH_RECT = 0, //!< a rectangular structuring element: \f[E_{ij}=1\f] MORPH_CROSS = 1, //!< a cross-shaped structuring element: //!< \f[E_{ij} = \fork{1}{if i=\texttt{anchor.y} or j=\texttt{anchor.x}}{0}{otherwise}\f] MORPH_ELLIPSE = 2 //!< an elliptic structuring element, that is, a filled ellipse inscribed //!< into the rectangle Rect(0, 0, esize.width, 0.esize.height) }; //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ //! interpolation algorithm enum InterpolationFlags{ /** nearest neighbor interpolation */ INTER_NEAREST = 0, /** bilinear interpolation */ INTER_LINEAR = 1, /** bicubic interpolation */ INTER_CUBIC = 2, /** resampling using pixel area relation. It may be a preferred method for image decimation, as it gives moire'-free results. But when the image is zoomed, it is similar to the INTER_NEAREST method. */ INTER_AREA = 3, /** Lanczos interpolation over 8x8 neighborhood */ INTER_LANCZOS4 = 4, /** mask for interpolation codes */ INTER_MAX = 7, /** flag, fills all of the destination image pixels. If some of them correspond to outliers in the source image, they are set to zero */ WARP_FILL_OUTLIERS = 8, /** flag, inverse transformation For example, @ref cv::linearPolar or @ref cv::logPolar transforms: - flag is __not__ set: \f$dst( \rho , \phi ) = src(x,y)\f$ - flag is set: \f$dst(x,y) = src( \rho , \phi )\f$ */ WARP_INVERSE_MAP = 16 }; enum InterpolationMasks { INTER_BITS = 5, INTER_BITS2 = INTER_BITS * 2, INTER_TAB_SIZE = 1 << INTER_BITS, INTER_TAB_SIZE2 = INTER_TAB_SIZE * INTER_TAB_SIZE }; //! @} imgproc_transform //! @addtogroup imgproc_misc //! @{ //! Distance types for Distance Transform and M-estimators //! @see cv::distanceTransform, cv::fitLine enum DistanceTypes { DIST_USER = -1, //!< User defined distance DIST_L1 = 1, //!< distance = |x1-x2| + |y1-y2| DIST_L2 = 2, //!< the simple euclidean distance DIST_C = 3, //!< distance = max(|x1-x2|,|y1-y2|) DIST_L12 = 4, //!< L1-L2 metric: distance = 2(sqrt(1+x*x/2) - 1)) DIST_FAIR = 5, //!< distance = c^2(|x|/c-log(1+|x|/c)), c = 1.3998 DIST_WELSCH = 6, //!< distance = c^2/2(1-exp(-(x/c)^2)), c = 2.9846 DIST_HUBER = 7 //!< distance = |x|<c ? x^2/2 : c(|x|-c/2), c=1.345 }; //! Mask size for distance transform enum DistanceTransformMasks { DIST_MASK_3 = 3, //!< mask=3 DIST_MASK_5 = 5, //!< mask=5 DIST_MASK_PRECISE = 0 //!< }; //! type of the threshold operation //! ![threshold types](pics/threshold.png) enum ThresholdTypes { THRESH_BINARY = 0, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{maxval}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] THRESH_BINARY_INV = 1, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{maxval}}{otherwise}\f] THRESH_TRUNC = 2, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{threshold}}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] THRESH_TOZERO = 3, //!< \f[\texttt{dst} (x,y) = \fork{\texttt{src}(x,y)}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{0}{otherwise}\f] THRESH_TOZERO_INV = 4, //!< \f[\texttt{dst} (x,y) = \fork{0}{if \(\texttt{src}(x,y) > \texttt{thresh}\)}{\texttt{src}(x,y)}{otherwise}\f] THRESH_MASK = 7, THRESH_OTSU = 8, //!< flag, use Otsu algorithm to choose the optimal threshold value THRESH_TRIANGLE = 16 //!< flag, use Triangle algorithm to choose the optimal threshold value }; //! adaptive threshold algorithm //! see cv::adaptiveThreshold enum AdaptiveThresholdTypes { /** the threshold value \f$T(x,y)\f$ is a mean of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C */ ADAPTIVE_THRESH_MEAN_C = 0, /** the threshold value \f$T(x, y)\f$ is a weighted sum (cross-correlation with a Gaussian window) of the \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood of \f$(x, y)\f$ minus C . The default sigma (standard deviation) is used for the specified blockSize . See cv::getGaussianKernel*/ ADAPTIVE_THRESH_GAUSSIAN_C = 1 }; //! cv::undistort mode enum UndistortTypes { PROJ_SPHERICAL_ORTHO = 0, PROJ_SPHERICAL_EQRECT = 1 }; //! class of the pixel in GrabCut algorithm enum GrabCutClasses { GC_BGD = 0, //!< an obvious background pixels GC_FGD = 1, //!< an obvious foreground (object) pixel GC_PR_BGD = 2, //!< a possible background pixel GC_PR_FGD = 3 //!< a possible foreground pixel }; //! GrabCut algorithm flags enum GrabCutModes { /** The function initializes the state and the mask using the provided rectangle. After that it runs iterCount iterations of the algorithm. */ GC_INIT_WITH_RECT = 0, /** The function initializes the state using the provided mask. Note that GC_INIT_WITH_RECT and GC_INIT_WITH_MASK can be combined. Then, all the pixels outside of the ROI are automatically initialized with GC_BGD .*/ GC_INIT_WITH_MASK = 1, /** The value means that the algorithm should just resume. */ GC_EVAL = 2 }; //! distanceTransform algorithm flags enum DistanceTransformLabelTypes { /** each connected component of zeros in src (as well as all the non-zero pixels closest to the connected component) will be assigned the same label */ DIST_LABEL_CCOMP = 0, /** each zero pixel (and all the non-zero pixels closest to it) gets its own label. */ DIST_LABEL_PIXEL = 1 }; //! floodfill algorithm flags enum FloodFillFlags { /** If set, the difference between the current pixel and seed pixel is considered. Otherwise, the difference between neighbor pixels is considered (that is, the range is floating). */ FLOODFILL_FIXED_RANGE = 1 << 16, /** If set, the function does not change the image ( newVal is ignored), and only fills the mask with the value specified in bits 8-16 of flags as described above. This option only make sense in function variants that have the mask parameter. */ FLOODFILL_MASK_ONLY = 1 << 17 }; //! @} imgproc_misc //! @addtogroup imgproc_shape //! @{ //! connected components algorithm output formats enum ConnectedComponentsTypes { CC_STAT_LEFT = 0, //!< The leftmost (x) coordinate which is the inclusive start of the bounding //!< box in the horizontal direction. CC_STAT_TOP = 1, //!< The topmost (y) coordinate which is the inclusive start of the bounding //!< box in the vertical direction. CC_STAT_WIDTH = 2, //!< The horizontal size of the bounding box CC_STAT_HEIGHT = 3, //!< The vertical size of the bounding box CC_STAT_AREA = 4, //!< The total area (in pixels) of the connected component CC_STAT_MAX = 5 }; //! connected components algorithm enum ConnectedComponentsAlgorithmsTypes { CCL_WU = 0, //!< SAUF algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity CCL_DEFAULT = -1, //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity CCL_GRANA = 1 //!< BBDT algorithm for 8-way connectivity, SAUF algorithm for 4-way connectivity }; //! mode of the contour retrieval algorithm enum RetrievalModes { /** retrieves only the extreme outer contours. It sets `hierarchy[i][2]=hierarchy[i][3]=-1` for all the contours. */ RETR_EXTERNAL = 0, /** retrieves all of the contours without establishing any hierarchical relationships. */ RETR_LIST = 1, /** retrieves all of the contours and organizes them into a two-level hierarchy. At the top level, there are external boundaries of the components. At the second level, there are boundaries of the holes. If there is another contour inside a hole of a connected component, it is still put at the top level. */ RETR_CCOMP = 2, /** retrieves all of the contours and reconstructs a full hierarchy of nested contours.*/ RETR_TREE = 3, RETR_FLOODFILL = 4 //!< }; //! the contour approximation algorithm enum ContourApproximationModes { /** stores absolutely all the contour points. That is, any 2 subsequent points (x1,y1) and (x2,y2) of the contour will be either horizontal, vertical or diagonal neighbors, that is, max(abs(x1-x2),abs(y2-y1))==1. */ CHAIN_APPROX_NONE = 1, /** compresses horizontal, vertical, and diagonal segments and leaves only their end points. For example, an up-right rectangular contour is encoded with 4 points. */ CHAIN_APPROX_SIMPLE = 2, /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ CHAIN_APPROX_TC89_L1 = 3, /** applies one of the flavors of the Teh-Chin chain approximation algorithm @cite TehChin89 */ CHAIN_APPROX_TC89_KCOS = 4 }; //! @} imgproc_shape //! Variants of a Hough transform enum HoughModes { /** classical or standard Hough transform. Every line is represented by two floating-point numbers \f$(\rho, \theta)\f$ , where \f$\rho\f$ is a distance between (0,0) point and the line, and \f$\theta\f$ is the angle between x-axis and the normal to the line. Thus, the matrix must be (the created sequence will be) of CV_32FC2 type */ HOUGH_STANDARD = 0, /** probabilistic Hough transform (more efficient in case if the picture contains a few long linear segments). It returns line segments rather than the whole line. Each segment is represented by starting and ending points, and the matrix must be (the created sequence will be) of the CV_32SC4 type. */ HOUGH_PROBABILISTIC = 1, /** multi-scale variant of the classical Hough transform. The lines are encoded the same way as HOUGH_STANDARD. */ HOUGH_MULTI_SCALE = 2, HOUGH_GRADIENT = 3 //!< basically *21HT*, described in @cite Yuen90 }; //! Variants of Line Segment %Detector //! @ingroup imgproc_feature enum LineSegmentDetectorModes { LSD_REFINE_NONE = 0, //!< No refinement applied LSD_REFINE_STD = 1, //!< Standard refinement is applied. E.g. breaking arches into smaller straighter line approximations. LSD_REFINE_ADV = 2 //!< Advanced refinement. Number of false alarms is calculated, lines are //!< refined through increase of precision, decrement in size, etc. }; /** Histogram comparison methods @ingroup imgproc_hist */ enum HistCompMethods { /** Correlation \f[d(H_1,H_2) = \frac{\sum_I (H_1(I) - \bar{H_1}) (H_2(I) - \bar{H_2})}{\sqrt{\sum_I(H_1(I) - \bar{H_1})^2 \sum_I(H_2(I) - \bar{H_2})^2}}\f] where \f[\bar{H_k} = \frac{1}{N} \sum _J H_k(J)\f] and \f$N\f$ is a total number of histogram bins. */ HISTCMP_CORREL = 0, /** Chi-Square \f[d(H_1,H_2) = \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)}\f] */ HISTCMP_CHISQR = 1, /** Intersection \f[d(H_1,H_2) = \sum _I \min (H_1(I), H_2(I))\f] */ HISTCMP_INTERSECT = 2, /** Bhattacharyya distance (In fact, OpenCV computes Hellinger distance, which is related to Bhattacharyya coefficient.) \f[d(H_1,H_2) = \sqrt{1 - \frac{1}{\sqrt{\bar{H_1} \bar{H_2} N^2}} \sum_I \sqrt{H_1(I) \cdot H_2(I)}}\f] */ HISTCMP_BHATTACHARYYA = 3, HISTCMP_HELLINGER = HISTCMP_BHATTACHARYYA, //!< Synonym for HISTCMP_BHATTACHARYYA /** Alternative Chi-Square \f[d(H_1,H_2) = 2 * \sum _I \frac{\left(H_1(I)-H_2(I)\right)^2}{H_1(I)+H_2(I)}\f] This alternative formula is regularly used for texture comparison. See e.g. @cite Puzicha1997 */ HISTCMP_CHISQR_ALT = 4, /** Kullback-Leibler divergence \f[d(H_1,H_2) = \sum _I H_1(I) \log \left(\frac{H_1(I)}{H_2(I)}\right)\f] */ HISTCMP_KL_DIV = 5 }; /** the color conversion code @see @ref imgproc_color_conversions @ingroup imgproc_misc */ enum ColorConversionCodes { COLOR_BGR2BGRA = 0, //!< add alpha channel to RGB or BGR image COLOR_RGB2RGBA = COLOR_BGR2BGRA, COLOR_BGRA2BGR = 1, //!< remove alpha channel from RGB or BGR image COLOR_RGBA2RGB = COLOR_BGRA2BGR, COLOR_BGR2RGBA = 2, //!< convert between RGB and BGR color spaces (with or without alpha channel) COLOR_RGB2BGRA = COLOR_BGR2RGBA, COLOR_RGBA2BGR = 3, COLOR_BGRA2RGB = COLOR_RGBA2BGR, COLOR_BGR2RGB = 4, COLOR_RGB2BGR = COLOR_BGR2RGB, COLOR_BGRA2RGBA = 5, COLOR_RGBA2BGRA = COLOR_BGRA2RGBA, COLOR_BGR2GRAY = 6, //!< convert between RGB/BGR and grayscale, @ref color_convert_rgb_gray "color conversions" COLOR_RGB2GRAY = 7, COLOR_GRAY2BGR = 8, COLOR_GRAY2RGB = COLOR_GRAY2BGR, COLOR_GRAY2BGRA = 9, COLOR_GRAY2RGBA = COLOR_GRAY2BGRA, COLOR_BGRA2GRAY = 10, COLOR_RGBA2GRAY = 11, COLOR_BGR2BGR565 = 12, //!< convert between RGB/BGR and BGR565 (16-bit images) COLOR_RGB2BGR565 = 13, COLOR_BGR5652BGR = 14, COLOR_BGR5652RGB = 15, COLOR_BGRA2BGR565 = 16, COLOR_RGBA2BGR565 = 17, COLOR_BGR5652BGRA = 18, COLOR_BGR5652RGBA = 19, COLOR_GRAY2BGR565 = 20, //!< convert between grayscale to BGR565 (16-bit images) COLOR_BGR5652GRAY = 21, COLOR_BGR2BGR555 = 22, //!< convert between RGB/BGR and BGR555 (16-bit images) COLOR_RGB2BGR555 = 23, COLOR_BGR5552BGR = 24, COLOR_BGR5552RGB = 25, COLOR_BGRA2BGR555 = 26, COLOR_RGBA2BGR555 = 27, COLOR_BGR5552BGRA = 28, COLOR_BGR5552RGBA = 29, COLOR_GRAY2BGR555 = 30, //!< convert between grayscale and BGR555 (16-bit images) COLOR_BGR5552GRAY = 31, COLOR_BGR2XYZ = 32, //!< convert RGB/BGR to CIE XYZ, @ref color_convert_rgb_xyz "color conversions" COLOR_RGB2XYZ = 33, COLOR_XYZ2BGR = 34, COLOR_XYZ2RGB = 35, COLOR_BGR2YCrCb = 36, //!< convert RGB/BGR to luma-chroma (aka YCC), @ref color_convert_rgb_ycrcb "color conversions" COLOR_RGB2YCrCb = 37, COLOR_YCrCb2BGR = 38, COLOR_YCrCb2RGB = 39, COLOR_BGR2HSV = 40, //!< convert RGB/BGR to HSV (hue saturation value), @ref color_convert_rgb_hsv "color conversions" COLOR_RGB2HSV = 41, COLOR_BGR2Lab = 44, //!< convert RGB/BGR to CIE Lab, @ref color_convert_rgb_lab "color conversions" COLOR_RGB2Lab = 45, COLOR_BGR2Luv = 50, //!< convert RGB/BGR to CIE Luv, @ref color_convert_rgb_luv "color conversions" COLOR_RGB2Luv = 51, COLOR_BGR2HLS = 52, //!< convert RGB/BGR to HLS (hue lightness saturation), @ref color_convert_rgb_hls "color conversions" COLOR_RGB2HLS = 53, COLOR_HSV2BGR = 54, //!< backward conversions to RGB/BGR COLOR_HSV2RGB = 55, COLOR_Lab2BGR = 56, COLOR_Lab2RGB = 57, COLOR_Luv2BGR = 58, COLOR_Luv2RGB = 59, COLOR_HLS2BGR = 60, COLOR_HLS2RGB = 61, COLOR_BGR2HSV_FULL = 66, //!< COLOR_RGB2HSV_FULL = 67, COLOR_BGR2HLS_FULL = 68, COLOR_RGB2HLS_FULL = 69, COLOR_HSV2BGR_FULL = 70, COLOR_HSV2RGB_FULL = 71, COLOR_HLS2BGR_FULL = 72, COLOR_HLS2RGB_FULL = 73, COLOR_LBGR2Lab = 74, COLOR_LRGB2Lab = 75, COLOR_LBGR2Luv = 76, COLOR_LRGB2Luv = 77, COLOR_Lab2LBGR = 78, COLOR_Lab2LRGB = 79, COLOR_Luv2LBGR = 80, COLOR_Luv2LRGB = 81, COLOR_BGR2YUV = 82, //!< convert between RGB/BGR and YUV COLOR_RGB2YUV = 83, COLOR_YUV2BGR = 84, COLOR_YUV2RGB = 85, //! YUV 4:2:0 family to RGB COLOR_YUV2RGB_NV12 = 90, COLOR_YUV2BGR_NV12 = 91, COLOR_YUV2RGB_NV21 = 92, COLOR_YUV2BGR_NV21 = 93, COLOR_YUV420sp2RGB = COLOR_YUV2RGB_NV21, COLOR_YUV420sp2BGR = COLOR_YUV2BGR_NV21, COLOR_YUV2RGBA_NV12 = 94, COLOR_YUV2BGRA_NV12 = 95, COLOR_YUV2RGBA_NV21 = 96, COLOR_YUV2BGRA_NV21 = 97, COLOR_YUV420sp2RGBA = COLOR_YUV2RGBA_NV21, COLOR_YUV420sp2BGRA = COLOR_YUV2BGRA_NV21, COLOR_YUV2RGB_YV12 = 98, COLOR_YUV2BGR_YV12 = 99, COLOR_YUV2RGB_IYUV = 100, COLOR_YUV2BGR_IYUV = 101, COLOR_YUV2RGB_I420 = COLOR_YUV2RGB_IYUV, COLOR_YUV2BGR_I420 = COLOR_YUV2BGR_IYUV, COLOR_YUV420p2RGB = COLOR_YUV2RGB_YV12, COLOR_YUV420p2BGR = COLOR_YUV2BGR_YV12, COLOR_YUV2RGBA_YV12 = 102, COLOR_YUV2BGRA_YV12 = 103, COLOR_YUV2RGBA_IYUV = 104, COLOR_YUV2BGRA_IYUV = 105, COLOR_YUV2RGBA_I420 = COLOR_YUV2RGBA_IYUV, COLOR_YUV2BGRA_I420 = COLOR_YUV2BGRA_IYUV, COLOR_YUV420p2RGBA = COLOR_YUV2RGBA_YV12, COLOR_YUV420p2BGRA = COLOR_YUV2BGRA_YV12, COLOR_YUV2GRAY_420 = 106, COLOR_YUV2GRAY_NV21 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_NV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_YV12 = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_IYUV = COLOR_YUV2GRAY_420, COLOR_YUV2GRAY_I420 = COLOR_YUV2GRAY_420, COLOR_YUV420sp2GRAY = COLOR_YUV2GRAY_420, COLOR_YUV420p2GRAY = COLOR_YUV2GRAY_420, //! YUV 4:2:2 family to RGB COLOR_YUV2RGB_UYVY = 107, COLOR_YUV2BGR_UYVY = 108, //COLOR_YUV2RGB_VYUY = 109, //COLOR_YUV2BGR_VYUY = 110, COLOR_YUV2RGB_Y422 = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_Y422 = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGB_UYNV = COLOR_YUV2RGB_UYVY, COLOR_YUV2BGR_UYNV = COLOR_YUV2BGR_UYVY, COLOR_YUV2RGBA_UYVY = 111, COLOR_YUV2BGRA_UYVY = 112, //COLOR_YUV2RGBA_VYUY = 113, //COLOR_YUV2BGRA_VYUY = 114, COLOR_YUV2RGBA_Y422 = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_Y422 = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGBA_UYNV = COLOR_YUV2RGBA_UYVY, COLOR_YUV2BGRA_UYNV = COLOR_YUV2BGRA_UYVY, COLOR_YUV2RGB_YUY2 = 115, COLOR_YUV2BGR_YUY2 = 116, COLOR_YUV2RGB_YVYU = 117, COLOR_YUV2BGR_YVYU = 118, COLOR_YUV2RGB_YUYV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUYV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGB_YUNV = COLOR_YUV2RGB_YUY2, COLOR_YUV2BGR_YUNV = COLOR_YUV2BGR_YUY2, COLOR_YUV2RGBA_YUY2 = 119, COLOR_YUV2BGRA_YUY2 = 120, COLOR_YUV2RGBA_YVYU = 121, COLOR_YUV2BGRA_YVYU = 122, COLOR_YUV2RGBA_YUYV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUYV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2RGBA_YUNV = COLOR_YUV2RGBA_YUY2, COLOR_YUV2BGRA_YUNV = COLOR_YUV2BGRA_YUY2, COLOR_YUV2GRAY_UYVY = 123, COLOR_YUV2GRAY_YUY2 = 124, //CV_YUV2GRAY_VYUY = CV_YUV2GRAY_UYVY, COLOR_YUV2GRAY_Y422 = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_UYNV = COLOR_YUV2GRAY_UYVY, COLOR_YUV2GRAY_YVYU = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUYV = COLOR_YUV2GRAY_YUY2, COLOR_YUV2GRAY_YUNV = COLOR_YUV2GRAY_YUY2, //! alpha premultiplication COLOR_RGBA2mRGBA = 125, COLOR_mRGBA2RGBA = 126, //! RGB to YUV 4:2:0 family COLOR_RGB2YUV_I420 = 127, COLOR_BGR2YUV_I420 = 128, COLOR_RGB2YUV_IYUV = COLOR_RGB2YUV_I420, COLOR_BGR2YUV_IYUV = COLOR_BGR2YUV_I420, COLOR_RGBA2YUV_I420 = 129, COLOR_BGRA2YUV_I420 = 130, COLOR_RGBA2YUV_IYUV = COLOR_RGBA2YUV_I420, COLOR_BGRA2YUV_IYUV = COLOR_BGRA2YUV_I420, COLOR_RGB2YUV_YV12 = 131, COLOR_BGR2YUV_YV12 = 132, COLOR_RGBA2YUV_YV12 = 133, COLOR_BGRA2YUV_YV12 = 134, //! Demosaicing COLOR_BayerBG2BGR = 46, COLOR_BayerGB2BGR = 47, COLOR_BayerRG2BGR = 48, COLOR_BayerGR2BGR = 49, COLOR_BayerBG2RGB = COLOR_BayerRG2BGR, COLOR_BayerGB2RGB = COLOR_BayerGR2BGR, COLOR_BayerRG2RGB = COLOR_BayerBG2BGR, COLOR_BayerGR2RGB = COLOR_BayerGB2BGR, COLOR_BayerBG2GRAY = 86, COLOR_BayerGB2GRAY = 87, COLOR_BayerRG2GRAY = 88, COLOR_BayerGR2GRAY = 89, //! Demosaicing using Variable Number of Gradients COLOR_BayerBG2BGR_VNG = 62, COLOR_BayerGB2BGR_VNG = 63, COLOR_BayerRG2BGR_VNG = 64, COLOR_BayerGR2BGR_VNG = 65, COLOR_BayerBG2RGB_VNG = COLOR_BayerRG2BGR_VNG, COLOR_BayerGB2RGB_VNG = COLOR_BayerGR2BGR_VNG, COLOR_BayerRG2RGB_VNG = COLOR_BayerBG2BGR_VNG, COLOR_BayerGR2RGB_VNG = COLOR_BayerGB2BGR_VNG, //! Edge-Aware Demosaicing COLOR_BayerBG2BGR_EA = 135, COLOR_BayerGB2BGR_EA = 136, COLOR_BayerRG2BGR_EA = 137, COLOR_BayerGR2BGR_EA = 138, COLOR_BayerBG2RGB_EA = COLOR_BayerRG2BGR_EA, COLOR_BayerGB2RGB_EA = COLOR_BayerGR2BGR_EA, COLOR_BayerRG2RGB_EA = COLOR_BayerBG2BGR_EA, COLOR_BayerGR2RGB_EA = COLOR_BayerGB2BGR_EA, //! Demosaicing with alpha channel COLOR_BayerBG2BGRA = 139, COLOR_BayerGB2BGRA = 140, COLOR_BayerRG2BGRA = 141, COLOR_BayerGR2BGRA = 142, COLOR_BayerBG2RGBA = COLOR_BayerRG2BGRA, COLOR_BayerGB2RGBA = COLOR_BayerGR2BGRA, COLOR_BayerRG2RGBA = COLOR_BayerBG2BGRA, COLOR_BayerGR2RGBA = COLOR_BayerGB2BGRA, COLOR_COLORCVT_MAX = 143 }; /** types of intersection between rectangles @ingroup imgproc_shape */ enum RectanglesIntersectTypes { INTERSECT_NONE = 0, //!< No intersection INTERSECT_PARTIAL = 1, //!< There is a partial intersection INTERSECT_FULL = 2 //!< One of the rectangle is fully enclosed in the other }; //! finds arbitrary template in the grayscale image using Generalized Hough Transform class CV_EXPORTS GeneralizedHough : public Algorithm { public: //! set template to search virtual void setTemplate(InputArray templ, Point templCenter = Point(-1, -1)) = 0; virtual void setTemplate(InputArray edges, InputArray dx, InputArray dy, Point templCenter = Point(-1, -1)) = 0; //! find template on image virtual void detect(InputArray image, OutputArray positions, OutputArray votes = noArray()) = 0; virtual void detect(InputArray edges, InputArray dx, InputArray dy, OutputArray positions, OutputArray votes = noArray()) = 0; //! Canny low threshold. virtual void setCannyLowThresh(int cannyLowThresh) = 0; virtual int getCannyLowThresh() const = 0; //! Canny high threshold. virtual void setCannyHighThresh(int cannyHighThresh) = 0; virtual int getCannyHighThresh() const = 0; //! Minimum distance between the centers of the detected objects. virtual void setMinDist(double minDist) = 0; virtual double getMinDist() const = 0; //! Inverse ratio of the accumulator resolution to the image resolution. virtual void setDp(double dp) = 0; virtual double getDp() const = 0; //! Maximal size of inner buffers. virtual void setMaxBufferSize(int maxBufferSize) = 0; virtual int getMaxBufferSize() const = 0; }; //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without translation and rotation class CV_EXPORTS GeneralizedHoughBallard : public GeneralizedHough { public: //! R-Table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! The accumulator threshold for the template centers at the detection stage. The smaller it is, the more false positions may be detected. virtual void setVotesThreshold(int votesThreshold) = 0; virtual int getVotesThreshold() const = 0; }; //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, translation and rotation class CV_EXPORTS GeneralizedHoughGuil : public GeneralizedHough { public: //! Angle difference in degrees between two points in feature. virtual void setXi(double xi) = 0; virtual double getXi() const = 0; //! Feature table levels. virtual void setLevels(int levels) = 0; virtual int getLevels() const = 0; //! Maximal difference between angles that treated as equal. virtual void setAngleEpsilon(double angleEpsilon) = 0; virtual double getAngleEpsilon() const = 0; //! Minimal rotation angle to detect in degrees. virtual void setMinAngle(double minAngle) = 0; virtual double getMinAngle() const = 0; //! Maximal rotation angle to detect in degrees. virtual void setMaxAngle(double maxAngle) = 0; virtual double getMaxAngle() const = 0; //! Angle step in degrees. virtual void setAngleStep(double angleStep) = 0; virtual double getAngleStep() const = 0; //! Angle votes threshold. virtual void setAngleThresh(int angleThresh) = 0; virtual int getAngleThresh() const = 0; //! Minimal scale to detect. virtual void setMinScale(double minScale) = 0; virtual double getMinScale() const = 0; //! Maximal scale to detect. virtual void setMaxScale(double maxScale) = 0; virtual double getMaxScale() const = 0; //! Scale step. virtual void setScaleStep(double scaleStep) = 0; virtual double getScaleStep() const = 0; //! Scale votes threshold. virtual void setScaleThresh(int scaleThresh) = 0; virtual int getScaleThresh() const = 0; //! Position votes threshold. virtual void setPosThresh(int posThresh) = 0; virtual int getPosThresh() const = 0; }; class CV_EXPORTS_W CLAHE : public Algorithm { public: CV_WRAP virtual void apply(InputArray src, OutputArray dst) = 0; CV_WRAP virtual void setClipLimit(double clipLimit) = 0; CV_WRAP virtual double getClipLimit() const = 0; CV_WRAP virtual void setTilesGridSize(Size tileGridSize) = 0; CV_WRAP virtual Size getTilesGridSize() const = 0; CV_WRAP virtual void collectGarbage() = 0; }; //! @addtogroup imgproc_subdiv2d //! @{ class CV_EXPORTS_W Subdiv2D { public: /** Subdiv2D point location cases */ enum { PTLOC_ERROR = -2, //!< Point location error PTLOC_OUTSIDE_RECT = -1, //!< Point outside the subdivision bounding rect PTLOC_INSIDE = 0, //!< Point inside some facet PTLOC_VERTEX = 1, //!< Point coincides with one of the subdivision vertices PTLOC_ON_EDGE = 2 //!< Point on some edge }; /** Subdiv2D edge type navigation (see: getEdge()) */ enum { NEXT_AROUND_ORG = 0x00, NEXT_AROUND_DST = 0x22, PREV_AROUND_ORG = 0x11, PREV_AROUND_DST = 0x33, NEXT_AROUND_LEFT = 0x13, NEXT_AROUND_RIGHT = 0x31, PREV_AROUND_LEFT = 0x20, PREV_AROUND_RIGHT = 0x02 }; /** creates an empty Subdiv2D object. To create a new empty Delaunay subdivision you need to use the initDelaunay() function. */ CV_WRAP Subdiv2D(); /** @overload @param rect – Rectangle that includes all of the 2D points that are to be added to the subdivision. The function creates an empty Delaunay subdivision where 2D points can be added using the function insert() . All of the points to be added must be within the specified rectangle, otherwise a runtime error is raised. */ CV_WRAP Subdiv2D(Rect rect); /** @brief Creates a new empty Delaunay subdivision @param rect – Rectangle that includes all of the 2D points that are to be added to the subdivision. */ CV_WRAP void initDelaunay(Rect rect); /** @brief Insert a single point into a Delaunay triangulation. @param pt – Point to insert. The function inserts a single point into a subdivision and modifies the subdivision topology appropriately. If a point with the same coordinates exists already, no new point is added. @returns the ID of the point. @note If the point is outside of the triangulation specified rect a runtime error is raised. */ CV_WRAP int insert(Point2f pt); /** @brief Insert multiple points into a Delaunay triangulation. @param ptvec – Points to insert. The function inserts a vector of points into a subdivision and modifies the subdivision topology appropriately. */ CV_WRAP void insert(const std::vector<Point2f>& ptvec); /** @brief Returns the location of a point within a Delaunay triangulation. @param pt – Point to locate. @param edge – Output edge that the point belongs to or is located to the right of it. @param vertex – Optional output vertex the input point coincides with. The function locates the input point within the subdivision and gives one of the triangle edges or vertices. @returns an integer which specify one of the following five cases for point location: - The point falls into some facet. The function returns PTLOC_INSIDE and edge will contain one of edges of the facet. - The point falls onto the edge. The function returns PTLOC_ON_EDGE and edge will contain this edge. - The point coincides with one of the subdivision vertices. The function returns PTLOC_VERTEX and vertex will contain a pointer to the vertex. - The point is outside the subdivision reference rectangle. The function returns PTLOC_OUTSIDE_RECT and no pointers are filled. - One of input arguments is invalid. A runtime error is raised or, if silent or “parent” error processing mode is selected, CV_PTLOC_ERROR is returned. */ CV_WRAP int locate(Point2f pt, CV_OUT int& edge, CV_OUT int& vertex); /** @brief Finds the subdivision vertex closest to the given point. @param pt – Input point. @param nearestPt – Output subdivision vertex point. The function is another function that locates the input point within the subdivision. It finds the subdivision vertex that is the closest to the input point. It is not necessarily one of vertices of the facet containing the input point, though the facet (located using locate() ) is used as a starting point. @returns vertex ID. */ CV_WRAP int findNearest(Point2f pt, CV_OUT Point2f* nearestPt = 0); /** @brief Returns a list of all edges. @param edgeList – Output vector. The function gives each edge as a 4 numbers vector, where each two are one of the edge vertices. i.e. org_x = v[0], org_y = v[1], dst_x = v[2], dst_y = v[3]. */ CV_WRAP void getEdgeList(CV_OUT std::vector<Vec4f>& edgeList) const; /** @brief Returns a list of the leading edge ID connected to each triangle. @param leadingEdgeList – Output vector. The function gives one edge ID for each triangle. */ CV_WRAP void getLeadingEdgeList(CV_OUT std::vector<int>& leadingEdgeList) const; /** @brief Returns a list of all triangles. @param triangleList – Output vector. The function gives each triangle as a 6 numbers vector, where each two are one of the triangle vertices. i.e. p1_x = v[0], p1_y = v[1], p2_x = v[2], p2_y = v[3], p3_x = v[4], p3_y = v[5]. */ CV_WRAP void getTriangleList(CV_OUT std::vector<Vec6f>& triangleList) const; /** @brief Returns a list of all Voroni facets. @param idx – Vector of vertices IDs to consider. For all vertices you can pass empty vector. @param facetList – Output vector of the Voroni facets. @param facetCenters – Output vector of the Voroni facets center points. */ CV_WRAP void getVoronoiFacetList(const std::vector<int>& idx, CV_OUT std::vector<std::vector<Point2f> >& facetList, CV_OUT std::vector<Point2f>& facetCenters); /** @brief Returns vertex location from vertex ID. @param vertex – vertex ID. @param firstEdge – Optional. The first edge ID which is connected to the vertex. @returns vertex (x,y) */ CV_WRAP Point2f getVertex(int vertex, CV_OUT int* firstEdge = 0) const; /** @brief Returns one of the edges related to the given edge. @param edge – Subdivision edge ID. @param nextEdgeType - Parameter specifying which of the related edges to return. The following values are possible: - NEXT_AROUND_ORG next around the edge origin ( eOnext on the picture below if e is the input edge) - NEXT_AROUND_DST next around the edge vertex ( eDnext ) - PREV_AROUND_ORG previous around the edge origin (reversed eRnext ) - PREV_AROUND_DST previous around the edge destination (reversed eLnext ) - NEXT_AROUND_LEFT next around the left facet ( eLnext ) - NEXT_AROUND_RIGHT next around the right facet ( eRnext ) - PREV_AROUND_LEFT previous around the left facet (reversed eOnext ) - PREV_AROUND_RIGHT previous around the right facet (reversed eDnext ) ![sample output](pics/quadedge.png) @returns edge ID related to the input edge. */ CV_WRAP int getEdge( int edge, int nextEdgeType ) const; /** @brief Returns next edge around the edge origin. @param edge – Subdivision edge ID. @returns an integer which is next edge ID around the edge origin: eOnext on the picture above if e is the input edge). */ CV_WRAP int nextEdge(int edge) const; /** @brief Returns another edge of the same quad-edge. @param edge – Subdivision edge ID. @param rotate - Parameter specifying which of the edges of the same quad-edge as the input one to return. The following values are possible: - 0 - the input edge ( e on the picture below if e is the input edge) - 1 - the rotated edge ( eRot ) - 2 - the reversed edge (reversed e (in green)) - 3 - the reversed rotated edge (reversed eRot (in green)) @returns one of the edges ID of the same quad-edge as the input edge. */ CV_WRAP int rotateEdge(int edge, int rotate) const; CV_WRAP int symEdge(int edge) const; /** @brief Returns the edge origin. @param edge – Subdivision edge ID. @param orgpt – Output vertex location. @returns vertex ID. */ CV_WRAP int edgeOrg(int edge, CV_OUT Point2f* orgpt = 0) const; /** @brief Returns the edge destination. @param edge – Subdivision edge ID. @param dstpt – Output vertex location. @returns vertex ID. */ CV_WRAP int edgeDst(int edge, CV_OUT Point2f* dstpt = 0) const; protected: int newEdge(); void deleteEdge(int edge); int newPoint(Point2f pt, bool isvirtual, int firstEdge = 0); void deletePoint(int vtx); void setEdgePoints( int edge, int orgPt, int dstPt ); void splice( int edgeA, int edgeB ); int connectEdges( int edgeA, int edgeB ); void swapEdges( int edge ); int isRightOf(Point2f pt, int edge) const; void calcVoronoi(); void clearVoronoi(); void checkSubdiv() const; struct CV_EXPORTS Vertex { Vertex(); Vertex(Point2f pt, bool _isvirtual, int _firstEdge=0); bool isvirtual() const; bool isfree() const; int firstEdge; int type; Point2f pt; }; struct CV_EXPORTS QuadEdge { QuadEdge(); QuadEdge(int edgeidx); bool isfree() const; int next[4]; int pt[4]; }; //! All of the vertices std::vector<Vertex> vtx; //! All of the edges std::vector<QuadEdge> qedges; int freeQEdge; int freePoint; bool validGeometry; int recentEdge; //! Top left corner of the bounding rect Point2f topLeft; //! Bottom right corner of the bounding rect Point2f bottomRight; }; //! @} imgproc_subdiv2d //! @addtogroup imgproc_feature //! @{ /** @example lsd_lines.cpp An example using the LineSegmentDetector */ /** @brief Line segment detector class following the algorithm described at @cite Rafael12 . */ class CV_EXPORTS_W LineSegmentDetector : public Algorithm { public: /** @brief Finds lines in the input image. This is the output of the default parameters of the algorithm on the above shown image. ![image](pics/building_lsd.png) @param _image A grayscale (CV_8UC1) input image. If only a roi needs to be selected, use: `lsd_ptr-\>detect(image(roi), lines, ...); lines += Scalar(roi.x, roi.y, roi.x, roi.y);` @param _lines A vector of Vec4i or Vec4f elements specifying the beginning and ending point of a line. Where Vec4i/Vec4f is (x1, y1, x2, y2), point 1 is the start, point 2 - end. Returned lines are strictly oriented depending on the gradient. @param width Vector of widths of the regions, where the lines are found. E.g. Width of line. @param prec Vector of precisions with which the lines are found. @param nfa Vector containing number of false alarms in the line region, with precision of 10%. The bigger the value, logarithmically better the detection. - -1 corresponds to 10 mean false alarms - 0 corresponds to 1 mean false alarm - 1 corresponds to 0.1 mean false alarms This vector will be calculated only when the objects type is LSD_REFINE_ADV. */ CV_WRAP virtual void detect(InputArray _image, OutputArray _lines, OutputArray width = noArray(), OutputArray prec = noArray(), OutputArray nfa = noArray()) = 0; /** @brief Draws the line segments on a given image. @param _image The image, where the liens will be drawn. Should be bigger or equal to the image, where the lines were found. @param lines A vector of the lines that needed to be drawn. */ CV_WRAP virtual void drawSegments(InputOutputArray _image, InputArray lines) = 0; /** @brief Draws two groups of lines in blue and red, counting the non overlapping (mismatching) pixels. @param size The size of the image, where lines1 and lines2 were found. @param lines1 The first group of lines that needs to be drawn. It is visualized in blue color. @param lines2 The second group of lines. They visualized in red color. @param _image Optional image, where the lines will be drawn. The image should be color(3-channel) in order for lines1 and lines2 to be drawn in the above mentioned colors. */ CV_WRAP virtual int compareSegments(const Size& size, InputArray lines1, InputArray lines2, InputOutputArray _image = noArray()) = 0; virtual ~LineSegmentDetector() { } }; /** @brief Creates a smart pointer to a LineSegmentDetector object and initializes it. The LineSegmentDetector algorithm is defined using the standard values. Only advanced users may want to edit those, as to tailor it for their own application. @param _refine The way found lines will be refined, see cv::LineSegmentDetectorModes @param _scale The scale of the image that will be used to find the lines. Range (0..1]. @param _sigma_scale Sigma for Gaussian filter. It is computed as sigma = _sigma_scale/_scale. @param _quant Bound to the quantization error on the gradient norm. @param _ang_th Gradient angle tolerance in degrees. @param _log_eps Detection threshold: -log10(NFA) \> log_eps. Used only when advancent refinement is chosen. @param _density_th Minimal density of aligned region points in the enclosing rectangle. @param _n_bins Number of bins in pseudo-ordering of gradient modulus. */ CV_EXPORTS_W Ptr<LineSegmentDetector> createLineSegmentDetector( int _refine = LSD_REFINE_STD, double _scale = 0.8, double _sigma_scale = 0.6, double _quant = 2.0, double _ang_th = 22.5, double _log_eps = 0, double _density_th = 0.7, int _n_bins = 1024); //! @} imgproc_feature //! @addtogroup imgproc_filter //! @{ /** @brief Returns Gaussian filter coefficients. The function computes and returns the \f$\texttt{ksize} \times 1\f$ matrix of Gaussian filter coefficients: \f[G_i= \alpha *e^{-(i-( \texttt{ksize} -1)/2)^2/(2* \texttt{sigma}^2)},\f] where \f$i=0..\texttt{ksize}-1\f$ and \f$\alpha\f$ is the scale factor chosen so that \f$\sum_i G_i=1\f$. Two of such generated kernels can be passed to sepFilter2D. Those functions automatically recognize smoothing kernels (a symmetrical kernel with sum of weights equal to 1) and handle them accordingly. You may also use the higher-level GaussianBlur. @param ksize Aperture size. It should be odd ( \f$\texttt{ksize} \mod 2 = 1\f$ ) and positive. @param sigma Gaussian standard deviation. If it is non-positive, it is computed from ksize as `sigma = 0.3\*((ksize-1)\*0.5 - 1) + 0.8`. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . @sa sepFilter2D, getDerivKernels, getStructuringElement, GaussianBlur */ CV_EXPORTS_W Mat getGaussianKernel( int ksize, double sigma, int ktype = CV_64F ); /** @brief Returns filter coefficients for computing spatial image derivatives. The function computes and returns the filter coefficients for spatial image derivatives. When `ksize=CV_SCHARR`, the Scharr \f$3 \times 3\f$ kernels are generated (see cv::Scharr). Otherwise, Sobel kernels are generated (see cv::Sobel). The filters are normally passed to sepFilter2D or to @param kx Output matrix of row filter coefficients. It has the type ktype . @param ky Output matrix of column filter coefficients. It has the type ktype . @param dx Derivative order in respect of x. @param dy Derivative order in respect of y. @param ksize Aperture size. It can be CV_SCHARR, 1, 3, 5, or 7. @param normalize Flag indicating whether to normalize (scale down) the filter coefficients or not. Theoretically, the coefficients should have the denominator \f$=2^{ksize*2-dx-dy-2}\f$. If you are going to filter floating-point images, you are likely to use the normalized kernels. But if you compute derivatives of an 8-bit image, store the results in a 16-bit image, and wish to preserve all the fractional bits, you may want to set normalize=false . @param ktype Type of filter coefficients. It can be CV_32f or CV_64F . */ CV_EXPORTS_W void getDerivKernels( OutputArray kx, OutputArray ky, int dx, int dy, int ksize, bool normalize = false, int ktype = CV_32F ); /** @brief Returns Gabor filter coefficients. For more details about gabor filter equations and parameters, see: [Gabor Filter](http://en.wikipedia.org/wiki/Gabor_filter). @param ksize Size of the filter returned. @param sigma Standard deviation of the gaussian envelope. @param theta Orientation of the normal to the parallel stripes of a Gabor function. @param lambd Wavelength of the sinusoidal factor. @param gamma Spatial aspect ratio. @param psi Phase offset. @param ktype Type of filter coefficients. It can be CV_32F or CV_64F . */ CV_EXPORTS_W Mat getGaborKernel( Size ksize, double sigma, double theta, double lambd, double gamma, double psi = CV_PI*0.5, int ktype = CV_64F ); //! returns "magic" border value for erosion and dilation. It is automatically transformed to Scalar::all(-DBL_MAX) for dilation. static inline Scalar morphologyDefaultBorderValue() { return Scalar::all(DBL_MAX); } /** @brief Returns a structuring element of the specified size and shape for morphological operations. The function constructs and returns the structuring element that can be further passed to cv::erode, cv::dilate or cv::morphologyEx. But you can also construct an arbitrary binary mask yourself and use it as the structuring element. @param shape Element shape that could be one of cv::MorphShapes @param ksize Size of the structuring element. @param anchor Anchor position within the element. The default value \f$(-1, -1)\f$ means that the anchor is at the center. Note that only the shape of a cross-shaped element depends on the anchor position. In other cases the anchor just regulates how much the result of the morphological operation is shifted. */ CV_EXPORTS_W Mat getStructuringElement(int shape, Size ksize, Point anchor = Point(-1,-1)); /** @brief Blurs an image using the median filter. The function smoothes an image using the median filter with the \f$\texttt{ksize} \times \texttt{ksize}\f$ aperture. Each channel of a multi-channel image is processed independently. In-place operation is supported. @note The median filter uses BORDER_REPLICATE internally to cope with border pixels, see cv::BorderTypes @param src input 1-, 3-, or 4-channel image; when ksize is 3 or 5, the image depth should be CV_8U, CV_16U, or CV_32F, for larger aperture sizes, it can only be CV_8U. @param dst destination array of the same size and type as src. @param ksize aperture linear size; it must be odd and greater than 1, for example: 3, 5, 7 ... @sa bilateralFilter, blur, boxFilter, GaussianBlur */ CV_EXPORTS_W void medianBlur( InputArray src, OutputArray dst, int ksize ); /** @brief Blurs an image using a Gaussian filter. The function convolves the source image with the specified Gaussian kernel. In-place filtering is supported. @param src input image; the image can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param ksize Gaussian kernel size. ksize.width and ksize.height can differ but they both must be positive and odd. Or, they can be zero's and then they are computed from sigma. @param sigmaX Gaussian kernel standard deviation in X direction. @param sigmaY Gaussian kernel standard deviation in Y direction; if sigmaY is zero, it is set to be equal to sigmaX, if both sigmas are zeros, they are computed from ksize.width and ksize.height, respectively (see cv::getGaussianKernel for details); to fully control the result regardless of possible future modifications of all this semantics, it is recommended to specify all of ksize, sigmaX, and sigmaY. @param borderType pixel extrapolation method, see cv::BorderTypes @sa sepFilter2D, filter2D, blur, boxFilter, bilateralFilter, medianBlur */ CV_EXPORTS_W void GaussianBlur( InputArray src, OutputArray dst, Size ksize, double sigmaX, double sigmaY = 0, int borderType = BORDER_DEFAULT ); /** @brief Applies the bilateral filter to an image. The function applies bilateral filtering to the input image, as described in http://www.dai.ed.ac.uk/CVonline/LOCAL_COPIES/MANDUCHI1/Bilateral_Filtering.html bilateralFilter can reduce unwanted noise very well while keeping edges fairly sharp. However, it is very slow compared to most filters. _Sigma values_: For simplicity, you can set the 2 sigma values to be the same. If they are small (\< 10), the filter will not have much effect, whereas if they are large (\> 150), they will have a very strong effect, making the image look "cartoonish". _Filter size_: Large filters (d \> 5) are very slow, so it is recommended to use d=5 for real-time applications, and perhaps d=9 for offline applications that need heavy noise filtering. This filter does not work inplace. @param src Source 8-bit or floating-point, 1-channel or 3-channel image. @param dst Destination image of the same size and type as src . @param d Diameter of each pixel neighborhood that is used during filtering. If it is non-positive, it is computed from sigmaSpace. @param sigmaColor Filter sigma in the color space. A larger value of the parameter means that farther colors within the pixel neighborhood (see sigmaSpace) will be mixed together, resulting in larger areas of semi-equal color. @param sigmaSpace Filter sigma in the coordinate space. A larger value of the parameter means that farther pixels will influence each other as long as their colors are close enough (see sigmaColor ). When d\>0, it specifies the neighborhood size regardless of sigmaSpace. Otherwise, d is proportional to sigmaSpace. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes */ CV_EXPORTS_W void bilateralFilter( InputArray src, OutputArray dst, int d, double sigmaColor, double sigmaSpace, int borderType = BORDER_DEFAULT ); /** @brief Blurs an image using the box filter. The function smooths an image using the kernel: \f[\texttt{K} = \alpha \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \end{bmatrix}\f] where \f[\alpha = \fork{\frac{1}{\texttt{ksize.width*ksize.height}}}{when \texttt{normalize=true}}{1}{otherwise}\f] Unnormalized box filter is useful for computing various integral characteristics over each pixel neighborhood, such as covariance matrices of image derivatives (used in dense optical flow algorithms, and so on). If you need to compute pixel sums over variable-size windows, use cv::integral. @param src input image. @param dst output image of the same size and type as src. @param ddepth the output image depth (-1 to use src.depth()). @param ksize blurring kernel size. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel center. @param normalize flag, specifying whether the kernel is normalized by its area or not. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa blur, bilateralFilter, GaussianBlur, medianBlur, integral */ CV_EXPORTS_W void boxFilter( InputArray src, OutputArray dst, int ddepth, Size ksize, Point anchor = Point(-1,-1), bool normalize = true, int borderType = BORDER_DEFAULT ); /** @brief Calculates the normalized sum of squares of the pixel values overlapping the filter. For every pixel \f$ (x, y) \f$ in the source image, the function calculates the sum of squares of those neighboring pixel values which overlap the filter placed over the pixel \f$ (x, y) \f$. The unnormalized square box filter can be useful in computing local image statistics such as the the local variance and standard deviation around the neighborhood of a pixel. @param _src input image @param _dst output image of the same size and type as _src @param ddepth the output image depth (-1 to use src.depth()) @param ksize kernel size @param anchor kernel anchor point. The default value of Point(-1, -1) denotes that the anchor is at the kernel center. @param normalize flag, specifying whether the kernel is to be normalized by it's area or not. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa boxFilter */ CV_EXPORTS_W void sqrBoxFilter( InputArray _src, OutputArray _dst, int ddepth, Size ksize, Point anchor = Point(-1, -1), bool normalize = true, int borderType = BORDER_DEFAULT ); /** @brief Blurs an image using the normalized box filter. The function smooths an image using the kernel: \f[\texttt{K} = \frac{1}{\texttt{ksize.width*ksize.height}} \begin{bmatrix} 1 & 1 & 1 & \cdots & 1 & 1 \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \hdotsfor{6} \\ 1 & 1 & 1 & \cdots & 1 & 1 \\ \end{bmatrix}\f] The call `blur(src, dst, ksize, anchor, borderType)` is equivalent to `boxFilter(src, dst, src.type(), anchor, true, borderType)`. @param src input image; it can have any number of channels, which are processed independently, but the depth should be CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param ksize blurring kernel size. @param anchor anchor point; default value Point(-1,-1) means that the anchor is at the kernel center. @param borderType border mode used to extrapolate pixels outside of the image, see cv::BorderTypes @sa boxFilter, bilateralFilter, GaussianBlur, medianBlur */ CV_EXPORTS_W void blur( InputArray src, OutputArray dst, Size ksize, Point anchor = Point(-1,-1), int borderType = BORDER_DEFAULT ); /** @brief Convolves an image with the kernel. The function applies an arbitrary linear filter to an image. In-place operation is supported. When the aperture is partially outside the image, the function interpolates outlier pixel values according to the specified border mode. The function does actually compute correlation, not the convolution: \f[\texttt{dst} (x,y) = \sum _{ \stackrel{0\leq x' < \texttt{kernel.cols},}{0\leq y' < \texttt{kernel.rows}} } \texttt{kernel} (x',y')* \texttt{src} (x+x'- \texttt{anchor.x} ,y+y'- \texttt{anchor.y} )\f] That is, the kernel is not mirrored around the anchor point. If you need a real convolution, flip the kernel using cv::flip and set the new anchor to `(kernel.cols - anchor.x - 1, kernel.rows - anchor.y - 1)`. The function uses the DFT-based algorithm in case of sufficiently large kernels (~`11 x 11` or larger) and the direct algorithm for small kernels. @param src input image. @param dst output image of the same size and the same number of channels as src. @param ddepth desired depth of the destination image, see @ref filter_depths "combinations" @param kernel convolution kernel (or rather a correlation kernel), a single-channel floating point matrix; if you want to apply different kernels to different channels, split the image into separate color planes using split and process them individually. @param anchor anchor of the kernel that indicates the relative position of a filtered point within the kernel; the anchor should lie within the kernel; default value (-1,-1) means that the anchor is at the kernel center. @param delta optional value added to the filtered pixels before storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa sepFilter2D, dft, matchTemplate */ CV_EXPORTS_W void filter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernel, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Applies a separable linear filter to an image. The function applies a separable linear filter to the image. That is, first, every row of src is filtered with the 1D kernel kernelX. Then, every column of the result is filtered with the 1D kernel kernelY. The final result shifted by delta is stored in dst . @param src Source image. @param dst Destination image of the same size and the same number of channels as src . @param ddepth Destination image depth, see @ref filter_depths "combinations" @param kernelX Coefficients for filtering each row. @param kernelY Coefficients for filtering each column. @param anchor Anchor position within the kernel. The default value \f$(-1,-1)\f$ means that the anchor is at the kernel center. @param delta Value added to the filtered results before storing them. @param borderType Pixel extrapolation method, see cv::BorderTypes @sa filter2D, Sobel, GaussianBlur, boxFilter, blur */ CV_EXPORTS_W void sepFilter2D( InputArray src, OutputArray dst, int ddepth, InputArray kernelX, InputArray kernelY, Point anchor = Point(-1,-1), double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first, second, third, or mixed image derivatives using an extended Sobel operator. In all cases except one, the \f$\texttt{ksize} \times \texttt{ksize}\f$ separable kernel is used to calculate the derivative. When \f$\texttt{ksize = 1}\f$, the \f$3 \times 1\f$ or \f$1 \times 3\f$ kernel is used (that is, no Gaussian smoothing is done). `ksize = 1` can only be used for the first or the second x- or y- derivatives. There is also the special value `ksize = CV_SCHARR (-1)` that corresponds to the \f$3\times3\f$ Scharr filter that may give more accurate results than the \f$3\times3\f$ Sobel. The Scharr aperture is \f[\vecthreethree{-3}{0}{3}{-10}{0}{10}{-3}{0}{3}\f] for the x-derivative, or transposed for the y-derivative. The function calculates an image derivative by convolving the image with the appropriate kernel: \f[\texttt{dst} = \frac{\partial^{xorder+yorder} \texttt{src}}{\partial x^{xorder} \partial y^{yorder}}\f] The Sobel operators combine Gaussian smoothing and differentiation, so the result is more or less resistant to the noise. Most often, the function is called with ( xorder = 1, yorder = 0, ksize = 3) or ( xorder = 0, yorder = 1, ksize = 3) to calculate the first x- or y- image derivative. The first case corresponds to a kernel of: \f[\vecthreethree{-1}{0}{1}{-2}{0}{2}{-1}{0}{1}\f] The second case corresponds to a kernel of: \f[\vecthreethree{-1}{-2}{-1}{0}{0}{0}{1}{2}{1}\f] @param src input image. @param dst output image of the same size and the same number of channels as src . @param ddepth output image depth, see @ref filter_depths "combinations"; in the case of 8-bit input images it will result in truncated derivatives. @param dx order of the derivative x. @param dy order of the derivative y. @param ksize size of the extended Sobel kernel; it must be 1, 3, 5, or 7. @param scale optional scale factor for the computed derivative values; by default, no scaling is applied (see cv::getDerivKernels for details). @param delta optional delta value that is added to the results prior to storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa Scharr, Laplacian, sepFilter2D, filter2D, GaussianBlur, cartToPolar */ CV_EXPORTS_W void Sobel( InputArray src, OutputArray dst, int ddepth, int dx, int dy, int ksize = 3, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first order image derivative in both x and y using a Sobel operator Equivalent to calling: @code Sobel( src, dx, CV_16SC1, 1, 0, 3 ); Sobel( src, dy, CV_16SC1, 0, 1, 3 ); @endcode @param src input image. @param dx output image with first-order derivative in x. @param dy output image with first-order derivative in y. @param ksize size of Sobel kernel. It must be 3. @param borderType pixel extrapolation method, see cv::BorderTypes @sa Sobel */ CV_EXPORTS_W void spatialGradient( InputArray src, OutputArray dx, OutputArray dy, int ksize = 3, int borderType = BORDER_DEFAULT ); /** @brief Calculates the first x- or y- image derivative using Scharr operator. The function computes the first x- or y- spatial image derivative using the Scharr operator. The call \f[\texttt{Scharr(src, dst, ddepth, dx, dy, scale, delta, borderType)}\f] is equivalent to \f[\texttt{Sobel(src, dst, ddepth, dx, dy, CV\_SCHARR, scale, delta, borderType)} .\f] @param src input image. @param dst output image of the same size and the same number of channels as src. @param ddepth output image depth, see @ref filter_depths "combinations" @param dx order of the derivative x. @param dy order of the derivative y. @param scale optional scale factor for the computed derivative values; by default, no scaling is applied (see getDerivKernels for details). @param delta optional delta value that is added to the results prior to storing them in dst. @param borderType pixel extrapolation method, see cv::BorderTypes @sa cartToPolar */ CV_EXPORTS_W void Scharr( InputArray src, OutputArray dst, int ddepth, int dx, int dy, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); /** @example laplace.cpp An example using Laplace transformations for edge detection */ /** @brief Calculates the Laplacian of an image. The function calculates the Laplacian of the source image by adding up the second x and y derivatives calculated using the Sobel operator: \f[\texttt{dst} = \Delta \texttt{src} = \frac{\partial^2 \texttt{src}}{\partial x^2} + \frac{\partial^2 \texttt{src}}{\partial y^2}\f] This is done when `ksize > 1`. When `ksize == 1`, the Laplacian is computed by filtering the image with the following \f$3 \times 3\f$ aperture: \f[\vecthreethree {0}{1}{0}{1}{-4}{1}{0}{1}{0}\f] @param src Source image. @param dst Destination image of the same size and the same number of channels as src . @param ddepth Desired depth of the destination image. @param ksize Aperture size used to compute the second-derivative filters. See getDerivKernels for details. The size must be positive and odd. @param scale Optional scale factor for the computed Laplacian values. By default, no scaling is applied. See getDerivKernels for details. @param delta Optional delta value that is added to the results prior to storing them in dst . @param borderType Pixel extrapolation method, see cv::BorderTypes @sa Sobel, Scharr */ CV_EXPORTS_W void Laplacian( InputArray src, OutputArray dst, int ddepth, int ksize = 1, double scale = 1, double delta = 0, int borderType = BORDER_DEFAULT ); //! @} imgproc_filter //! @addtogroup imgproc_feature //! @{ /** @example edge.cpp An example on using the canny edge detector */ /** @brief Finds edges in an image using the Canny algorithm @cite Canny86 . The function finds edges in the input image image and marks them in the output map edges using the Canny algorithm. The smallest value between threshold1 and threshold2 is used for edge linking. The largest value is used to find initial segments of strong edges. See <http://en.wikipedia.org/wiki/Canny_edge_detector> @param image 8-bit input image. @param edges output edge map; single channels 8-bit image, which has the same size as image . @param threshold1 first threshold for the hysteresis procedure. @param threshold2 second threshold for the hysteresis procedure. @param apertureSize aperture size for the Sobel operator. @param L2gradient a flag, indicating whether a more accurate \f$L_2\f$ norm \f$=\sqrt{(dI/dx)^2 + (dI/dy)^2}\f$ should be used to calculate the image gradient magnitude ( L2gradient=true ), or whether the default \f$L_1\f$ norm \f$=|dI/dx|+|dI/dy|\f$ is enough ( L2gradient=false ). */ CV_EXPORTS_W void Canny( InputArray image, OutputArray edges, double threshold1, double threshold2, int apertureSize = 3, bool L2gradient = false ); /** \overload Finds edges in an image using the Canny algorithm with custom image gradient. @param dx 16-bit x derivative of input image (CV_16SC1 or CV_16SC3). @param dy 16-bit y derivative of input image (same type as dx). @param edges,threshold1,threshold2,L2gradient See cv::Canny */ CV_EXPORTS_W void Canny( InputArray dx, InputArray dy, OutputArray edges, double threshold1, double threshold2, bool L2gradient = false ); /** @brief Calculates the minimal eigenvalue of gradient matrices for corner detection. The function is similar to cornerEigenValsAndVecs but it calculates and stores only the minimal eigenvalue of the covariance matrix of derivatives, that is, \f$\min(\lambda_1, \lambda_2)\f$ in terms of the formulae in the cornerEigenValsAndVecs description. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the minimal eigenvalues. It has the type CV_32FC1 and the same size as src . @param blockSize Neighborhood size (see the details on cornerEigenValsAndVecs ). @param ksize Aperture parameter for the Sobel operator. @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void cornerMinEigenVal( InputArray src, OutputArray dst, int blockSize, int ksize = 3, int borderType = BORDER_DEFAULT ); /** @brief Harris corner detector. The function runs the Harris corner detector on the image. Similarly to cornerMinEigenVal and cornerEigenValsAndVecs , for each pixel \f$(x, y)\f$ it calculates a \f$2\times2\f$ gradient covariance matrix \f$M^{(x,y)}\f$ over a \f$\texttt{blockSize} \times \texttt{blockSize}\f$ neighborhood. Then, it computes the following characteristic: \f[\texttt{dst} (x,y) = \mathrm{det} M^{(x,y)} - k \cdot \left ( \mathrm{tr} M^{(x,y)} \right )^2\f] Corners in the image can be found as the local maxima of this response map. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the Harris detector responses. It has the type CV_32FC1 and the same size as src . @param blockSize Neighborhood size (see the details on cornerEigenValsAndVecs ). @param ksize Aperture parameter for the Sobel operator. @param k Harris detector free parameter. See the formula below. @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void cornerHarris( InputArray src, OutputArray dst, int blockSize, int ksize, double k, int borderType = BORDER_DEFAULT ); /** @brief Calculates eigenvalues and eigenvectors of image blocks for corner detection. For every pixel \f$p\f$ , the function cornerEigenValsAndVecs considers a blockSize \f$\times\f$ blockSize neighborhood \f$S(p)\f$ . It calculates the covariation matrix of derivatives over the neighborhood as: \f[M = \begin{bmatrix} \sum _{S(p)}(dI/dx)^2 & \sum _{S(p)}dI/dx dI/dy \\ \sum _{S(p)}dI/dx dI/dy & \sum _{S(p)}(dI/dy)^2 \end{bmatrix}\f] where the derivatives are computed using the Sobel operator. After that, it finds eigenvectors and eigenvalues of \f$M\f$ and stores them in the destination image as \f$(\lambda_1, \lambda_2, x_1, y_1, x_2, y_2)\f$ where - \f$\lambda_1, \lambda_2\f$ are the non-sorted eigenvalues of \f$M\f$ - \f$x_1, y_1\f$ are the eigenvectors corresponding to \f$\lambda_1\f$ - \f$x_2, y_2\f$ are the eigenvectors corresponding to \f$\lambda_2\f$ The output of the function can be used for robust edge or corner detection. @param src Input single-channel 8-bit or floating-point image. @param dst Image to store the results. It has the same size as src and the type CV_32FC(6) . @param blockSize Neighborhood size (see details below). @param ksize Aperture parameter for the Sobel operator. @param borderType Pixel extrapolation method. See cv::BorderTypes. @sa cornerMinEigenVal, cornerHarris, preCornerDetect */ CV_EXPORTS_W void cornerEigenValsAndVecs( InputArray src, OutputArray dst, int blockSize, int ksize, int borderType = BORDER_DEFAULT ); /** @brief Calculates a feature map for corner detection. The function calculates the complex spatial derivative-based function of the source image \f[\texttt{dst} = (D_x \texttt{src} )^2 \cdot D_{yy} \texttt{src} + (D_y \texttt{src} )^2 \cdot D_{xx} \texttt{src} - 2 D_x \texttt{src} \cdot D_y \texttt{src} \cdot D_{xy} \texttt{src}\f] where \f$D_x\f$,\f$D_y\f$ are the first image derivatives, \f$D_{xx}\f$,\f$D_{yy}\f$ are the second image derivatives, and \f$D_{xy}\f$ is the mixed derivative. The corners can be found as local maximums of the functions, as shown below: @code Mat corners, dilated_corners; preCornerDetect(image, corners, 3); // dilation with 3x3 rectangular structuring element dilate(corners, dilated_corners, Mat(), 1); Mat corner_mask = corners == dilated_corners; @endcode @param src Source single-channel 8-bit of floating-point image. @param dst Output image that has the type CV_32F and the same size as src . @param ksize %Aperture size of the Sobel . @param borderType Pixel extrapolation method. See cv::BorderTypes. */ CV_EXPORTS_W void preCornerDetect( InputArray src, OutputArray dst, int ksize, int borderType = BORDER_DEFAULT ); /** @brief Refines the corner locations. The function iterates to find the sub-pixel accurate location of corners or radial saddle points, as shown on the figure below. ![image](pics/cornersubpix.png) Sub-pixel accurate corner locator is based on the observation that every vector from the center \f$q\f$ to a point \f$p\f$ located within a neighborhood of \f$q\f$ is orthogonal to the image gradient at \f$p\f$ subject to image and measurement noise. Consider the expression: \f[\epsilon _i = {DI_{p_i}}^T \cdot (q - p_i)\f] where \f${DI_{p_i}}\f$ is an image gradient at one of the points \f$p_i\f$ in a neighborhood of \f$q\f$ . The value of \f$q\f$ is to be found so that \f$\epsilon_i\f$ is minimized. A system of equations may be set up with \f$\epsilon_i\f$ set to zero: \f[\sum _i(DI_{p_i} \cdot {DI_{p_i}}^T) - \sum _i(DI_{p_i} \cdot {DI_{p_i}}^T \cdot p_i)\f] where the gradients are summed within a neighborhood ("search window") of \f$q\f$ . Calling the first gradient term \f$G\f$ and the second gradient term \f$b\f$ gives: \f[q = G^{-1} \cdot b\f] The algorithm sets the center of the neighborhood window at this new center \f$q\f$ and then iterates until the center stays within a set threshold. @param image Input image. @param corners Initial coordinates of the input corners and refined coordinates provided for output. @param winSize Half of the side length of the search window. For example, if winSize=Size(5,5) , then a \f$5*2+1 \times 5*2+1 = 11 \times 11\f$ search window is used. @param zeroZone Half of the size of the dead region in the middle of the search zone over which the summation in the formula below is not done. It is used sometimes to avoid possible singularities of the autocorrelation matrix. The value of (-1,-1) indicates that there is no such a size. @param criteria Criteria for termination of the iterative process of corner refinement. That is, the process of corner position refinement stops either after criteria.maxCount iterations or when the corner position moves by less than criteria.epsilon on some iteration. */ CV_EXPORTS_W void cornerSubPix( InputArray image, InputOutputArray corners, Size winSize, Size zeroZone, TermCriteria criteria ); /** @brief Determines strong corners on an image. The function finds the most prominent corners in the image or in the specified image region, as described in @cite Shi94 - Function calculates the corner quality measure at every source image pixel using the cornerMinEigenVal or cornerHarris . - Function performs a non-maximum suppression (the local maximums in *3 x 3* neighborhood are retained). - The corners with the minimal eigenvalue less than \f$\texttt{qualityLevel} \cdot \max_{x,y} qualityMeasureMap(x,y)\f$ are rejected. - The remaining corners are sorted by the quality measure in the descending order. - Function throws away each corner for which there is a stronger corner at a distance less than maxDistance. The function can be used to initialize a point-based tracker of an object. @note If the function is called with different values A and B of the parameter qualityLevel , and A \> B, the vector of returned corners with qualityLevel=A will be the prefix of the output vector with qualityLevel=B . @param image Input 8-bit or floating-point 32-bit, single-channel image. @param corners Output vector of detected corners. @param maxCorners Maximum number of corners to return. If there are more corners than are found, the strongest of them is returned. `maxCorners <= 0` implies that no limit on the maximum is set and all detected corners are returned. @param qualityLevel Parameter characterizing the minimal accepted quality of image corners. The parameter value is multiplied by the best corner quality measure, which is the minimal eigenvalue (see cornerMinEigenVal ) or the Harris function response (see cornerHarris ). The corners with the quality measure less than the product are rejected. For example, if the best corner has the quality measure = 1500, and the qualityLevel=0.01 , then all the corners with the quality measure less than 15 are rejected. @param minDistance Minimum possible Euclidean distance between the returned corners. @param mask Optional region of interest. If the image is not empty (it needs to have the type CV_8UC1 and the same size as image ), it specifies the region in which the corners are detected. @param blockSize Size of an average block for computing a derivative covariation matrix over each pixel neighborhood. See cornerEigenValsAndVecs . @param useHarrisDetector Parameter indicating whether to use a Harris detector (see cornerHarris) or cornerMinEigenVal. @param k Free parameter of the Harris detector. @sa cornerMinEigenVal, cornerHarris, calcOpticalFlowPyrLK, estimateRigidTransform, */ CV_EXPORTS_W void goodFeaturesToTrack( InputArray image, OutputArray corners, int maxCorners, double qualityLevel, double minDistance, InputArray mask = noArray(), int blockSize = 3, bool useHarrisDetector = false, double k = 0.04 ); /** @example houghlines.cpp An example using the Hough line detector */ /** @brief Finds lines in a binary image using the standard Hough transform. The function implements the standard or standard multi-scale Hough transform algorithm for line detection. See <http://homepages.inf.ed.ac.uk/rbf/HIPR2/hough.htm> for a good explanation of Hough transform. @param image 8-bit, single-channel binary source image. The image may be modified by the function. @param lines Output vector of lines. Each line is represented by a two-element vector \f$(\rho, \theta)\f$ . \f$\rho\f$ is the distance from the coordinate origin \f$(0,0)\f$ (top-left corner of the image). \f$\theta\f$ is the line rotation angle in radians ( \f$0 \sim \textrm{vertical line}, \pi/2 \sim \textrm{horizontal line}\f$ ). @param rho Distance resolution of the accumulator in pixels. @param theta Angle resolution of the accumulator in radians. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough votes ( \f$>\texttt{threshold}\f$ ). @param srn For the multi-scale Hough transform, it is a divisor for the distance resolution rho . The coarse accumulator distance resolution is rho and the accurate accumulator resolution is rho/srn . If both srn=0 and stn=0 , the classical Hough transform is used. Otherwise, both these parameters should be positive. @param stn For the multi-scale Hough transform, it is a divisor for the distance resolution theta. @param min_theta For standard and multi-scale Hough transform, minimum angle to check for lines. Must fall between 0 and max_theta. @param max_theta For standard and multi-scale Hough transform, maximum angle to check for lines. Must fall between min_theta and CV_PI. */ CV_EXPORTS_W void HoughLines( InputArray image, OutputArray lines, double rho, double theta, int threshold, double srn = 0, double stn = 0, double min_theta = 0, double max_theta = CV_PI ); /** @brief Finds line segments in a binary image using the probabilistic Hough transform. The function implements the probabilistic Hough transform algorithm for line detection, described in @cite Matas00 See the line detection example below: @code #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat src, dst, color_dst; if( argc != 2 || !(src=imread(argv[1], 0)).data) return -1; Canny( src, dst, 50, 200, 3 ); cvtColor( dst, color_dst, COLOR_GRAY2BGR ); #if 0 vector<Vec2f> lines; HoughLines( dst, lines, 1, CV_PI/180, 100 ); for( size_t i = 0; i < lines.size(); i++ ) { float rho = lines[i][0]; float theta = lines[i][1]; double a = cos(theta), b = sin(theta); double x0 = a*rho, y0 = b*rho; Point pt1(cvRound(x0 + 1000*(-b)), cvRound(y0 + 1000*(a))); Point pt2(cvRound(x0 - 1000*(-b)), cvRound(y0 - 1000*(a))); line( color_dst, pt1, pt2, Scalar(0,0,255), 3, 8 ); } #else vector<Vec4i> lines; HoughLinesP( dst, lines, 1, CV_PI/180, 80, 30, 10 ); for( size_t i = 0; i < lines.size(); i++ ) { line( color_dst, Point(lines[i][0], lines[i][1]), Point(lines[i][2], lines[i][3]), Scalar(0,0,255), 3, 8 ); } #endif namedWindow( "Source", 1 ); imshow( "Source", src ); namedWindow( "Detected Lines", 1 ); imshow( "Detected Lines", color_dst ); waitKey(0); return 0; } @endcode This is a sample picture the function parameters have been tuned for: ![image](pics/building.jpg) And this is the output of the above program in case of the probabilistic Hough transform: ![image](pics/houghp.png) @param image 8-bit, single-channel binary source image. The image may be modified by the function. @param lines Output vector of lines. Each line is represented by a 4-element vector \f$(x_1, y_1, x_2, y_2)\f$ , where \f$(x_1,y_1)\f$ and \f$(x_2, y_2)\f$ are the ending points of each detected line segment. @param rho Distance resolution of the accumulator in pixels. @param theta Angle resolution of the accumulator in radians. @param threshold Accumulator threshold parameter. Only those lines are returned that get enough votes ( \f$>\texttt{threshold}\f$ ). @param minLineLength Minimum line length. Line segments shorter than that are rejected. @param maxLineGap Maximum allowed gap between points on the same line to link them. @sa LineSegmentDetector */ CV_EXPORTS_W void HoughLinesP( InputArray image, OutputArray lines, double rho, double theta, int threshold, double minLineLength = 0, double maxLineGap = 0 ); /** @example houghcircles.cpp An example using the Hough circle detector */ /** @brief Finds circles in a grayscale image using the Hough transform. The function finds circles in a grayscale image using a modification of the Hough transform. Example: : @code #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> #include <math.h> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat img, gray; if( argc != 2 || !(img=imread(argv[1], 1)).data) return -1; cvtColor(img, gray, COLOR_BGR2GRAY); // smooth it, otherwise a lot of false circles may be detected GaussianBlur( gray, gray, Size(9, 9), 2, 2 ); vector<Vec3f> circles; HoughCircles(gray, circles, HOUGH_GRADIENT, 2, gray.rows/4, 200, 100 ); for( size_t i = 0; i < circles.size(); i++ ) { Point center(cvRound(circles[i][0]), cvRound(circles[i][1])); int radius = cvRound(circles[i][2]); // draw the circle center circle( img, center, 3, Scalar(0,255,0), -1, 8, 0 ); // draw the circle outline circle( img, center, radius, Scalar(0,0,255), 3, 8, 0 ); } namedWindow( "circles", 1 ); imshow( "circles", img ); waitKey(0); return 0; } @endcode @note Usually the function detects the centers of circles well. However, it may fail to find correct radii. You can assist to the function by specifying the radius range ( minRadius and maxRadius ) if you know it. Or, you may ignore the returned radius, use only the center, and find the correct radius using an additional procedure. @param image 8-bit, single-channel, grayscale input image. @param circles Output vector of found circles. Each vector is encoded as a 3-element floating-point vector \f$(x, y, radius)\f$ . @param method Detection method, see cv::HoughModes. Currently, the only implemented method is HOUGH_GRADIENT @param dp Inverse ratio of the accumulator resolution to the image resolution. For example, if dp=1 , the accumulator has the same resolution as the input image. If dp=2 , the accumulator has half as big width and height. @param minDist Minimum distance between the centers of the detected circles. If the parameter is too small, multiple neighbor circles may be falsely detected in addition to a true one. If it is too large, some circles may be missed. @param param1 First method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the higher threshold of the two passed to the Canny edge detector (the lower one is twice smaller). @param param2 Second method-specific parameter. In case of CV_HOUGH_GRADIENT , it is the accumulator threshold for the circle centers at the detection stage. The smaller it is, the more false circles may be detected. Circles, corresponding to the larger accumulator values, will be returned first. @param minRadius Minimum circle radius. @param maxRadius Maximum circle radius. @sa fitEllipse, minEnclosingCircle */ CV_EXPORTS_W void HoughCircles( InputArray image, OutputArray circles, int method, double dp, double minDist, double param1 = 100, double param2 = 100, int minRadius = 0, int maxRadius = 0 ); //! @} imgproc_feature //! @addtogroup imgproc_filter //! @{ /** @example morphology2.cpp An example using the morphological operations */ /** @brief Erodes an image by using a specific structuring element. The function erodes the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the minimum is taken: \f[\texttt{dst} (x,y) = \min _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] The function supports the in-place mode. Erosion can be applied several ( iterations ) times. In case of multi-channel images, each channel is processed independently. @param src input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src. @param kernel structuring element used for erosion; if `element=Mat()`, a `3 x 3` rectangular structuring element is used. Kernel can be created using getStructuringElement. @param anchor position of the anchor within the element; default value (-1, -1) means that the anchor is at the element center. @param iterations number of times erosion is applied. @param borderType pixel extrapolation method, see cv::BorderTypes @param borderValue border value in case of a constant border @sa dilate, morphologyEx, getStructuringElement */ CV_EXPORTS_W void erode( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); /** @brief Dilates an image by using a specific structuring element. The function dilates the source image using the specified structuring element that determines the shape of a pixel neighborhood over which the maximum is taken: \f[\texttt{dst} (x,y) = \max _{(x',y'): \, \texttt{element} (x',y') \ne0 } \texttt{src} (x+x',y+y')\f] The function supports the in-place mode. Dilation can be applied several ( iterations ) times. In case of multi-channel images, each channel is processed independently. @param src input image; the number of channels can be arbitrary, but the depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst output image of the same size and type as src\`. @param kernel structuring element used for dilation; if elemenat=Mat(), a 3 x 3 rectangular structuring element is used. Kernel can be created using getStructuringElement @param anchor position of the anchor within the element; default value (-1, -1) means that the anchor is at the element center. @param iterations number of times dilation is applied. @param borderType pixel extrapolation method, see cv::BorderTypes @param borderValue border value in case of a constant border @sa erode, morphologyEx, getStructuringElement */ CV_EXPORTS_W void dilate( InputArray src, OutputArray dst, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); /** @brief Performs advanced morphological transformations. The function morphologyEx can perform advanced morphological transformations using an erosion and dilation as basic operations. Any of the operations can be done in-place. In case of multi-channel images, each channel is processed independently. @param src Source image. The number of channels can be arbitrary. The depth should be one of CV_8U, CV_16U, CV_16S, CV_32F or CV_64F. @param dst Destination image of the same size and type as source image. @param op Type of a morphological operation, see cv::MorphTypes @param kernel Structuring element. It can be created using cv::getStructuringElement. @param anchor Anchor position with the kernel. Negative values mean that the anchor is at the kernel center. @param iterations Number of times erosion and dilation are applied. @param borderType Pixel extrapolation method, see cv::BorderTypes @param borderValue Border value in case of a constant border. The default value has a special meaning. @sa dilate, erode, getStructuringElement */ CV_EXPORTS_W void morphologyEx( InputArray src, OutputArray dst, int op, InputArray kernel, Point anchor = Point(-1,-1), int iterations = 1, int borderType = BORDER_CONSTANT, const Scalar& borderValue = morphologyDefaultBorderValue() ); //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ /** @brief Resizes an image. The function resize resizes the image src down to or up to the specified size. Note that the initial dst type or size are not taken into account. Instead, the size and type are derived from the `src`,`dsize`,`fx`, and `fy`. If you want to resize src so that it fits the pre-created dst, you may call the function as follows: @code // explicitly specify dsize=dst.size(); fx and fy will be computed from that. resize(src, dst, dst.size(), 0, 0, interpolation); @endcode If you want to decimate the image by factor of 2 in each direction, you can call the function this way: @code // specify fx and fy and let the function compute the destination image size. resize(src, dst, Size(), 0.5, 0.5, interpolation); @endcode To shrink an image, it will generally look best with cv::INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with cv::INTER_CUBIC (slow) or cv::INTER_LINEAR (faster but still looks OK). @param src input image. @param dst output image; it has the size dsize (when it is non-zero) or the size computed from src.size(), fx, and fy; the type of dst is the same as of src. @param dsize output image size; if it equals zero, it is computed as: \f[\texttt{dsize = Size(round(fx*src.cols), round(fy*src.rows))}\f] Either dsize or both fx and fy must be non-zero. @param fx scale factor along the horizontal axis; when it equals 0, it is computed as \f[\texttt{(double)dsize.width/src.cols}\f] @param fy scale factor along the vertical axis; when it equals 0, it is computed as \f[\texttt{(double)dsize.height/src.rows}\f] @param interpolation interpolation method, see cv::InterpolationFlags @sa warpAffine, warpPerspective, remap */ CV_EXPORTS_W void resize( InputArray src, OutputArray dst, Size dsize, double fx = 0, double fy = 0, int interpolation = INTER_LINEAR ); /** @brief Applies an affine transformation to an image. The function warpAffine transforms the source image using the specified matrix: \f[\texttt{dst} (x,y) = \texttt{src} ( \texttt{M} _{11} x + \texttt{M} _{12} y + \texttt{M} _{13}, \texttt{M} _{21} x + \texttt{M} _{22} y + \texttt{M} _{23})\f] when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with cv::invertAffineTransform and then put in the formula above instead of M. The function cannot operate in-place. @param src input image. @param dst output image that has the size dsize and the same type as src . @param M \f$2\times 3\f$ transformation matrix. @param dsize size of the output image. @param flags combination of interpolation methods (see cv::InterpolationFlags) and the optional flag WARP_INVERSE_MAP that means that M is the inverse transformation ( \f$\texttt{dst}\rightarrow\texttt{src}\f$ ). @param borderMode pixel extrapolation method (see cv::BorderTypes); when borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image corresponding to the "outliers" in the source image are not modified by the function. @param borderValue value used in case of a constant border; by default, it is 0. @sa warpPerspective, resize, remap, getRectSubPix, transform */ CV_EXPORTS_W void warpAffine( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Applies a perspective transformation to an image. The function warpPerspective transforms the source image using the specified matrix: \f[\texttt{dst} (x,y) = \texttt{src} \left ( \frac{M_{11} x + M_{12} y + M_{13}}{M_{31} x + M_{32} y + M_{33}} , \frac{M_{21} x + M_{22} y + M_{23}}{M_{31} x + M_{32} y + M_{33}} \right )\f] when the flag WARP_INVERSE_MAP is set. Otherwise, the transformation is first inverted with invert and then put in the formula above instead of M. The function cannot operate in-place. @param src input image. @param dst output image that has the size dsize and the same type as src . @param M \f$3\times 3\f$ transformation matrix. @param dsize size of the output image. @param flags combination of interpolation methods (INTER_LINEAR or INTER_NEAREST) and the optional flag WARP_INVERSE_MAP, that sets M as the inverse transformation ( \f$\texttt{dst}\rightarrow\texttt{src}\f$ ). @param borderMode pixel extrapolation method (BORDER_CONSTANT or BORDER_REPLICATE). @param borderValue value used in case of a constant border; by default, it equals 0. @sa warpAffine, resize, remap, getRectSubPix, perspectiveTransform */ CV_EXPORTS_W void warpPerspective( InputArray src, OutputArray dst, InputArray M, Size dsize, int flags = INTER_LINEAR, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Applies a generic geometrical transformation to an image. The function remap transforms the source image using the specified map: \f[\texttt{dst} (x,y) = \texttt{src} (map_x(x,y),map_y(x,y))\f] where values of pixels with non-integer coordinates are computed using one of available interpolation methods. \f$map_x\f$ and \f$map_y\f$ can be encoded as separate floating-point maps in \f$map_1\f$ and \f$map_2\f$ respectively, or interleaved floating-point maps of \f$(x,y)\f$ in \f$map_1\f$, or fixed-point maps created by using convertMaps. The reason you might want to convert from floating to fixed-point representations of a map is that they can yield much faster (\~2x) remapping operations. In the converted case, \f$map_1\f$ contains pairs (cvFloor(x), cvFloor(y)) and \f$map_2\f$ contains indices in a table of interpolation coefficients. This function cannot operate in-place. @param src Source image. @param dst Destination image. It has the same size as map1 and the same type as src . @param map1 The first map of either (x,y) points or just x values having the type CV_16SC2 , CV_32FC1, or CV_32FC2. See convertMaps for details on converting a floating point representation to fixed-point for speed. @param map2 The second map of y values having the type CV_16UC1, CV_32FC1, or none (empty map if map1 is (x,y) points), respectively. @param interpolation Interpolation method (see cv::InterpolationFlags). The method INTER_AREA is not supported by this function. @param borderMode Pixel extrapolation method (see cv::BorderTypes). When borderMode=BORDER_TRANSPARENT, it means that the pixels in the destination image that corresponds to the "outliers" in the source image are not modified by the function. @param borderValue Value used in case of a constant border. By default, it is 0. @note Due to current implementaion limitations the size of an input and output images should be less than 32767x32767. */ CV_EXPORTS_W void remap( InputArray src, OutputArray dst, InputArray map1, InputArray map2, int interpolation, int borderMode = BORDER_CONSTANT, const Scalar& borderValue = Scalar()); /** @brief Converts image transformation maps from one representation to another. The function converts a pair of maps for remap from one representation to another. The following options ( (map1.type(), map2.type()) \f$\rightarrow\f$ (dstmap1.type(), dstmap2.type()) ) are supported: - \f$\texttt{(CV_32FC1, CV_32FC1)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. This is the most frequently used conversion operation, in which the original floating-point maps (see remap ) are converted to a more compact and much faster fixed-point representation. The first output array contains the rounded coordinates and the second array (created only when nninterpolation=false ) contains indices in the interpolation tables. - \f$\texttt{(CV_32FC2)} \rightarrow \texttt{(CV_16SC2, CV_16UC1)}\f$. The same as above but the original maps are stored in one 2-channel matrix. - Reverse conversion. Obviously, the reconstructed floating-point maps will not be exactly the same as the originals. @param map1 The first input map of type CV_16SC2, CV_32FC1, or CV_32FC2 . @param map2 The second input map of type CV_16UC1, CV_32FC1, or none (empty matrix), respectively. @param dstmap1 The first output map that has the type dstmap1type and the same size as src . @param dstmap2 The second output map. @param dstmap1type Type of the first output map that should be CV_16SC2, CV_32FC1, or CV_32FC2 . @param nninterpolation Flag indicating whether the fixed-point maps are used for the nearest-neighbor or for a more complex interpolation. @sa remap, undistort, initUndistortRectifyMap */ CV_EXPORTS_W void convertMaps( InputArray map1, InputArray map2, OutputArray dstmap1, OutputArray dstmap2, int dstmap1type, bool nninterpolation = false ); /** @brief Calculates an affine matrix of 2D rotation. The function calculates the following matrix: \f[\begin{bmatrix} \alpha & \beta & (1- \alpha ) \cdot \texttt{center.x} - \beta \cdot \texttt{center.y} \\ - \beta & \alpha & \beta \cdot \texttt{center.x} + (1- \alpha ) \cdot \texttt{center.y} \end{bmatrix}\f] where \f[\begin{array}{l} \alpha = \texttt{scale} \cdot \cos \texttt{angle} , \\ \beta = \texttt{scale} \cdot \sin \texttt{angle} \end{array}\f] The transformation maps the rotation center to itself. If this is not the target, adjust the shift. @param center Center of the rotation in the source image. @param angle Rotation angle in degrees. Positive values mean counter-clockwise rotation (the coordinate origin is assumed to be the top-left corner). @param scale Isotropic scale factor. @sa getAffineTransform, warpAffine, transform */ CV_EXPORTS_W Mat getRotationMatrix2D( Point2f center, double angle, double scale ); //! returns 3x3 perspective transformation for the corresponding 4 point pairs. CV_EXPORTS Mat getPerspectiveTransform( const Point2f src[], const Point2f dst[] ); /** @brief Calculates an affine transform from three pairs of the corresponding points. The function calculates the \f$2 \times 3\f$ matrix of an affine transform so that: \f[\begin{bmatrix} x'_i \\ y'_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] where \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2\f] @param src Coordinates of triangle vertices in the source image. @param dst Coordinates of the corresponding triangle vertices in the destination image. @sa warpAffine, transform */ CV_EXPORTS Mat getAffineTransform( const Point2f src[], const Point2f dst[] ); /** @brief Inverts an affine transformation. The function computes an inverse affine transformation represented by \f$2 \times 3\f$ matrix M: \f[\begin{bmatrix} a_{11} & a_{12} & b_1 \\ a_{21} & a_{22} & b_2 \end{bmatrix}\f] The result is also a \f$2 \times 3\f$ matrix of the same type as M. @param M Original affine transformation. @param iM Output reverse affine transformation. */ CV_EXPORTS_W void invertAffineTransform( InputArray M, OutputArray iM ); /** @brief Calculates a perspective transform from four pairs of the corresponding points. The function calculates the \f$3 \times 3\f$ matrix of a perspective transform so that: \f[\begin{bmatrix} t_i x'_i \\ t_i y'_i \\ t_i \end{bmatrix} = \texttt{map_matrix} \cdot \begin{bmatrix} x_i \\ y_i \\ 1 \end{bmatrix}\f] where \f[dst(i)=(x'_i,y'_i), src(i)=(x_i, y_i), i=0,1,2,3\f] @param src Coordinates of quadrangle vertices in the source image. @param dst Coordinates of the corresponding quadrangle vertices in the destination image. @sa findHomography, warpPerspective, perspectiveTransform */ CV_EXPORTS_W Mat getPerspectiveTransform( InputArray src, InputArray dst ); CV_EXPORTS_W Mat getAffineTransform( InputArray src, InputArray dst ); /** @brief Retrieves a pixel rectangle from an image with sub-pixel accuracy. The function getRectSubPix extracts pixels from src: \f[dst(x, y) = src(x + \texttt{center.x} - ( \texttt{dst.cols} -1)*0.5, y + \texttt{center.y} - ( \texttt{dst.rows} -1)*0.5)\f] where the values of the pixels at non-integer coordinates are retrieved using bilinear interpolation. Every channel of multi-channel images is processed independently. While the center of the rectangle must be inside the image, parts of the rectangle may be outside. In this case, the replication border mode (see cv::BorderTypes) is used to extrapolate the pixel values outside of the image. @param image Source image. @param patchSize Size of the extracted patch. @param center Floating point coordinates of the center of the extracted rectangle within the source image. The center must be inside the image. @param patch Extracted patch that has the size patchSize and the same number of channels as src . @param patchType Depth of the extracted pixels. By default, they have the same depth as src . @sa warpAffine, warpPerspective */ CV_EXPORTS_W void getRectSubPix( InputArray image, Size patchSize, Point2f center, OutputArray patch, int patchType = -1 ); /** @example polar_transforms.cpp An example using the cv::linearPolar and cv::logPolar operations */ /** @brief Remaps an image to semilog-polar coordinates space. Transform the source image using the following transformation (See @ref polar_remaps_reference_image "Polar remaps reference image"): \f[\begin{array}{l} dst( \rho , \phi ) = src(x,y) \\ dst.size() \leftarrow src.size() \end{array}\f] where \f[\begin{array}{l} I = (dx,dy) = (x - center.x,y - center.y) \\ \rho = M \cdot log_e(\texttt{magnitude} (I)) ,\\ \phi = Ky \cdot \texttt{angle} (I)_{0..360 deg} \\ \end{array}\f] and \f[\begin{array}{l} M = src.cols / log_e(maxRadius) \\ Ky = src.rows / 360 \\ \end{array}\f] The function emulates the human "foveal" vision and can be used for fast scale and rotation-invariant template matching, for object tracking and so forth. @param src Source image @param dst Destination image. It will have same size and type as src. @param center The transformation center; where the output precision is maximal @param M Magnitude scale parameter. It determines the radius of the bounding circle to transform too. @param flags A combination of interpolation methods, see cv::InterpolationFlags @note - The function can not operate in-place. - To calculate magnitude and angle in degrees @ref cv::cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. */ CV_EXPORTS_W void logPolar( InputArray src, OutputArray dst, Point2f center, double M, int flags ); /** @brief Remaps an image to polar coordinates space. @anchor polar_remaps_reference_image ![Polar remaps reference](pics/polar_remap_doc.png) Transform the source image using the following transformation: \f[\begin{array}{l} dst( \rho , \phi ) = src(x,y) \\ dst.size() \leftarrow src.size() \end{array}\f] where \f[\begin{array}{l} I = (dx,dy) = (x - center.x,y - center.y) \\ \rho = Kx \cdot \texttt{magnitude} (I) ,\\ \phi = Ky \cdot \texttt{angle} (I)_{0..360 deg} \end{array}\f] and \f[\begin{array}{l} Kx = src.cols / maxRadius \\ Ky = src.rows / 360 \end{array}\f] @param src Source image @param dst Destination image. It will have same size and type as src. @param center The transformation center; @param maxRadius The radius of the bounding circle to transform. It determines the inverse magnitude scale parameter too. @param flags A combination of interpolation methods, see cv::InterpolationFlags @note - The function can not operate in-place. - To calculate magnitude and angle in degrees @ref cv::cartToPolar is used internally thus angles are measured from 0 to 360 with accuracy about 0.3 degrees. */ CV_EXPORTS_W void linearPolar( InputArray src, OutputArray dst, Point2f center, double maxRadius, int flags ); //! @} imgproc_transform //! @addtogroup imgproc_misc //! @{ /** @overload */ CV_EXPORTS_W void integral( InputArray src, OutputArray sum, int sdepth = -1 ); /** @overload */ CV_EXPORTS_AS(integral2) void integral( InputArray src, OutputArray sum, OutputArray sqsum, int sdepth = -1, int sqdepth = -1 ); /** @brief Calculates the integral of an image. The function calculates one or more integral images for the source image as follows: \f[\texttt{sum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)\f] \f[\texttt{sqsum} (X,Y) = \sum _{x<X,y<Y} \texttt{image} (x,y)^2\f] \f[\texttt{tilted} (X,Y) = \sum _{y<Y,abs(x-X+1) \leq Y-y-1} \texttt{image} (x,y)\f] Using these integral images, you can calculate sum, mean, and standard deviation over a specific up-right or rotated rectangular region of the image in a constant time, for example: \f[\sum _{x_1 \leq x < x_2, \, y_1 \leq y < y_2} \texttt{image} (x,y) = \texttt{sum} (x_2,y_2)- \texttt{sum} (x_1,y_2)- \texttt{sum} (x_2,y_1)+ \texttt{sum} (x_1,y_1)\f] It makes possible to do a fast blurring or fast block correlation with a variable window size, for example. In case of multi-channel images, sums for each channel are accumulated independently. As a practical example, the next figure shows the calculation of the integral of a straight rectangle Rect(3,3,3,2) and of a tilted rectangle Rect(5,1,2,3) . The selected pixels in the original image are shown, as well as the relative pixels in the integral images sum and tilted . ![integral calculation example](pics/integral.png) @param src input image as \f$W \times H\f$, 8-bit or floating-point (32f or 64f). @param sum integral image as \f$(W+1)\times (H+1)\f$ , 32-bit integer or floating-point (32f or 64f). @param sqsum integral image for squared pixel values; it is \f$(W+1)\times (H+1)\f$, double-precision floating-point (64f) array. @param tilted integral for the image rotated by 45 degrees; it is \f$(W+1)\times (H+1)\f$ array with the same data type as sum. @param sdepth desired depth of the integral and the tilted integral images, CV_32S, CV_32F, or CV_64F. @param sqdepth desired depth of the integral image of squared pixel values, CV_32F or CV_64F. */ CV_EXPORTS_AS(integral3) void integral( InputArray src, OutputArray sum, OutputArray sqsum, OutputArray tilted, int sdepth = -1, int sqdepth = -1 ); //! @} imgproc_misc //! @addtogroup imgproc_motion //! @{ /** @brief Adds an image to the accumulator. The function adds src or some of its elements to dst : \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f] The function supports multi-channel images. Each channel is processed independently. The functions accumulate\* can be used, for example, to collect statistics of a scene background viewed by a still camera and for the further foreground-background segmentation. @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. @param mask Optional operation mask. @sa accumulateSquare, accumulateProduct, accumulateWeighted */ CV_EXPORTS_W void accumulate( InputArray src, InputOutputArray dst, InputArray mask = noArray() ); /** @brief Adds the square of a source image to the accumulator. The function adds the input image src or its selected region, raised to a power of 2, to the accumulator dst : \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src} (x,y)^2 \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f] The function supports multi-channel images. Each channel is processed independently. @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. @param mask Optional operation mask. @sa accumulateSquare, accumulateProduct, accumulateWeighted */ CV_EXPORTS_W void accumulateSquare( InputArray src, InputOutputArray dst, InputArray mask = noArray() ); /** @brief Adds the per-element product of two input images to the accumulator. The function adds the product of two images or their selected regions to the accumulator dst : \f[\texttt{dst} (x,y) \leftarrow \texttt{dst} (x,y) + \texttt{src1} (x,y) \cdot \texttt{src2} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f] The function supports multi-channel images. Each channel is processed independently. @param src1 First input image, 1- or 3-channel, 8-bit or 32-bit floating point. @param src2 Second input image of the same type and the same size as src1 . @param dst %Accumulator with the same number of channels as input images, 32-bit or 64-bit floating-point. @param mask Optional operation mask. @sa accumulate, accumulateSquare, accumulateWeighted */ CV_EXPORTS_W void accumulateProduct( InputArray src1, InputArray src2, InputOutputArray dst, InputArray mask=noArray() ); /** @brief Updates a running average. The function calculates the weighted sum of the input image src and the accumulator dst so that dst becomes a running average of a frame sequence: \f[\texttt{dst} (x,y) \leftarrow (1- \texttt{alpha} ) \cdot \texttt{dst} (x,y) + \texttt{alpha} \cdot \texttt{src} (x,y) \quad \text{if} \quad \texttt{mask} (x,y) \ne 0\f] That is, alpha regulates the update speed (how fast the accumulator "forgets" about earlier images). The function supports multi-channel images. Each channel is processed independently. @param src Input image as 1- or 3-channel, 8-bit or 32-bit floating point. @param dst %Accumulator image with the same number of channels as input image, 32-bit or 64-bit floating-point. @param alpha Weight of the input image. @param mask Optional operation mask. @sa accumulate, accumulateSquare, accumulateProduct */ CV_EXPORTS_W void accumulateWeighted( InputArray src, InputOutputArray dst, double alpha, InputArray mask = noArray() ); /** @brief The function is used to detect translational shifts that occur between two images. The operation takes advantage of the Fourier shift theorem for detecting the translational shift in the frequency domain. It can be used for fast image registration as well as motion estimation. For more information please see <http://en.wikipedia.org/wiki/Phase_correlation> Calculates the cross-power spectrum of two supplied source arrays. The arrays are padded if needed with getOptimalDFTSize. The function performs the following equations: - First it applies a Hanning window (see <http://en.wikipedia.org/wiki/Hann_function>) to each image to remove possible edge effects. This window is cached until the array size changes to speed up processing time. - Next it computes the forward DFTs of each source array: \f[\mathbf{G}_a = \mathcal{F}\{src_1\}, \; \mathbf{G}_b = \mathcal{F}\{src_2\}\f] where \f$\mathcal{F}\f$ is the forward DFT. - It then computes the cross-power spectrum of each frequency domain array: \f[R = \frac{ \mathbf{G}_a \mathbf{G}_b^*}{|\mathbf{G}_a \mathbf{G}_b^*|}\f] - Next the cross-correlation is converted back into the time domain via the inverse DFT: \f[r = \mathcal{F}^{-1}\{R\}\f] - Finally, it computes the peak location and computes a 5x5 weighted centroid around the peak to achieve sub-pixel accuracy. \f[(\Delta x, \Delta y) = \texttt{weightedCentroid} \{\arg \max_{(x, y)}\{r\}\}\f] - If non-zero, the response parameter is computed as the sum of the elements of r within the 5x5 centroid around the peak location. It is normalized to a maximum of 1 (meaning there is a single peak) and will be smaller when there are multiple peaks. @param src1 Source floating point array (CV_32FC1 or CV_64FC1) @param src2 Source floating point array (CV_32FC1 or CV_64FC1) @param window Floating point array with windowing coefficients to reduce edge effects (optional). @param response Signal power within the 5x5 centroid around the peak, between 0 and 1 (optional). @returns detected phase shift (sub-pixel) between the two arrays. @sa dft, getOptimalDFTSize, idft, mulSpectrums createHanningWindow */ CV_EXPORTS_W Point2d phaseCorrelate(InputArray src1, InputArray src2, InputArray window = noArray(), CV_OUT double* response = 0); /** @brief This function computes a Hanning window coefficients in two dimensions. See (http://en.wikipedia.org/wiki/Hann_function) and (http://en.wikipedia.org/wiki/Window_function) for more information. An example is shown below: @code // create hanning window of size 100x100 and type CV_32F Mat hann; createHanningWindow(hann, Size(100, 100), CV_32F); @endcode @param dst Destination array to place Hann coefficients in @param winSize The window size specifications @param type Created array type */ CV_EXPORTS_W void createHanningWindow(OutputArray dst, Size winSize, int type); //! @} imgproc_motion //! @addtogroup imgproc_misc //! @{ /** @brief Applies a fixed-level threshold to each array element. The function applies fixed-level thresholding to a multiple-channel array. The function is typically used to get a bi-level (binary) image out of a grayscale image ( cv::compare could be also used for this purpose) or for removing a noise, that is, filtering out pixels with too small or too large values. There are several types of thresholding supported by the function. They are determined by type parameter. Also, the special values cv::THRESH_OTSU or cv::THRESH_TRIANGLE may be combined with one of the above values. In these cases, the function determines the optimal threshold value using the Otsu's or Triangle algorithm and uses it instead of the specified thresh . The function returns the computed threshold value. Currently, the Otsu's and Triangle methods are implemented only for 8-bit images. @note Input image should be single channel only in case of CV_THRESH_OTSU or CV_THRESH_TRIANGLE flags @param src input array (multiple-channel, 8-bit or 32-bit floating point). @param dst output array of the same size and type and the same number of channels as src. @param thresh threshold value. @param maxval maximum value to use with the THRESH_BINARY and THRESH_BINARY_INV thresholding types. @param type thresholding type (see the cv::ThresholdTypes). @sa adaptiveThreshold, findContours, compare, min, max */ CV_EXPORTS_W double threshold( InputArray src, OutputArray dst, double thresh, double maxval, int type ); /** @brief Applies an adaptive threshold to an array. The function transforms a grayscale image to a binary image according to the formulae: - **THRESH_BINARY** \f[dst(x,y) = \fork{\texttt{maxValue}}{if \(src(x,y) > T(x,y)\)}{0}{otherwise}\f] - **THRESH_BINARY_INV** \f[dst(x,y) = \fork{0}{if \(src(x,y) > T(x,y)\)}{\texttt{maxValue}}{otherwise}\f] where \f$T(x,y)\f$ is a threshold calculated individually for each pixel (see adaptiveMethod parameter). The function can process the image in-place. @param src Source 8-bit single-channel image. @param dst Destination image of the same size and the same type as src. @param maxValue Non-zero value assigned to the pixels for which the condition is satisfied @param adaptiveMethod Adaptive thresholding algorithm to use, see cv::AdaptiveThresholdTypes @param thresholdType Thresholding type that must be either THRESH_BINARY or THRESH_BINARY_INV, see cv::ThresholdTypes. @param blockSize Size of a pixel neighborhood that is used to calculate a threshold value for the pixel: 3, 5, 7, and so on. @param C Constant subtracted from the mean or weighted mean (see the details below). Normally, it is positive but may be zero or negative as well. @sa threshold, blur, GaussianBlur */ CV_EXPORTS_W void adaptiveThreshold( InputArray src, OutputArray dst, double maxValue, int adaptiveMethod, int thresholdType, int blockSize, double C ); //! @} imgproc_misc //! @addtogroup imgproc_filter //! @{ /** @brief Blurs an image and downsamples it. By default, size of the output image is computed as `Size((src.cols+1)/2, (src.rows+1)/2)`, but in any case, the following conditions should be satisfied: \f[\begin{array}{l} | \texttt{dstsize.width} *2-src.cols| \leq 2 \\ | \texttt{dstsize.height} *2-src.rows| \leq 2 \end{array}\f] The function performs the downsampling step of the Gaussian pyramid construction. First, it convolves the source image with the kernel: \f[\frac{1}{256} \begin{bmatrix} 1 & 4 & 6 & 4 & 1 \\ 4 & 16 & 24 & 16 & 4 \\ 6 & 24 & 36 & 24 & 6 \\ 4 & 16 & 24 & 16 & 4 \\ 1 & 4 & 6 & 4 & 1 \end{bmatrix}\f] Then, it downsamples the image by rejecting even rows and columns. @param src input image. @param dst output image; it has the specified size and the same type as src. @param dstsize size of the output image. @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported) */ CV_EXPORTS_W void pyrDown( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); /** @brief Upsamples an image and then blurs it. By default, size of the output image is computed as `Size(src.cols\*2, (src.rows\*2)`, but in any case, the following conditions should be satisfied: \f[\begin{array}{l} | \texttt{dstsize.width} -src.cols*2| \leq ( \texttt{dstsize.width} \mod 2) \\ | \texttt{dstsize.height} -src.rows*2| \leq ( \texttt{dstsize.height} \mod 2) \end{array}\f] The function performs the upsampling step of the Gaussian pyramid construction, though it can actually be used to construct the Laplacian pyramid. First, it upsamples the source image by injecting even zero rows and columns and then convolves the result with the same kernel as in pyrDown multiplied by 4. @param src input image. @param dst output image. It has the specified size and the same type as src . @param dstsize size of the output image. @param borderType Pixel extrapolation method, see cv::BorderTypes (only BORDER_DEFAULT is supported) */ CV_EXPORTS_W void pyrUp( InputArray src, OutputArray dst, const Size& dstsize = Size(), int borderType = BORDER_DEFAULT ); /** @brief Constructs the Gaussian pyramid for an image. The function constructs a vector of images and builds the Gaussian pyramid by recursively applying pyrDown to the previously built pyramid layers, starting from `dst[0]==src`. @param src Source image. Check pyrDown for the list of supported types. @param dst Destination vector of maxlevel+1 images of the same type as src. dst[0] will be the same as src. dst[1] is the next pyramid layer, a smoothed and down-sized src, and so on. @param maxlevel 0-based index of the last (the smallest) pyramid layer. It must be non-negative. @param borderType Pixel extrapolation method, see cv::BorderTypes (BORDER_CONSTANT isn't supported) */ CV_EXPORTS void buildPyramid( InputArray src, OutputArrayOfArrays dst, int maxlevel, int borderType = BORDER_DEFAULT ); //! @} imgproc_filter //! @addtogroup imgproc_transform //! @{ /** @brief Transforms an image to compensate for lens distortion. The function transforms an image to compensate radial and tangential lens distortion. The function is simply a combination of cv::initUndistortRectifyMap (with unity R ) and cv::remap (with bilinear interpolation). See the former function for details of the transformation being performed. Those pixels in the destination image, for which there is no correspondent pixels in the source image, are filled with zeros (black color). A particular subset of the source image that will be visible in the corrected image can be regulated by newCameraMatrix. You can use cv::getOptimalNewCameraMatrix to compute the appropriate newCameraMatrix depending on your requirements. The camera matrix and the distortion parameters can be determined using cv::calibrateCamera. If the resolution of images is different from the resolution used at the calibration stage, \f$f_x, f_y, c_x\f$ and \f$c_y\f$ need to be scaled accordingly, while the distortion coefficients remain the same. @param src Input (distorted) image. @param dst Output (corrected) image that has the same size and type as src . @param cameraMatrix Input camera matrix \f$A = \vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param newCameraMatrix Camera matrix of the distorted image. By default, it is the same as cameraMatrix but you may additionally scale and shift the result by using a different matrix. */ CV_EXPORTS_W void undistort( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray newCameraMatrix = noArray() ); /** @brief Computes the undistortion and rectification transformation map. The function computes the joint undistortion and rectification transformation and represents the result in the form of maps for remap. The undistorted image looks like original, as if it is captured with a camera using the camera matrix =newCameraMatrix and zero distortion. In case of a monocular camera, newCameraMatrix is usually equal to cameraMatrix, or it can be computed by cv::getOptimalNewCameraMatrix for a better control over scaling. In case of a stereo camera, newCameraMatrix is normally set to P1 or P2 computed by cv::stereoRectify . Also, this new camera is oriented differently in the coordinate space, according to R. That, for example, helps to align two heads of a stereo camera so that the epipolar lines on both images become horizontal and have the same y- coordinate (in case of a horizontally aligned stereo camera). The function actually builds the maps for the inverse mapping algorithm that is used by remap. That is, for each pixel \f$(u, v)\f$ in the destination (corrected and rectified) image, the function computes the corresponding coordinates in the source image (that is, in the original image from camera). The following process is applied: \f[ \begin{array}{l} x \leftarrow (u - {c'}_x)/{f'}_x \\ y \leftarrow (v - {c'}_y)/{f'}_y \\ {[X\,Y\,W]} ^T \leftarrow R^{-1}*[x \, y \, 1]^T \\ x' \leftarrow X/W \\ y' \leftarrow Y/W \\ r^2 \leftarrow x'^2 + y'^2 \\ x'' \leftarrow x' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + 2p_1 x' y' + p_2(r^2 + 2 x'^2) + s_1 r^2 + s_2 r^4\\ y'' \leftarrow y' \frac{1 + k_1 r^2 + k_2 r^4 + k_3 r^6}{1 + k_4 r^2 + k_5 r^4 + k_6 r^6} + p_1 (r^2 + 2 y'^2) + 2 p_2 x' y' + s_3 r^2 + s_4 r^4 \\ s\vecthree{x'''}{y'''}{1} = \vecthreethree{R_{33}(\tau_x, \tau_y)}{0}{-R_{13}((\tau_x, \tau_y)} {0}{R_{33}(\tau_x, \tau_y)}{-R_{23}(\tau_x, \tau_y)} {0}{0}{1} R(\tau_x, \tau_y) \vecthree{x''}{y''}{1}\\ map_x(u,v) \leftarrow x''' f_x + c_x \\ map_y(u,v) \leftarrow y''' f_y + c_y \end{array} \f] where \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ are the distortion coefficients. In case of a stereo camera, this function is called twice: once for each camera head, after stereoRectify, which in its turn is called after cv::stereoCalibrate. But if the stereo camera was not calibrated, it is still possible to compute the rectification transformations directly from the fundamental matrix using cv::stereoRectifyUncalibrated. For each camera, the function computes homography H as the rectification transformation in a pixel domain, not a rotation matrix R in 3D space. R can be computed from H as \f[\texttt{R} = \texttt{cameraMatrix} ^{-1} \cdot \texttt{H} \cdot \texttt{cameraMatrix}\f] where cameraMatrix can be chosen arbitrarily. @param cameraMatrix Input camera matrix \f$A=\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param R Optional rectification transformation in the object space (3x3 matrix). R1 or R2 , computed by stereoRectify can be passed here. If the matrix is empty, the identity transformation is assumed. In cvInitUndistortMap R assumed to be an identity matrix. @param newCameraMatrix New camera matrix \f$A'=\vecthreethree{f_x'}{0}{c_x'}{0}{f_y'}{c_y'}{0}{0}{1}\f$. @param size Undistorted image size. @param m1type Type of the first output map that can be CV_32FC1, CV_32FC2 or CV_16SC2, see cv::convertMaps @param map1 The first output map. @param map2 The second output map. */ CV_EXPORTS_W void initUndistortRectifyMap( InputArray cameraMatrix, InputArray distCoeffs, InputArray R, InputArray newCameraMatrix, Size size, int m1type, OutputArray map1, OutputArray map2 ); //! initializes maps for cv::remap() for wide-angle CV_EXPORTS_W float initWideAngleProjMap( InputArray cameraMatrix, InputArray distCoeffs, Size imageSize, int destImageWidth, int m1type, OutputArray map1, OutputArray map2, int projType = PROJ_SPHERICAL_EQRECT, double alpha = 0); /** @brief Returns the default new camera matrix. The function returns the camera matrix that is either an exact copy of the input cameraMatrix (when centerPrinicipalPoint=false ), or the modified one (when centerPrincipalPoint=true). In the latter case, the new camera matrix will be: \f[\begin{bmatrix} f_x && 0 && ( \texttt{imgSize.width} -1)*0.5 \\ 0 && f_y && ( \texttt{imgSize.height} -1)*0.5 \\ 0 && 0 && 1 \end{bmatrix} ,\f] where \f$f_x\f$ and \f$f_y\f$ are \f$(0,0)\f$ and \f$(1,1)\f$ elements of cameraMatrix, respectively. By default, the undistortion functions in OpenCV (see initUndistortRectifyMap, undistort) do not move the principal point. However, when you work with stereo, it is important to move the principal points in both views to the same y-coordinate (which is required by most of stereo correspondence algorithms), and may be to the same x-coordinate too. So, you can form the new camera matrix for each view where the principal points are located at the center. @param cameraMatrix Input camera matrix. @param imgsize Camera view image size in pixels. @param centerPrincipalPoint Location of the principal point in the new camera matrix. The parameter indicates whether this location should be at the image center or not. */ CV_EXPORTS_W Mat getDefaultNewCameraMatrix( InputArray cameraMatrix, Size imgsize = Size(), bool centerPrincipalPoint = false ); /** @brief Computes the ideal point coordinates from the observed point coordinates. The function is similar to cv::undistort and cv::initUndistortRectifyMap but it operates on a sparse set of points instead of a raster image. Also the function performs a reverse transformation to projectPoints. In case of a 3D object, it does not reconstruct its 3D coordinates, but for a planar object, it does, up to a translation vector, if the proper R is specified. For each observed point coordinate \f$(u, v)\f$ the function computes: \f[ \begin{array}{l} x^{"} \leftarrow (u - c_x)/f_x \\ y^{"} \leftarrow (v - c_y)/f_y \\ (x',y') = undistort(x^{"},y^{"}, \texttt{distCoeffs}) \\ {[X\,Y\,W]} ^T \leftarrow R*[x' \, y' \, 1]^T \\ x \leftarrow X/W \\ y \leftarrow Y/W \\ \text{only performed if P is specified:} \\ u' \leftarrow x {f'}_x + {c'}_x \\ v' \leftarrow y {f'}_y + {c'}_y \end{array} \f] where *undistort* is an approximate iterative algorithm that estimates the normalized original point coordinates out of the normalized distorted point coordinates ("normalized" means that the coordinates do not depend on the camera matrix). The function can be used for both a stereo camera head or a monocular camera (when R is empty). @param src Observed point coordinates, 1xN or Nx1 2-channel (CV_32FC2 or CV_64FC2). @param dst Output ideal point coordinates after undistortion and reverse perspective transformation. If matrix P is identity or omitted, dst will contain normalized point coordinates. @param cameraMatrix Camera matrix \f$\vecthreethree{f_x}{0}{c_x}{0}{f_y}{c_y}{0}{0}{1}\f$ . @param distCoeffs Input vector of distortion coefficients \f$(k_1, k_2, p_1, p_2[, k_3[, k_4, k_5, k_6[, s_1, s_2, s_3, s_4[, \tau_x, \tau_y]]]])\f$ of 4, 5, 8, 12 or 14 elements. If the vector is NULL/empty, the zero distortion coefficients are assumed. @param R Rectification transformation in the object space (3x3 matrix). R1 or R2 computed by cv::stereoRectify can be passed here. If the matrix is empty, the identity transformation is used. @param P New camera matrix (3x3) or new projection matrix (3x4) \f$\begin{bmatrix} {f'}_x & 0 & {c'}_x & t_x \\ 0 & {f'}_y & {c'}_y & t_y \\ 0 & 0 & 1 & t_z \end{bmatrix}\f$. P1 or P2 computed by cv::stereoRectify can be passed here. If the matrix is empty, the identity new camera matrix is used. */ CV_EXPORTS_W void undistortPoints( InputArray src, OutputArray dst, InputArray cameraMatrix, InputArray distCoeffs, InputArray R = noArray(), InputArray P = noArray()); //! @} imgproc_transform //! @addtogroup imgproc_hist //! @{ /** @example demhist.cpp An example for creating histograms of an image */ /** @brief Calculates a histogram of a set of arrays. The function cv::calcHist calculates the histogram of one or more arrays. The elements of a tuple used to increment a histogram bin are taken from the corresponding input arrays at the same location. The sample below shows how to compute a 2D Hue-Saturation histogram for a color image. : @code #include <opencv2/imgproc.hpp> #include <opencv2/highgui.hpp> using namespace cv; int main( int argc, char** argv ) { Mat src, hsv; if( argc != 2 || !(src=imread(argv[1], 1)).data ) return -1; cvtColor(src, hsv, COLOR_BGR2HSV); // Quantize the hue to 30 levels // and the saturation to 32 levels int hbins = 30, sbins = 32; int histSize[] = {hbins, sbins}; // hue varies from 0 to 179, see cvtColor float hranges[] = { 0, 180 }; // saturation varies from 0 (black-gray-white) to // 255 (pure spectrum color) float sranges[] = { 0, 256 }; const float* ranges[] = { hranges, sranges }; MatND hist; // we compute the histogram from the 0-th and 1-st channels int channels[] = {0, 1}; calcHist( &hsv, 1, channels, Mat(), // do not use mask hist, 2, histSize, ranges, true, // the histogram is uniform false ); double maxVal=0; minMaxLoc(hist, 0, &maxVal, 0, 0); int scale = 10; Mat histImg = Mat::zeros(sbins*scale, hbins*10, CV_8UC3); for( int h = 0; h < hbins; h++ ) for( int s = 0; s < sbins; s++ ) { float binVal = hist.at<float>(h, s); int intensity = cvRound(binVal*255/maxVal); rectangle( histImg, Point(h*scale, s*scale), Point( (h+1)*scale - 1, (s+1)*scale - 1), Scalar::all(intensity), CV_FILLED ); } namedWindow( "Source", 1 ); imshow( "Source", src ); namedWindow( "H-S Histogram", 1 ); imshow( "H-S Histogram", histImg ); waitKey(); } @endcode @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same size. Each of them can have an arbitrary number of channels. @param nimages Number of source images. @param channels List of the dims channels used to compute the histogram. The first array channels are numerated from 0 to images[0].channels()-1 , the second array channels are counted from images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. @param mask Optional mask. If the matrix is not empty, it must be an 8-bit array of the same size as images[i] . The non-zero mask elements mark the array elements counted in the histogram. @param hist Output histogram, which is a dense or sparse dims -dimensional array. @param dims Histogram dimensionality that must be positive and not greater than CV_MAX_DIMS (equal to 32 in the current OpenCV version). @param histSize Array of histogram sizes in each dimension. @param ranges Array of the dims arrays of the histogram bin boundaries in each dimension. When the histogram is uniform ( uniform =true), then for each dimension i it is enough to specify the lower (inclusive) boundary \f$L_0\f$ of the 0-th histogram bin and the upper (exclusive) boundary \f$U_{\texttt{histSize}[i]-1}\f$ for the last histogram bin histSize[i]-1 . That is, in case of a uniform histogram each of ranges[i] is an array of 2 elements. When the histogram is not uniform ( uniform=false ), then each of ranges[i] contains histSize[i]+1 elements: \f$L_0, U_0=L_1, U_1=L_2, ..., U_{\texttt{histSize[i]}-2}=L_{\texttt{histSize[i]}-1}, U_{\texttt{histSize[i]}-1}\f$ . The array elements, that are not between \f$L_0\f$ and \f$U_{\texttt{histSize[i]}-1}\f$ , are not counted in the histogram. @param uniform Flag indicating whether the histogram is uniform or not (see above). @param accumulate Accumulation flag. If it is set, the histogram is not cleared in the beginning when it is allocated. This feature enables you to compute a single histogram from several sets of arrays, or to update the histogram in time. */ CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, OutputArray hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); /** @overload this variant uses cv::SparseMat for output */ CV_EXPORTS void calcHist( const Mat* images, int nimages, const int* channels, InputArray mask, SparseMat& hist, int dims, const int* histSize, const float** ranges, bool uniform = true, bool accumulate = false ); /** @overload */ CV_EXPORTS_W void calcHist( InputArrayOfArrays images, const std::vector<int>& channels, InputArray mask, OutputArray hist, const std::vector<int>& histSize, const std::vector<float>& ranges, bool accumulate = false ); /** @brief Calculates the back projection of a histogram. The function cv::calcBackProject calculates the back project of the histogram. That is, similarly to cv::calcHist , at each location (x, y) the function collects the values from the selected channels in the input images and finds the corresponding histogram bin. But instead of incrementing it, the function reads the bin value, scales it by scale , and stores in backProject(x,y) . In terms of statistics, the function computes probability of each element value in respect with the empirical probability distribution represented by the histogram. See how, for example, you can find and track a bright-colored object in a scene: - Before tracking, show the object to the camera so that it covers almost the whole frame. Calculate a hue histogram. The histogram may have strong maximums, corresponding to the dominant colors in the object. - When tracking, calculate a back projection of a hue plane of each input video frame using that pre-computed histogram. Threshold the back projection to suppress weak colors. It may also make sense to suppress pixels with non-sufficient color saturation and too dark or too bright pixels. - Find connected components in the resulting picture and choose, for example, the largest component. This is an approximate algorithm of the CamShift color object tracker. @param images Source arrays. They all should have the same depth, CV_8U, CV_16U or CV_32F , and the same size. Each of them can have an arbitrary number of channels. @param nimages Number of source images. @param channels The list of channels used to compute the back projection. The number of channels must match the histogram dimensionality. The first array channels are numerated from 0 to images[0].channels()-1 , the second array channels are counted from images[0].channels() to images[0].channels() + images[1].channels()-1, and so on. @param hist Input histogram that can be dense or sparse. @param backProject Destination back projection array that is a single-channel array of the same size and depth as images[0] . @param ranges Array of arrays of the histogram bin boundaries in each dimension. See cv::calcHist . @param scale Optional scale factor for the output back projection. @param uniform Flag indicating whether the histogram is uniform or not (see above). @sa cv::calcHist, cv::compareHist */ CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, InputArray hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); /** @overload */ CV_EXPORTS void calcBackProject( const Mat* images, int nimages, const int* channels, const SparseMat& hist, OutputArray backProject, const float** ranges, double scale = 1, bool uniform = true ); /** @overload */ CV_EXPORTS_W void calcBackProject( InputArrayOfArrays images, const std::vector<int>& channels, InputArray hist, OutputArray dst, const std::vector<float>& ranges, double scale ); /** @brief Compares two histograms. The function cv::compareHist compares two dense or two sparse histograms using the specified method. The function returns \f$d(H_1, H_2)\f$ . While the function works well with 1-, 2-, 3-dimensional dense histograms, it may not be suitable for high-dimensional sparse histograms. In such histograms, because of aliasing and sampling problems, the coordinates of non-zero histogram bins can slightly shift. To compare such histograms or more general sparse configurations of weighted points, consider using the cv::EMD function. @param H1 First compared histogram. @param H2 Second compared histogram of the same size as H1 . @param method Comparison method, see cv::HistCompMethods */ CV_EXPORTS_W double compareHist( InputArray H1, InputArray H2, int method ); /** @overload */ CV_EXPORTS double compareHist( const SparseMat& H1, const SparseMat& H2, int method ); /** @brief Equalizes the histogram of a grayscale image. The function equalizes the histogram of the input image using the following algorithm: - Calculate the histogram \f$H\f$ for src . - Normalize the histogram so that the sum of histogram bins is 255. - Compute the integral of the histogram: \f[H'_i = \sum _{0 \le j < i} H(j)\f] - Transform the image using \f$H'\f$ as a look-up table: \f$\texttt{dst}(x,y) = H'(\texttt{src}(x,y))\f$ The algorithm normalizes the brightness and increases the contrast of the image. @param src Source 8-bit single channel image. @param dst Destination image of the same size and type as src . */ CV_EXPORTS_W void equalizeHist( InputArray src, OutputArray dst ); /** @brief Computes the "minimal work" distance between two weighted point configurations. The function computes the earth mover distance and/or a lower boundary of the distance between the two weighted point configurations. One of the applications described in @cite RubnerSept98, @cite Rubner2000 is multi-dimensional histogram comparison for image retrieval. EMD is a transportation problem that is solved using some modification of a simplex algorithm, thus the complexity is exponential in the worst case, though, on average it is much faster. In the case of a real metric the lower boundary can be calculated even faster (using linear-time algorithm) and it can be used to determine roughly whether the two signatures are far enough so that they cannot relate to the same object. @param signature1 First signature, a \f$\texttt{size1}\times \texttt{dims}+1\f$ floating-point matrix. Each row stores the point weight followed by the point coordinates. The matrix is allowed to have a single column (weights only) if the user-defined cost matrix is used. The weights must be non-negative and have at least one non-zero value. @param signature2 Second signature of the same format as signature1 , though the number of rows may be different. The total weights may be different. In this case an extra "dummy" point is added to either signature1 or signature2. The weights must be non-negative and have at least one non-zero value. @param distType Used metric. See cv::DistanceTypes. @param cost User-defined \f$\texttt{size1}\times \texttt{size2}\f$ cost matrix. Also, if a cost matrix is used, lower boundary lowerBound cannot be calculated because it needs a metric function. @param lowerBound Optional input/output parameter: lower boundary of a distance between the two signatures that is a distance between mass centers. The lower boundary may not be calculated if the user-defined cost matrix is used, the total weights of point configurations are not equal, or if the signatures consist of weights only (the signature matrices have a single column). You **must** initialize \*lowerBound . If the calculated distance between mass centers is greater or equal to \*lowerBound (it means that the signatures are far enough), the function does not calculate EMD. In any case \*lowerBound is set to the calculated distance between mass centers on return. Thus, if you want to calculate both distance between mass centers and EMD, \*lowerBound should be set to 0. @param flow Resultant \f$\texttt{size1} \times \texttt{size2}\f$ flow matrix: \f$\texttt{flow}_{i,j}\f$ is a flow from \f$i\f$ -th point of signature1 to \f$j\f$ -th point of signature2 . */ CV_EXPORTS float EMD( InputArray signature1, InputArray signature2, int distType, InputArray cost=noArray(), float* lowerBound = 0, OutputArray flow = noArray() ); //! @} imgproc_hist /** @example watershed.cpp An example using the watershed algorithm */ /** @brief Performs a marker-based image segmentation using the watershed algorithm. The function implements one of the variants of watershed, non-parametric marker-based segmentation algorithm, described in @cite Meyer92 . Before passing the image to the function, you have to roughly outline the desired regions in the image markers with positive (\>0) indices. So, every region is represented as one or more connected components with the pixel values 1, 2, 3, and so on. Such markers can be retrieved from a binary mask using findContours and drawContours (see the watershed.cpp demo). The markers are "seeds" of the future image regions. All the other pixels in markers , whose relation to the outlined regions is not known and should be defined by the algorithm, should be set to 0's. In the function output, each pixel in markers is set to a value of the "seed" components or to -1 at boundaries between the regions. @note Any two neighbor connected components are not necessarily separated by a watershed boundary (-1's pixels); for example, they can touch each other in the initial marker image passed to the function. @param image Input 8-bit 3-channel image. @param markers Input/output 32-bit single-channel image (map) of markers. It should have the same size as image . @sa findContours @ingroup imgproc_misc */ CV_EXPORTS_W void watershed( InputArray image, InputOutputArray markers ); //! @addtogroup imgproc_filter //! @{ /** @brief Performs initial step of meanshift segmentation of an image. The function implements the filtering stage of meanshift segmentation, that is, the output of the function is the filtered "posterized" image with color gradients and fine-grain texture flattened. At every pixel (X,Y) of the input image (or down-sized input image, see below) the function executes meanshift iterations, that is, the pixel (X,Y) neighborhood in the joint space-color hyperspace is considered: \f[(x,y): X- \texttt{sp} \le x \le X+ \texttt{sp} , Y- \texttt{sp} \le y \le Y+ \texttt{sp} , ||(R,G,B)-(r,g,b)|| \le \texttt{sr}\f] where (R,G,B) and (r,g,b) are the vectors of color components at (X,Y) and (x,y), respectively (though, the algorithm does not depend on the color space used, so any 3-component color space can be used instead). Over the neighborhood the average spatial value (X',Y') and average color vector (R',G',B') are found and they act as the neighborhood center on the next iteration: \f[(X,Y)~(X',Y'), (R,G,B)~(R',G',B').\f] After the iterations over, the color components of the initial pixel (that is, the pixel from where the iterations started) are set to the final value (average color at the last iteration): \f[I(X,Y) <- (R*,G*,B*)\f] When maxLevel \> 0, the gaussian pyramid of maxLevel+1 levels is built, and the above procedure is run on the smallest layer first. After that, the results are propagated to the larger layer and the iterations are run again only on those pixels where the layer colors differ by more than sr from the lower-resolution layer of the pyramid. That makes boundaries of color regions sharper. Note that the results will be actually different from the ones obtained by running the meanshift procedure on the whole original image (i.e. when maxLevel==0). @param src The source 8-bit, 3-channel image. @param dst The destination image of the same format and the same size as the source. @param sp The spatial window radius. @param sr The color window radius. @param maxLevel Maximum level of the pyramid for the segmentation. @param termcrit Termination criteria: when to stop meanshift iterations. */ CV_EXPORTS_W void pyrMeanShiftFiltering( InputArray src, OutputArray dst, double sp, double sr, int maxLevel = 1, TermCriteria termcrit=TermCriteria(TermCriteria::MAX_ITER+TermCriteria::EPS,5,1) ); //! @} //! @addtogroup imgproc_misc //! @{ /** @example grabcut.cpp An example using the GrabCut algorithm */ /** @brief Runs the GrabCut algorithm. The function implements the [GrabCut image segmentation algorithm](http://en.wikipedia.org/wiki/GrabCut). @param img Input 8-bit 3-channel image. @param mask Input/output 8-bit single-channel mask. The mask is initialized by the function when mode is set to GC_INIT_WITH_RECT. Its elements may have one of the cv::GrabCutClasses. @param rect ROI containing a segmented object. The pixels outside of the ROI are marked as "obvious background". The parameter is only used when mode==GC_INIT_WITH_RECT . @param bgdModel Temporary array for the background model. Do not modify it while you are processing the same image. @param fgdModel Temporary arrays for the foreground model. Do not modify it while you are processing the same image. @param iterCount Number of iterations the algorithm should make before returning the result. Note that the result can be refined with further calls with mode==GC_INIT_WITH_MASK or mode==GC_EVAL . @param mode Operation mode that could be one of the cv::GrabCutModes */ CV_EXPORTS_W void grabCut( InputArray img, InputOutputArray mask, Rect rect, InputOutputArray bgdModel, InputOutputArray fgdModel, int iterCount, int mode = GC_EVAL ); /** @example distrans.cpp An example on using the distance transform\ */ /** @brief Calculates the distance to the closest zero pixel for each pixel of the source image. The function cv::distanceTransform calculates the approximate or precise distance from every binary image pixel to the nearest zero pixel. For zero image pixels, the distance will obviously be zero. When maskSize == DIST_MASK_PRECISE and distanceType == DIST_L2 , the function runs the algorithm described in @cite Felzenszwalb04 . This algorithm is parallelized with the TBB library. In other cases, the algorithm @cite Borgefors86 is used. This means that for a pixel the function finds the shortest path to the nearest zero pixel consisting of basic shifts: horizontal, vertical, diagonal, or knight's move (the latest is available for a \f$5\times 5\f$ mask). The overall distance is calculated as a sum of these basic distances. Since the distance function should be symmetric, all of the horizontal and vertical shifts must have the same cost (denoted as a ), all the diagonal shifts must have the same cost (denoted as `b`), and all knight's moves must have the same cost (denoted as `c`). For the cv::DIST_C and cv::DIST_L1 types, the distance is calculated precisely, whereas for cv::DIST_L2 (Euclidean distance) the distance can be calculated only with a relative error (a \f$5\times 5\f$ mask gives more accurate results). For `a`,`b`, and `c`, OpenCV uses the values suggested in the original paper: - DIST_L1: `a = 1, b = 2` - DIST_L2: - `3 x 3`: `a=0.955, b=1.3693` - `5 x 5`: `a=1, b=1.4, c=2.1969` - DIST_C: `a = 1, b = 1` Typically, for a fast, coarse distance estimation DIST_L2, a \f$3\times 3\f$ mask is used. For a more accurate distance estimation DIST_L2, a \f$5\times 5\f$ mask or the precise algorithm is used. Note that both the precise and the approximate algorithms are linear on the number of pixels. This variant of the function does not only compute the minimum distance for each pixel \f$(x, y)\f$ but also identifies the nearest connected component consisting of zero pixels (labelType==DIST_LABEL_CCOMP) or the nearest zero pixel (labelType==DIST_LABEL_PIXEL). Index of the component/pixel is stored in `labels(x, y)`. When labelType==DIST_LABEL_CCOMP, the function automatically finds connected components of zero pixels in the input image and marks them with distinct labels. When labelType==DIST_LABEL_CCOMP, the function scans through the input image and marks all the zero pixels with distinct labels. In this mode, the complexity is still linear. That is, the function provides a very fast way to compute the Voronoi diagram for a binary image. Currently, the second variant can use only the approximate distance transform algorithm, i.e. maskSize=DIST_MASK_PRECISE is not supported yet. @param src 8-bit, single-channel (binary) source image. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, single-channel image of the same size as src. @param labels Output 2D array of labels (the discrete Voronoi diagram). It has the type CV_32SC1 and the same size as src. @param distanceType Type of distance, see cv::DistanceTypes @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks. DIST_MASK_PRECISE is not supported by this variant. In case of the DIST_L1 or DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times 5\f$ or any larger aperture. @param labelType Type of the label array to build, see cv::DistanceTransformLabelTypes. */ CV_EXPORTS_AS(distanceTransformWithLabels) void distanceTransform( InputArray src, OutputArray dst, OutputArray labels, int distanceType, int maskSize, int labelType = DIST_LABEL_CCOMP ); /** @overload @param src 8-bit, single-channel (binary) source image. @param dst Output image with calculated distances. It is a 8-bit or 32-bit floating-point, single-channel image of the same size as src . @param distanceType Type of distance, see cv::DistanceTypes @param maskSize Size of the distance transform mask, see cv::DistanceTransformMasks. In case of the DIST_L1 or DIST_C distance type, the parameter is forced to 3 because a \f$3\times 3\f$ mask gives the same result as \f$5\times 5\f$ or any larger aperture. @param dstType Type of output image. It can be CV_8U or CV_32F. Type CV_8U can be used only for the first variant of the function and distanceType == DIST_L1. */ CV_EXPORTS_W void distanceTransform( InputArray src, OutputArray dst, int distanceType, int maskSize, int dstType=CV_32F); /** @example ffilldemo.cpp An example using the FloodFill technique */ /** @overload variant without `mask` parameter */ CV_EXPORTS int floodFill( InputOutputArray image, Point seedPoint, Scalar newVal, CV_OUT Rect* rect = 0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); /** @brief Fills a connected component with the given color. The function cv::floodFill fills a connected component starting from the seed point with the specified color. The connectivity is determined by the color/brightness closeness of the neighbor pixels. The pixel at \f$(x,y)\f$ is considered to belong to the repainted domain if: - in case of a grayscale image and floating range \f[\texttt{src} (x',y')- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} (x',y')+ \texttt{upDiff}\f] - in case of a grayscale image and fixed range \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)- \texttt{loDiff} \leq \texttt{src} (x,y) \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)+ \texttt{upDiff}\f] - in case of a color image and floating range \f[\texttt{src} (x',y')_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} (x',y')_r+ \texttt{upDiff} _r,\f] \f[\texttt{src} (x',y')_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} (x',y')_g+ \texttt{upDiff} _g\f] and \f[\texttt{src} (x',y')_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} (x',y')_b+ \texttt{upDiff} _b\f] - in case of a color image and fixed range \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r- \texttt{loDiff} _r \leq \texttt{src} (x,y)_r \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_r+ \texttt{upDiff} _r,\f] \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g- \texttt{loDiff} _g \leq \texttt{src} (x,y)_g \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_g+ \texttt{upDiff} _g\f] and \f[\texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b- \texttt{loDiff} _b \leq \texttt{src} (x,y)_b \leq \texttt{src} ( \texttt{seedPoint} .x, \texttt{seedPoint} .y)_b+ \texttt{upDiff} _b\f] where \f$src(x',y')\f$ is the value of one of pixel neighbors that is already known to belong to the component. That is, to be added to the connected component, a color/brightness of the pixel should be close enough to: - Color/brightness of one of its neighbors that already belong to the connected component in case of a floating range. - Color/brightness of the seed point in case of a fixed range. Use these functions to either mark a connected component with the specified color in-place, or build a mask and then extract the contour, or copy the region to another image, and so on. @param image Input/output 1- or 3-channel, 8-bit, or floating-point image. It is modified by the function unless the FLOODFILL_MASK_ONLY flag is set in the second variant of the function. See the details below. @param mask Operation mask that should be a single-channel 8-bit image, 2 pixels wider and 2 pixels taller than image. Since this is both an input and output parameter, you must take responsibility of initializing it. Flood-filling cannot go across non-zero pixels in the input mask. For example, an edge detector output can be used as a mask to stop filling at edges. On output, pixels in the mask corresponding to filled pixels in the image are set to 1 or to the a value specified in flags as described below. It is therefore possible to use the same mask in multiple calls to the function to make sure the filled areas do not overlap. @param seedPoint Starting point. @param newVal New value of the repainted domain pixels. @param loDiff Maximal lower brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. @param upDiff Maximal upper brightness/color difference between the currently observed pixel and one of its neighbors belonging to the component, or a seed pixel being added to the component. @param rect Optional output parameter set by the function to the minimum bounding rectangle of the repainted domain. @param flags Operation flags. The first 8 bits contain a connectivity value. The default value of 4 means that only the four nearest neighbor pixels (those that share an edge) are considered. A connectivity value of 8 means that the eight nearest neighbor pixels (those that share a corner) will be considered. The next 8 bits (8-16) contain a value between 1 and 255 with which to fill the mask (the default value is 1). For example, 4 | ( 255 \<\< 8 ) will consider 4 nearest neighbours and fill the mask with a value of 255. The following additional options occupy higher bits and therefore may be further combined with the connectivity and mask fill values using bit-wise or (|), see cv::FloodFillFlags. @note Since the mask is larger than the filled image, a pixel \f$(x, y)\f$ in image corresponds to the pixel \f$(x+1, y+1)\f$ in the mask . @sa findContours */ CV_EXPORTS_W int floodFill( InputOutputArray image, InputOutputArray mask, Point seedPoint, Scalar newVal, CV_OUT Rect* rect=0, Scalar loDiff = Scalar(), Scalar upDiff = Scalar(), int flags = 4 ); /** @brief Converts an image from one color space to another. The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR). Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed). So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on. The conventional ranges for R, G, and B channel values are: - 0 to 255 for CV_8U images - 0 to 65535 for CV_16U images - 0 to 1 for CV_32F images In case of linear transformations, the range does not matter. But in case of a non-linear transformation, an input RGB image should be normalized to the proper value range to get the correct results, for example, for RGB \f$\rightarrow\f$ L\*u\*v\* transformation. For example, if you have a 32-bit floating-point image directly converted from an 8-bit image without any scaling, then it will have the 0..255 value range instead of 0..1 assumed by the function. So, before calling cvtColor , you need first to scale the image down: @code img *= 1./255; cvtColor(img, img, COLOR_BGR2Luv); @endcode If you use cvtColor with 8-bit images, the conversion will have some information lost. For many applications, this will not be noticeable but it is recommended to use 32-bit images in applications that need the full range of colors or that convert an image before an operation and then convert back. If conversion adds the alpha channel, its value will set to the maximum of corresponding channel range: 255 for CV_8U, 65535 for CV_16U, 1 for CV_32F. @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC... ), or single-precision floating-point. @param dst output image of the same size and depth as src. @param code color space conversion code (see cv::ColorConversionCodes). @param dstCn number of channels in the destination image; if the parameter is 0, the number of the channels is derived automatically from src and code. @see @ref imgproc_color_conversions */ CV_EXPORTS_W void cvtColor( InputArray src, OutputArray dst, int code, int dstCn = 0 ); //! @} imgproc_misc // main function for all demosaicing processes CV_EXPORTS_W void demosaicing(InputArray _src, OutputArray _dst, int code, int dcn = 0); //! @addtogroup imgproc_shape //! @{ /** @brief Calculates all of the moments up to the third order of a polygon or rasterized shape. The function computes moments, up to the 3rd order, of a vector shape or a rasterized shape. The results are returned in the structure cv::Moments. @param array Raster image (single-channel, 8-bit or floating-point 2D array) or an array ( \f$1 \times N\f$ or \f$N \times 1\f$ ) of 2D points (Point or Point2f ). @param binaryImage If it is true, all non-zero image pixels are treated as 1's. The parameter is used for images only. @returns moments. @note Only applicable to contour moments calculations from Python bindings: Note that the numpy type for the input array should be either np.int32 or np.float32. @sa contourArea, arcLength */ CV_EXPORTS_W Moments moments( InputArray array, bool binaryImage = false ); /** @brief Calculates seven Hu invariants. The function calculates seven Hu invariants (introduced in @cite Hu62; see also <http://en.wikipedia.org/wiki/Image_moment>) defined as: \f[\begin{array}{l} hu[0]= \eta _{20}+ \eta _{02} \\ hu[1]=( \eta _{20}- \eta _{02})^{2}+4 \eta _{11}^{2} \\ hu[2]=( \eta _{30}-3 \eta _{12})^{2}+ (3 \eta _{21}- \eta _{03})^{2} \\ hu[3]=( \eta _{30}+ \eta _{12})^{2}+ ( \eta _{21}+ \eta _{03})^{2} \\ hu[4]=( \eta _{30}-3 \eta _{12})( \eta _{30}+ \eta _{12})[( \eta _{30}+ \eta _{12})^{2}-3( \eta _{21}+ \eta _{03})^{2}]+(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ hu[5]=( \eta _{20}- \eta _{02})[( \eta _{30}+ \eta _{12})^{2}- ( \eta _{21}+ \eta _{03})^{2}]+4 \eta _{11}( \eta _{30}+ \eta _{12})( \eta _{21}+ \eta _{03}) \\ hu[6]=(3 \eta _{21}- \eta _{03})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}]-( \eta _{30}-3 \eta _{12})( \eta _{21}+ \eta _{03})[3( \eta _{30}+ \eta _{12})^{2}-( \eta _{21}+ \eta _{03})^{2}] \\ \end{array}\f] where \f$\eta_{ji}\f$ stands for \f$\texttt{Moments::nu}_{ji}\f$ . These values are proved to be invariants to the image scale, rotation, and reflection except the seventh one, whose sign is changed by reflection. This invariance is proved with the assumption of infinite image resolution. In case of raster images, the computed Hu invariants for the original and transformed images are a bit different. @param moments Input moments computed with moments . @param hu Output Hu invariants. @sa matchShapes */ CV_EXPORTS void HuMoments( const Moments& moments, double hu[7] ); /** @overload */ CV_EXPORTS_W void HuMoments( const Moments& m, OutputArray hu ); //! @} imgproc_shape //! @addtogroup imgproc_object //! @{ //! type of the template matching operation enum TemplateMatchModes { TM_SQDIFF = 0, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y')-I(x+x',y+y'))^2\f] TM_SQDIFF_NORMED = 1, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y')-I(x+x',y+y'))^2}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] TM_CCORR = 2, //!< \f[R(x,y)= \sum _{x',y'} (T(x',y') \cdot I(x+x',y+y'))\f] TM_CCORR_NORMED = 3, //!< \f[R(x,y)= \frac{\sum_{x',y'} (T(x',y') \cdot I(x+x',y+y'))}{\sqrt{\sum_{x',y'}T(x',y')^2 \cdot \sum_{x',y'} I(x+x',y+y')^2}}\f] TM_CCOEFF = 4, //!< \f[R(x,y)= \sum _{x',y'} (T'(x',y') \cdot I'(x+x',y+y'))\f] //!< where //!< \f[\begin{array}{l} T'(x',y')=T(x',y') - 1/(w \cdot h) \cdot \sum _{x'',y''} T(x'',y'') \\ I'(x+x',y+y')=I(x+x',y+y') - 1/(w \cdot h) \cdot \sum _{x'',y''} I(x+x'',y+y'') \end{array}\f] TM_CCOEFF_NORMED = 5 //!< \f[R(x,y)= \frac{ \sum_{x',y'} (T'(x',y') \cdot I'(x+x',y+y')) }{ \sqrt{\sum_{x',y'}T'(x',y')^2 \cdot \sum_{x',y'} I'(x+x',y+y')^2} }\f] }; /** @brief Compares a template against overlapped image regions. The function slides through image , compares the overlapped patches of size \f$w \times h\f$ against templ using the specified method and stores the comparison results in result . Here are the formulae for the available comparison methods ( \f$I\f$ denotes image, \f$T\f$ template, \f$R\f$ result ). The summation is done over template and/or the image patch: \f$x' = 0...w-1, y' = 0...h-1\f$ After the function finishes the comparison, the best matches can be found as global minimums (when TM_SQDIFF was used) or maximums (when TM_CCORR or TM_CCOEFF was used) using the minMaxLoc function. In case of a color image, template summation in the numerator and each sum in the denominator is done over all of the channels and separate mean values are used for each channel. That is, the function can take a color template and a color image. The result will still be a single-channel image, which is easier to analyze. @param image Image where the search is running. It must be 8-bit or 32-bit floating-point. @param templ Searched template. It must be not greater than the source image and have the same data type. @param result Map of comparison results. It must be single-channel 32-bit floating-point. If image is \f$W \times H\f$ and templ is \f$w \times h\f$ , then result is \f$(W-w+1) \times (H-h+1)\f$ . @param method Parameter specifying the comparison method, see cv::TemplateMatchModes @param mask Mask of searched template. It must have the same datatype and size with templ. It is not set by default. */ CV_EXPORTS_W void matchTemplate( InputArray image, InputArray templ, OutputArray result, int method, InputArray mask = noArray() ); //! @} //! @addtogroup imgproc_shape //! @{ /** @brief computes the connected components labeled image of boolean image image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image. ccltype specifies the connected components labeling algorithm to use, currently Grana's (BBDT) and Wu's (SAUF) algorithms are supported, see the cv::ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not. @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. @param ccltype connected components algorithm type (see the cv::ConnectedComponentsAlgorithmsTypes). */ CV_EXPORTS_AS(connectedComponentsWithAlgorithm) int connectedComponents(InputArray image, OutputArray labels, int connectivity, int ltype, int ccltype); /** @overload @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. */ CV_EXPORTS_W int connectedComponents(InputArray image, OutputArray labels, int connectivity = 8, int ltype = CV_32S); /** @brief computes the connected components labeled image of boolean image and also produces a statistics output for each label image with 4 or 8 way connectivity - returns N, the total number of labels [0, N-1] where 0 represents the background label. ltype specifies the output label image type, an important consideration based on the total number of labels or alternatively the total number of pixels in the source image. ccltype specifies the connected components labeling algorithm to use, currently Grana's (BBDT) and Wu's (SAUF) algorithms are supported, see the cv::ConnectedComponentsAlgorithmsTypes for details. Note that SAUF algorithm forces a row major ordering of labels while BBDT does not. @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param stats statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes. The data type is CV_32S. @param centroids centroid output for each label, including the background label. Centroids are accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. @param ccltype connected components algorithm type (see the cv::ConnectedComponentsAlgorithmsTypes). */ CV_EXPORTS_AS(connectedComponentsWithStatsWithAlgorithm) int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity, int ltype, int ccltype); /** @overload @param image the 8-bit single-channel image to be labeled @param labels destination labeled image @param stats statistics output for each label, including the background label, see below for available statistics. Statistics are accessed via stats(label, COLUMN) where COLUMN is one of cv::ConnectedComponentsTypes. The data type is CV_32S. @param centroids centroid output for each label, including the background label. Centroids are accessed via centroids(label, 0) for x and centroids(label, 1) for y. The data type CV_64F. @param connectivity 8 or 4 for 8-way or 4-way connectivity respectively @param ltype output image label type. Currently CV_32S and CV_16U are supported. */ CV_EXPORTS_W int connectedComponentsWithStats(InputArray image, OutputArray labels, OutputArray stats, OutputArray centroids, int connectivity = 8, int ltype = CV_32S); /** @brief Finds contours in a binary image. The function retrieves contours from the binary image using the algorithm @cite Suzuki85 . The contours are a useful tool for shape analysis and object detection and recognition. See squares.cpp in the OpenCV sample directory. @note Since opencv 3.2 source image is not modified by this function. @param image Source, an 8-bit single-channel image. Non-zero pixels are treated as 1's. Zero pixels remain 0's, so the image is treated as binary . You can use cv::compare, cv::inRange, cv::threshold , cv::adaptiveThreshold, cv::Canny, and others to create a binary image out of a grayscale or color one. If mode equals to cv::RETR_CCOMP or cv::RETR_FLOODFILL, the input can also be a 32-bit integer image of labels (CV_32SC1). @param contours Detected contours. Each contour is stored as a vector of points (e.g. std::vector<std::vector<cv::Point> >). @param hierarchy Optional output vector (e.g. std::vector<cv::Vec4i>), containing information about the image topology. It has as many elements as the number of contours. For each i-th contour contours[i], the elements hierarchy[i][0] , hierarchy[i][1] , hierarchy[i][2] , and hierarchy[i][3] are set to 0-based indices in contours of the next and previous contours at the same hierarchical level, the first child contour and the parent contour, respectively. If for the contour i there are no next, previous, parent, or nested contours, the corresponding elements of hierarchy[i] will be negative. @param mode Contour retrieval mode, see cv::RetrievalModes @param method Contour approximation method, see cv::ContourApproximationModes @param offset Optional offset by which every contour point is shifted. This is useful if the contours are extracted from the image ROI and then they should be analyzed in the whole image context. */ CV_EXPORTS_W void findContours( InputOutputArray image, OutputArrayOfArrays contours, OutputArray hierarchy, int mode, int method, Point offset = Point()); /** @overload */ CV_EXPORTS void findContours( InputOutputArray image, OutputArrayOfArrays contours, int mode, int method, Point offset = Point()); /** @brief Approximates a polygonal curve(s) with the specified precision. The function cv::approxPolyDP approximates a curve or a polygon with another curve/polygon with less vertices so that the distance between them is less or equal to the specified precision. It uses the Douglas-Peucker algorithm <http://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm> @param curve Input vector of a 2D point stored in std::vector or Mat @param approxCurve Result of the approximation. The type should match the type of the input curve. @param epsilon Parameter specifying the approximation accuracy. This is the maximum distance between the original curve and its approximation. @param closed If true, the approximated curve is closed (its first and last vertices are connected). Otherwise, it is not closed. */ CV_EXPORTS_W void approxPolyDP( InputArray curve, OutputArray approxCurve, double epsilon, bool closed ); /** @brief Calculates a contour perimeter or a curve length. The function computes a curve length or a closed contour perimeter. @param curve Input vector of 2D points, stored in std::vector or Mat. @param closed Flag indicating whether the curve is closed or not. */ CV_EXPORTS_W double arcLength( InputArray curve, bool closed ); /** @brief Calculates the up-right bounding rectangle of a point set. The function calculates and returns the minimal up-right bounding rectangle for the specified point set. @param points Input 2D point set, stored in std::vector or Mat. */ CV_EXPORTS_W Rect boundingRect( InputArray points ); /** @brief Calculates a contour area. The function computes a contour area. Similarly to moments , the area is computed using the Green formula. Thus, the returned area and the number of non-zero pixels, if you draw the contour using drawContours or fillPoly , can be different. Also, the function will most certainly give a wrong results for contours with self-intersections. Example: @code vector<Point> contour; contour.push_back(Point2f(0, 0)); contour.push_back(Point2f(10, 0)); contour.push_back(Point2f(10, 10)); contour.push_back(Point2f(5, 4)); double area0 = contourArea(contour); vector<Point> approx; approxPolyDP(contour, approx, 5, true); double area1 = contourArea(approx); cout << "area0 =" << area0 << endl << "area1 =" << area1 << endl << "approx poly vertices" << approx.size() << endl; @endcode @param contour Input vector of 2D points (contour vertices), stored in std::vector or Mat. @param oriented Oriented area flag. If it is true, the function returns a signed area value, depending on the contour orientation (clockwise or counter-clockwise). Using this feature you can determine orientation of a contour by taking the sign of an area. By default, the parameter is false, which means that the absolute value is returned. */ CV_EXPORTS_W double contourArea( InputArray contour, bool oriented = false ); /** @brief Finds a rotated rectangle of the minimum area enclosing the input 2D point set. The function calculates and returns the minimum-area bounding rectangle (possibly rotated) for a specified point set. See the OpenCV sample minarea.cpp . Developer should keep in mind that the returned rotatedRect can contain negative indices when data is close to the containing Mat element boundary. @param points Input vector of 2D points, stored in std::vector\<\> or Mat */ CV_EXPORTS_W RotatedRect minAreaRect( InputArray points ); /** @brief Finds the four vertices of a rotated rect. Useful to draw the rotated rectangle. The function finds the four vertices of a rotated rectangle. This function is useful to draw the rectangle. In C++, instead of using this function, you can directly use box.points() method. Please visit the [tutorial on bounding rectangle](http://docs.opencv.org/doc/tutorials/imgproc/shapedescriptors/bounding_rects_circles/bounding_rects_circles.html#bounding-rects-circles) for more information. @param box The input rotated rectangle. It may be the output of @param points The output array of four vertices of rectangles. */ CV_EXPORTS_W void boxPoints(RotatedRect box, OutputArray points); /** @brief Finds a circle of the minimum area enclosing a 2D point set. The function finds the minimal enclosing circle of a 2D point set using an iterative algorithm. See the OpenCV sample minarea.cpp . @param points Input vector of 2D points, stored in std::vector\<\> or Mat @param center Output center of the circle. @param radius Output radius of the circle. */ CV_EXPORTS_W void minEnclosingCircle( InputArray points, CV_OUT Point2f& center, CV_OUT float& radius ); /** @example minarea.cpp */ /** @brief Finds a triangle of minimum area enclosing a 2D point set and returns its area. The function finds a triangle of minimum area enclosing the given set of 2D points and returns its area. The output for a given 2D point set is shown in the image below. 2D points are depicted in *red* and the enclosing triangle in *yellow*. ![Sample output of the minimum enclosing triangle function](pics/minenclosingtriangle.png) The implementation of the algorithm is based on O'Rourke's @cite ORourke86 and Klee and Laskowski's @cite KleeLaskowski85 papers. O'Rourke provides a \f$\theta(n)\f$ algorithm for finding the minimal enclosing triangle of a 2D convex polygon with n vertices. Since the minEnclosingTriangle function takes a 2D point set as input an additional preprocessing step of computing the convex hull of the 2D point set is required. The complexity of the convexHull function is \f$O(n log(n))\f$ which is higher than \f$\theta(n)\f$. Thus the overall complexity of the function is \f$O(n log(n))\f$. @param points Input vector of 2D points with depth CV_32S or CV_32F, stored in std::vector\<\> or Mat @param triangle Output vector of three 2D points defining the vertices of the triangle. The depth of the OutputArray must be CV_32F. */ CV_EXPORTS_W double minEnclosingTriangle( InputArray points, CV_OUT OutputArray triangle ); /** @brief Compares two shapes. The function compares two shapes. All three implemented methods use the Hu invariants (see cv::HuMoments) @param contour1 First contour or grayscale image. @param contour2 Second contour or grayscale image. @param method Comparison method, see ::ShapeMatchModes @param parameter Method-specific parameter (not supported now). */ CV_EXPORTS_W double matchShapes( InputArray contour1, InputArray contour2, int method, double parameter ); /** @example convexhull.cpp An example using the convexHull functionality */ /** @brief Finds the convex hull of a point set. The function cv::convexHull finds the convex hull of a 2D point set using the Sklansky's algorithm @cite Sklansky82 that has *O(N logN)* complexity in the current implementation. See the OpenCV sample convexhull.cpp that demonstrates the usage of different function variants. @param points Input 2D point set, stored in std::vector or Mat. @param hull Output convex hull. It is either an integer vector of indices or vector of points. In the first case, the hull elements are 0-based indices of the convex hull points in the original array (since the set of convex hull points is a subset of the original point set). In the second case, hull elements are the convex hull points themselves. @param clockwise Orientation flag. If it is true, the output convex hull is oriented clockwise. Otherwise, it is oriented counter-clockwise. The assumed coordinate system has its X axis pointing to the right, and its Y axis pointing upwards. @param returnPoints Operation flag. In case of a matrix, when the flag is true, the function returns convex hull points. Otherwise, it returns indices of the convex hull points. When the output array is std::vector, the flag is ignored, and the output depends on the type of the vector: std::vector\<int\> implies returnPoints=false, std::vector\<Point\> implies returnPoints=true. */ CV_EXPORTS_W void convexHull( InputArray points, OutputArray hull, bool clockwise = false, bool returnPoints = true ); /** @brief Finds the convexity defects of a contour. The figure below displays convexity defects of a hand contour: ![image](pics/defects.png) @param contour Input contour. @param convexhull Convex hull obtained using convexHull that should contain indices of the contour points that make the hull. @param convexityDefects The output vector of convexity defects. In C++ and the new Python/Java interface each convexity defect is represented as 4-element integer vector (a.k.a. cv::Vec4i): (start_index, end_index, farthest_pt_index, fixpt_depth), where indices are 0-based indices in the original contour of the convexity defect beginning, end and the farthest point, and fixpt_depth is fixed-point approximation (with 8 fractional bits) of the distance between the farthest contour point and the hull. That is, to get the floating-point value of the depth will be fixpt_depth/256.0. */ CV_EXPORTS_W void convexityDefects( InputArray contour, InputArray convexhull, OutputArray convexityDefects ); /** @brief Tests a contour convexity. The function tests whether the input contour is convex or not. The contour must be simple, that is, without self-intersections. Otherwise, the function output is undefined. @param contour Input vector of 2D points, stored in std::vector\<\> or Mat */ CV_EXPORTS_W bool isContourConvex( InputArray contour ); //! finds intersection of two convex polygons CV_EXPORTS_W float intersectConvexConvex( InputArray _p1, InputArray _p2, OutputArray _p12, bool handleNested = true ); /** @example fitellipse.cpp An example using the fitEllipse technique */ /** @brief Fits an ellipse around a set of 2D points. The function calculates the ellipse that fits (in a least-squares sense) a set of 2D points best of all. It returns the rotated rectangle in which the ellipse is inscribed. The first algorithm described by @cite Fitzgibbon95 is used. Developer should keep in mind that it is possible that the returned ellipse/rotatedRect data contains negative indices, due to the data points being close to the border of the containing Mat element. @param points Input 2D point set, stored in std::vector\<\> or Mat */ CV_EXPORTS_W RotatedRect fitEllipse( InputArray points ); /** @brief Fits a line to a 2D or 3D point set. The function fitLine fits a line to a 2D or 3D point set by minimizing \f$\sum_i \rho(r_i)\f$ where \f$r_i\f$ is a distance between the \f$i^{th}\f$ point, the line and \f$\rho(r)\f$ is a distance function, one of the following: - DIST_L2 \f[\rho (r) = r^2/2 \quad \text{(the simplest and the fastest least-squares method)}\f] - DIST_L1 \f[\rho (r) = r\f] - DIST_L12 \f[\rho (r) = 2 \cdot ( \sqrt{1 + \frac{r^2}{2}} - 1)\f] - DIST_FAIR \f[\rho \left (r \right ) = C^2 \cdot \left ( \frac{r}{C} - \log{\left(1 + \frac{r}{C}\right)} \right ) \quad \text{where} \quad C=1.3998\f] - DIST_WELSCH \f[\rho \left (r \right ) = \frac{C^2}{2} \cdot \left ( 1 - \exp{\left(-\left(\frac{r}{C}\right)^2\right)} \right ) \quad \text{where} \quad C=2.9846\f] - DIST_HUBER \f[\rho (r) = \fork{r^2/2}{if \(r < C\)}{C \cdot (r-C/2)}{otherwise} \quad \text{where} \quad C=1.345\f] The algorithm is based on the M-estimator ( <http://en.wikipedia.org/wiki/M-estimator> ) technique that iteratively fits the line using the weighted least-squares algorithm. After each iteration the weights \f$w_i\f$ are adjusted to be inversely proportional to \f$\rho(r_i)\f$ . @param points Input vector of 2D or 3D points, stored in std::vector\<\> or Mat. @param line Output line parameters. In case of 2D fitting, it should be a vector of 4 elements (like Vec4f) - (vx, vy, x0, y0), where (vx, vy) is a normalized vector collinear to the line and (x0, y0) is a point on the line. In case of 3D fitting, it should be a vector of 6 elements (like Vec6f) - (vx, vy, vz, x0, y0, z0), where (vx, vy, vz) is a normalized vector collinear to the line and (x0, y0, z0) is a point on the line. @param distType Distance used by the M-estimator, see cv::DistanceTypes @param param Numerical parameter ( C ) for some types of distances. If it is 0, an optimal value is chosen. @param reps Sufficient accuracy for the radius (distance between the coordinate origin and the line). @param aeps Sufficient accuracy for the angle. 0.01 would be a good default value for reps and aeps. */ CV_EXPORTS_W void fitLine( InputArray points, OutputArray line, int distType, double param, double reps, double aeps ); /** @brief Performs a point-in-contour test. The function determines whether the point is inside a contour, outside, or lies on an edge (or coincides with a vertex). It returns positive (inside), negative (outside), or zero (on an edge) value, correspondingly. When measureDist=false , the return value is +1, -1, and 0, respectively. Otherwise, the return value is a signed distance between the point and the nearest contour edge. See below a sample output of the function where each image pixel is tested against the contour: ![sample output](pics/pointpolygon.png) @param contour Input contour. @param pt Point tested against the contour. @param measureDist If true, the function estimates the signed distance from the point to the nearest contour edge. Otherwise, the function only checks if the point is inside a contour or not. */ CV_EXPORTS_W double pointPolygonTest( InputArray contour, Point2f pt, bool measureDist ); /** @brief Finds out if there is any intersection between two rotated rectangles. If there is then the vertices of the intersecting region are returned as well. Below are some examples of intersection configurations. The hatched pattern indicates the intersecting region and the red vertices are returned by the function. ![intersection examples](pics/intersection.png) @param rect1 First rectangle @param rect2 Second rectangle @param intersectingRegion The output array of the verticies of the intersecting region. It returns at most 8 vertices. Stored as std::vector\<cv::Point2f\> or cv::Mat as Mx1 of type CV_32FC2. @returns One of cv::RectanglesIntersectTypes */ CV_EXPORTS_W int rotatedRectangleIntersection( const RotatedRect& rect1, const RotatedRect& rect2, OutputArray intersectingRegion ); //! @} imgproc_shape CV_EXPORTS_W Ptr<CLAHE> createCLAHE(double clipLimit = 40.0, Size tileGridSize = Size(8, 8)); //! Ballard, D.H. (1981). Generalizing the Hough transform to detect arbitrary shapes. Pattern Recognition 13 (2): 111-122. //! Detects position only without translation and rotation CV_EXPORTS Ptr<GeneralizedHoughBallard> createGeneralizedHoughBallard(); //! Guil, N., González-Linares, J.M. and Zapata, E.L. (1999). Bidimensional shape detection using an invariant approach. Pattern Recognition 32 (6): 1025-1038. //! Detects position, translation and rotation CV_EXPORTS Ptr<GeneralizedHoughGuil> createGeneralizedHoughGuil(); //! Performs linear blending of two images CV_EXPORTS void blendLinear(InputArray src1, InputArray src2, InputArray weights1, InputArray weights2, OutputArray dst); //! @addtogroup imgproc_colormap //! @{ //! GNU Octave/MATLAB equivalent colormaps enum ColormapTypes { COLORMAP_AUTUMN = 0, //!< ![autumn](pics/colormaps/colorscale_autumn.jpg) COLORMAP_BONE = 1, //!< ![bone](pics/colormaps/colorscale_bone.jpg) COLORMAP_JET = 2, //!< ![jet](pics/colormaps/colorscale_jet.jpg) COLORMAP_WINTER = 3, //!< ![winter](pics/colormaps/colorscale_winter.jpg) COLORMAP_RAINBOW = 4, //!< ![rainbow](pics/colormaps/colorscale_rainbow.jpg) COLORMAP_OCEAN = 5, //!< ![ocean](pics/colormaps/colorscale_ocean.jpg) COLORMAP_SUMMER = 6, //!< ![summer](pics/colormaps/colorscale_summer.jpg) COLORMAP_SPRING = 7, //!< ![spring](pics/colormaps/colorscale_spring.jpg) COLORMAP_COOL = 8, //!< ![cool](pics/colormaps/colorscale_cool.jpg) COLORMAP_HSV = 9, //!< ![HSV](pics/colormaps/colorscale_hsv.jpg) COLORMAP_PINK = 10, //!< ![pink](pics/colormaps/colorscale_pink.jpg) COLORMAP_HOT = 11, //!< ![hot](pics/colormaps/colorscale_hot.jpg) COLORMAP_PARULA = 12 //!< ![parula](pics/colormaps/colorscale_parula.jpg) }; /** @brief Applies a GNU Octave/MATLAB equivalent colormap on a given image. @param src The source image, grayscale or colored of type CV_8UC1 or CV_8UC3. @param dst The result is the colormapped source image. Note: Mat::create is called on dst. @param colormap The colormap to apply, see cv::ColormapTypes */ CV_EXPORTS_W void applyColorMap(InputArray src, OutputArray dst, int colormap); //! @} imgproc_colormap //! @addtogroup imgproc_draw //! @{ /** @brief Draws a line segment connecting two points. The function line draws the line segment between pt1 and pt2 points in the image. The line is clipped by the image boundaries. For non-antialiased lines with integer coordinates, the 8-connected or 4-connected Bresenham algorithm is used. Thick lines are drawn with rounding endings. Antialiased lines are drawn using Gaussian filtering. @param img Image. @param pt1 First point of the line segment. @param pt2 Second point of the line segment. @param color Line color. @param thickness Line thickness. @param lineType Type of the line, see cv::LineTypes. @param shift Number of fractional bits in the point coordinates. */ CV_EXPORTS_W void line(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a arrow segment pointing from the first point to the second one. The function arrowedLine draws an arrow between pt1 and pt2 points in the image. See also cv::line. @param img Image. @param pt1 The point the arrow starts from. @param pt2 The point the arrow points to. @param color Line color. @param thickness Line thickness. @param line_type Type of the line, see cv::LineTypes @param shift Number of fractional bits in the point coordinates. @param tipLength The length of the arrow tip in relation to the arrow length */ CV_EXPORTS_W void arrowedLine(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness=1, int line_type=8, int shift=0, double tipLength=0.1); /** @brief Draws a simple, thick, or filled up-right rectangle. The function rectangle draws a rectangle outline or a filled rectangle whose two opposite corners are pt1 and pt2. @param img Image. @param pt1 Vertex of the rectangle. @param pt2 Vertex of the rectangle opposite to pt1 . @param color Rectangle color or brightness (grayscale image). @param thickness Thickness of lines that make up the rectangle. Negative values, like CV_FILLED , mean that the function has to draw a filled rectangle. @param lineType Type of the line. See the line description. @param shift Number of fractional bits in the point coordinates. */ CV_EXPORTS_W void rectangle(InputOutputArray img, Point pt1, Point pt2, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @overload use `rec` parameter as alternative specification of the drawn rectangle: `r.tl() and r.br()-Point(1,1)` are opposite corners */ CV_EXPORTS void rectangle(CV_IN_OUT Mat& img, Rect rec, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a circle. The function circle draws a simple or filled circle with a given center and radius. @param img Image where the circle is drawn. @param center Center of the circle. @param radius Radius of the circle. @param color Circle color. @param thickness Thickness of the circle outline, if positive. Negative thickness means that a filled circle is to be drawn. @param lineType Type of the circle boundary. See the line description. @param shift Number of fractional bits in the coordinates of the center and in the radius value. */ CV_EXPORTS_W void circle(InputOutputArray img, Point center, int radius, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @brief Draws a simple or thick elliptic arc or fills an ellipse sector. The function cv::ellipse with less parameters draws an ellipse outline, a filled ellipse, an elliptic arc, or a filled ellipse sector. The drawing code uses general parametric form. A piecewise-linear curve is used to approximate the elliptic arc boundary. If you need more control of the ellipse rendering, you can retrieve the curve using cv::ellipse2Poly and then render it with polylines or fill it with cv::fillPoly. If you use the first variant of the function and want to draw the whole ellipse, not an arc, pass `startAngle=0` and `endAngle=360`. The figure below explains the meaning of the parameters to draw the blue arc. ![Parameters of Elliptic Arc](pics/ellipse.svg) @param img Image. @param center Center of the ellipse. @param axes Half of the size of the ellipse main axes. @param angle Ellipse rotation angle in degrees. @param startAngle Starting angle of the elliptic arc in degrees. @param endAngle Ending angle of the elliptic arc in degrees. @param color Ellipse color. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn. @param lineType Type of the ellipse boundary. See the line description. @param shift Number of fractional bits in the coordinates of the center and values of axes. */ CV_EXPORTS_W void ellipse(InputOutputArray img, Point center, Size axes, double angle, double startAngle, double endAngle, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0); /** @overload @param img Image. @param box Alternative ellipse representation via RotatedRect. This means that the function draws an ellipse inscribed in the rotated rectangle. @param color Ellipse color. @param thickness Thickness of the ellipse arc outline, if positive. Otherwise, this indicates that a filled ellipse sector is to be drawn. @param lineType Type of the ellipse boundary. See the line description. */ CV_EXPORTS_W void ellipse(InputOutputArray img, const RotatedRect& box, const Scalar& color, int thickness = 1, int lineType = LINE_8); /* ----------------------------------------------------------------------------------------- */ /* ADDING A SET OF PREDEFINED MARKERS WHICH COULD BE USED TO HIGHLIGHT POSITIONS IN AN IMAGE */ /* ----------------------------------------------------------------------------------------- */ //! Possible set of marker types used for the cv::drawMarker function enum MarkerTypes { MARKER_CROSS = 0, //!< A crosshair marker shape MARKER_TILTED_CROSS = 1, //!< A 45 degree tilted crosshair marker shape MARKER_STAR = 2, //!< A star marker shape, combination of cross and tilted cross MARKER_DIAMOND = 3, //!< A diamond marker shape MARKER_SQUARE = 4, //!< A square marker shape MARKER_TRIANGLE_UP = 5, //!< An upwards pointing triangle marker shape MARKER_TRIANGLE_DOWN = 6 //!< A downwards pointing triangle marker shape }; /** @brief Draws a marker on a predefined position in an image. The function drawMarker draws a marker on a given position in the image. For the moment several marker types are supported, see cv::MarkerTypes for more information. @param img Image. @param position The point where the crosshair is positioned. @param color Line color. @param markerType The specific type of marker you want to use, see cv::MarkerTypes @param thickness Line thickness. @param line_type Type of the line, see cv::LineTypes @param markerSize The length of the marker axis [default = 20 pixels] */ CV_EXPORTS_W void drawMarker(CV_IN_OUT Mat& img, Point position, const Scalar& color, int markerType = MARKER_CROSS, int markerSize=20, int thickness=1, int line_type=8); /* ----------------------------------------------------------------------------------------- */ /* END OF MARKER SECTION */ /* ----------------------------------------------------------------------------------------- */ /** @overload */ CV_EXPORTS void fillConvexPoly(Mat& img, const Point* pts, int npts, const Scalar& color, int lineType = LINE_8, int shift = 0); /** @brief Fills a convex polygon. The function fillConvexPoly draws a filled convex polygon. This function is much faster than the function cv::fillPoly . It can fill not only convex polygons but any monotonic polygon without self-intersections, that is, a polygon whose contour intersects every horizontal line (scan line) twice at the most (though, its top-most and/or the bottom edge could be horizontal). @param img Image. @param points Polygon vertices. @param color Polygon color. @param lineType Type of the polygon boundaries. See the line description. @param shift Number of fractional bits in the vertex coordinates. */ CV_EXPORTS_W void fillConvexPoly(InputOutputArray img, InputArray points, const Scalar& color, int lineType = LINE_8, int shift = 0); /** @overload */ CV_EXPORTS void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType = LINE_8, int shift = 0, Point offset = Point() ); /** @brief Fills the area bounded by one or more polygons. The function fillPoly fills an area bounded by several polygonal contours. The function can fill complex areas, for example, areas with holes, contours with self-intersections (some of their parts), and so forth. @param img Image. @param pts Array of polygons where each polygon is represented as an array of points. @param color Polygon color. @param lineType Type of the polygon boundaries. See the line description. @param shift Number of fractional bits in the vertex coordinates. @param offset Optional offset of all points of the contours. */ CV_EXPORTS_W void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType = LINE_8, int shift = 0, Point offset = Point() ); /** @overload */ CV_EXPORTS void polylines(Mat& img, const Point* const* pts, const int* npts, int ncontours, bool isClosed, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0 ); /** @brief Draws several polygonal curves. @param img Image. @param pts Array of polygonal curves. @param isClosed Flag indicating whether the drawn polylines are closed or not. If they are closed, the function draws a line from the last vertex of each curve to its first vertex. @param color Polyline color. @param thickness Thickness of the polyline edges. @param lineType Type of the line segments. See the line description. @param shift Number of fractional bits in the vertex coordinates. The function polylines draws one or more polygonal curves. */ CV_EXPORTS_W void polylines(InputOutputArray img, InputArrayOfArrays pts, bool isClosed, const Scalar& color, int thickness = 1, int lineType = LINE_8, int shift = 0 ); /** @example contours2.cpp An example using the drawContour functionality */ /** @example segment_objects.cpp An example using drawContours to clean up a background segmentation result */ /** @brief Draws contours outlines or filled contours. The function draws contour outlines in the image if \f$\texttt{thickness} \ge 0\f$ or fills the area bounded by the contours if \f$\texttt{thickness}<0\f$ . The example below shows how to retrieve connected components from the binary image and label them: : @code #include "opencv2/imgproc.hpp" #include "opencv2/highgui.hpp" using namespace cv; using namespace std; int main( int argc, char** argv ) { Mat src; // the first command-line parameter must be a filename of the binary // (black-n-white) image if( argc != 2 || !(src=imread(argv[1], 0)).data) return -1; Mat dst = Mat::zeros(src.rows, src.cols, CV_8UC3); src = src > 1; namedWindow( "Source", 1 ); imshow( "Source", src ); vector<vector<Point> > contours; vector<Vec4i> hierarchy; findContours( src, contours, hierarchy, RETR_CCOMP, CHAIN_APPROX_SIMPLE ); // iterate through all the top-level contours, // draw each connected component with its own random color int idx = 0; for( ; idx >= 0; idx = hierarchy[idx][0] ) { Scalar color( rand()&255, rand()&255, rand()&255 ); drawContours( dst, contours, idx, color, FILLED, 8, hierarchy ); } namedWindow( "Components", 1 ); imshow( "Components", dst ); waitKey(0); } @endcode @param image Destination image. @param contours All the input contours. Each contour is stored as a point vector. @param contourIdx Parameter indicating a contour to draw. If it is negative, all the contours are drawn. @param color Color of the contours. @param thickness Thickness of lines the contours are drawn with. If it is negative (for example, thickness=CV_FILLED ), the contour interiors are drawn. @param lineType Line connectivity. See cv::LineTypes. @param hierarchy Optional information about hierarchy. It is only needed if you want to draw only some of the contours (see maxLevel ). @param maxLevel Maximal level for drawn contours. If it is 0, only the specified contour is drawn. If it is 1, the function draws the contour(s) and all the nested contours. If it is 2, the function draws the contours, all the nested contours, all the nested-to-nested contours, and so on. This parameter is only taken into account when there is hierarchy available. @param offset Optional contour shift parameter. Shift all the drawn contours by the specified \f$\texttt{offset}=(dx,dy)\f$ . */ CV_EXPORTS_W void drawContours( InputOutputArray image, InputArrayOfArrays contours, int contourIdx, const Scalar& color, int thickness = 1, int lineType = LINE_8, InputArray hierarchy = noArray(), int maxLevel = INT_MAX, Point offset = Point() ); /** @brief Clips the line against the image rectangle. The function cv::clipLine calculates a part of the line segment that is entirely within the specified rectangle. it returns false if the line segment is completely outside the rectangle. Otherwise, it returns true . @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . @param pt1 First line point. @param pt2 Second line point. */ CV_EXPORTS bool clipLine(Size imgSize, CV_IN_OUT Point& pt1, CV_IN_OUT Point& pt2); /** @overload @param imgSize Image size. The image rectangle is Rect(0, 0, imgSize.width, imgSize.height) . @param pt1 First line point. @param pt2 Second line point. */ CV_EXPORTS bool clipLine(Size2l imgSize, CV_IN_OUT Point2l& pt1, CV_IN_OUT Point2l& pt2); /** @overload @param imgRect Image rectangle. @param pt1 First line point. @param pt2 Second line point. */ CV_EXPORTS_W bool clipLine(Rect imgRect, CV_OUT CV_IN_OUT Point& pt1, CV_OUT CV_IN_OUT Point& pt2); /** @brief Approximates an elliptic arc with a polyline. The function ellipse2Poly computes the vertices of a polyline that approximates the specified elliptic arc. It is used by cv::ellipse. @param center Center of the arc. @param axes Half of the size of the ellipse main axes. See the ellipse for details. @param angle Rotation angle of the ellipse in degrees. See the ellipse for details. @param arcStart Starting angle of the elliptic arc in degrees. @param arcEnd Ending angle of the elliptic arc in degrees. @param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. @param pts Output vector of polyline vertices. */ CV_EXPORTS_W void ellipse2Poly( Point center, Size axes, int angle, int arcStart, int arcEnd, int delta, CV_OUT std::vector<Point>& pts ); /** @overload @param center Center of the arc. @param axes Half of the size of the ellipse main axes. See the ellipse for details. @param angle Rotation angle of the ellipse in degrees. See the ellipse for details. @param arcStart Starting angle of the elliptic arc in degrees. @param arcEnd Ending angle of the elliptic arc in degrees. @param delta Angle between the subsequent polyline vertices. It defines the approximation accuracy. @param pts Output vector of polyline vertices. */ CV_EXPORTS void ellipse2Poly(Point2d center, Size2d axes, int angle, int arcStart, int arcEnd, int delta, CV_OUT std::vector<Point2d>& pts); /** @brief Draws a text string. The function putText renders the specified text string in the image. Symbols that cannot be rendered using the specified font are replaced by question marks. See getTextSize for a text rendering code example. @param img Image. @param text Text string to be drawn. @param org Bottom-left corner of the text string in the image. @param fontFace Font type, see cv::HersheyFonts. @param fontScale Font scale factor that is multiplied by the font-specific base size. @param color Text color. @param thickness Thickness of the lines used to draw a text. @param lineType Line type. See the line for details. @param bottomLeftOrigin When true, the image data origin is at the bottom-left corner. Otherwise, it is at the top-left corner. */ CV_EXPORTS_W void putText( InputOutputArray img, const String& text, Point org, int fontFace, double fontScale, Scalar color, int thickness = 1, int lineType = LINE_8, bool bottomLeftOrigin = false ); /** @brief Calculates the width and height of a text string. The function getTextSize calculates and returns the size of a box that contains the specified text. That is, the following code renders some text, the tight box surrounding it, and the baseline: : @code String text = "Funny text inside the box"; int fontFace = FONT_HERSHEY_SCRIPT_SIMPLEX; double fontScale = 2; int thickness = 3; Mat img(600, 800, CV_8UC3, Scalar::all(0)); int baseline=0; Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline); baseline += thickness; // center the text Point textOrg((img.cols - textSize.width)/2, (img.rows + textSize.height)/2); // draw the box rectangle(img, textOrg + Point(0, baseline), textOrg + Point(textSize.width, -textSize.height), Scalar(0,0,255)); // ... and the baseline first line(img, textOrg + Point(0, thickness), textOrg + Point(textSize.width, thickness), Scalar(0, 0, 255)); // then put the text itself putText(img, text, textOrg, fontFace, fontScale, Scalar::all(255), thickness, 8); @endcode @param text Input text string. @param fontFace Font to use, see cv::HersheyFonts. @param fontScale Font scale factor that is multiplied by the font-specific base size. @param thickness Thickness of lines used to render the text. See putText for details. @param[out] baseLine y-coordinate of the baseline relative to the bottom-most text point. @return The size of a box that contains the specified text. @see cv::putText */ CV_EXPORTS_W Size getTextSize(const String& text, int fontFace, double fontScale, int thickness, CV_OUT int* baseLine); /** @brief Line iterator The class is used to iterate over all the pixels on the raster line segment connecting two specified points. The class LineIterator is used to get each pixel of a raster line. It can be treated as versatile implementation of the Bresenham algorithm where you can stop at each pixel and do some extra processing, for example, grab pixel values along the line or draw a line with an effect (for example, with XOR operation). The number of pixels along the line is stored in LineIterator::count. The method LineIterator::pos returns the current position in the image: @code{.cpp} // grabs pixels along the line (pt1, pt2) // from 8-bit 3-channel image to the buffer LineIterator it(img, pt1, pt2, 8); LineIterator it2 = it; vector<Vec3b> buf(it.count); for(int i = 0; i < it.count; i++, ++it) buf[i] = *(const Vec3b)*it; // alternative way of iterating through the line for(int i = 0; i < it2.count; i++, ++it2) { Vec3b val = img.at<Vec3b>(it2.pos()); CV_Assert(buf[i] == val); } @endcode */ class CV_EXPORTS LineIterator { public: /** @brief intializes the iterator creates iterators for the line connecting pt1 and pt2 the line will be clipped on the image boundaries the line is 8-connected or 4-connected If leftToRight=true, then the iteration is always done from the left-most point to the right most, not to depend on the ordering of pt1 and pt2 parameters */ LineIterator( const Mat& img, Point pt1, Point pt2, int connectivity = 8, bool leftToRight = false ); /** @brief returns pointer to the current pixel */ uchar* operator *(); /** @brief prefix increment operator (++it). shifts iterator to the next pixel */ LineIterator& operator ++(); /** @brief postfix increment operator (it++). shifts iterator to the next pixel */ LineIterator operator ++(int); /** @brief returns coordinates of the current pixel */ Point pos() const; uchar* ptr; const uchar* ptr0; int step, elemSize; int err, count; int minusDelta, plusDelta; int minusStep, plusStep; }; //! @cond IGNORED // === LineIterator implementation === inline uchar* LineIterator::operator *() { return ptr; } inline LineIterator& LineIterator::operator ++() { int mask = err < 0 ? -1 : 0; err += minusDelta + (plusDelta & mask); ptr += minusStep + (plusStep & mask); return *this; } inline LineIterator LineIterator::operator ++(int) { LineIterator it = *this; ++(*this); return it; } inline Point LineIterator::pos() const { Point p; p.y = (int)((ptr - ptr0)/step); p.x = (int)(((ptr - ptr0) - p.y*step)/elemSize); return p; } //! @endcond //! @} imgproc_draw //! @} imgproc } // cv #ifndef DISABLE_OPENCV_24_COMPATIBILITY #include "opencv2/imgproc/imgproc_c.h" #endif #endif
mit
emilti/sportsbook
Source/Web/SportsBook.Web/Areas/Administration/Controllers/AdminFacilitiesController.cs
3448
namespace SportsBook.Web.Areas.Administration.Controllers { using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using Data; using Data.Models; using Infrastructure.Mapping; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using Microsoft.AspNet.Identity; using Services.Data.Contracts; using ViewModels; [Authorize(Roles = "Admin")] public class AdminFacilitiesController : Controller { private readonly IFacilitiesService facilities; public AdminFacilitiesController(IFacilitiesService facilitiesService) { this.facilities = facilitiesService; } public ActionResult Index() { return this.View(); } public ActionResult Facilities_Read([DataSourceRequest]DataSourceRequest request) { DataSourceResult result = this.facilities.All() .To<FacilityGridViewModel>() .ToDataSourceResult(request); return this.Json(result); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Facilities_Create([DataSourceRequest]DataSourceRequest request, FacilityGridViewModel facility) { var newId = 0; if (this.ModelState.IsValid) { var entity = new Facility { Name = facility.Name, Description = facility.Description, AuthorId = this.User.Identity.GetUserId(), Image = facility.Image, CityId = 1 }; this.facilities.Add(entity); this.facilities.Save(); newId = entity.Id; } var facilityToDisplay = this.facilities.All() .To<FacilityGridViewModel>() .FirstOrDefault(x => x.Id == newId); return this.Json(new[] { facilityToDisplay }.ToDataSourceResult(request, ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Facilities_Update([DataSourceRequest]DataSourceRequest request, FacilityGridViewModel facility) { if (this.ModelState.IsValid) { var entity = this.facilities.GetFacilityDetails(facility.Id); entity.Name = facility.Name; entity.Description = facility.Description; entity.Image = facility.Image; this.facilities.Save(); } var postToDisplay = this.facilities.All() .To<FacilityGridViewModel>() .FirstOrDefault(x => x.Id == facility.Id); return this.Json(new[] { facility }.ToDataSourceResult(request, ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult Facilities_Destroy([DataSourceRequest]DataSourceRequest request, Facility facility) { this.facilities.Remove(facility); this.facilities.Save(); return this.Json(new[] { facility }.ToDataSourceResult(request, ModelState)); } protected override void Dispose(bool disposing) { this.facilities.Dispose(); base.Dispose(disposing); } } }
mit
akkirilov/SoftUniProject
04_DB Frameworks_Hibernate+Spring Data/99_Exams/Photography2/src/main/java/app/domain/dtos/workshops/ParticipantsWrapperXmlDto.java
930
package app.domain.dtos.workshops; 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.XmlRootElement; @XmlRootElement(name = "participants") @XmlAccessorType(XmlAccessType.FIELD) public class ParticipantsWrapperXmlDto { @XmlAttribute(name = "count") private Integer count; @XmlElement(name = "participant") private List<ParticipantByLocation> participants; public ParticipantsWrapperXmlDto() { super(); } public Integer getCount() { return count; } public void setCount(Integer count) { this.count = count; } public List<ParticipantByLocation> getParticipants() { return participants; } public void setParticipants(List<ParticipantByLocation> participants) { this.participants = participants; } }
mit
prack/php-rb
lib/prb/i/stringlike.php
75
<?php // TODO: Document! interface Prb_I_Stringlike { function toStr(); }
mit
srpanwar/JSONParser
ConsoleApplication2/Program.cs
1122
using JsonParser; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication2 { class Program { static void Main(string[] args) { string data = File.ReadAllText(@"....."); Stopwatch watch = new Stopwatch(); for (int i = 0; i < 20; i++) { watch.Start(); Newtonsoft.Json.Linq.JObject jObj = Newtonsoft.Json.Linq.JObject.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); GC.Collect(); for (int i = 0; i < 20; i++) { watch.Start(); JParser parser = new JParser(); JToken token = parser.Parse(data); watch.Stop(); Console.WriteLine(watch.Elapsed); watch.Reset(); } Console.WriteLine(" "); } } }
mit
arjunshukla/CMPE-275_Team-07_Term-Project_Mini-Hotel-Manager
NodeJS_webapp/client/js/generateReport.js
3352
google.load('visualization', '1.0', { 'packages': ['corechart'] }); // Set a callback to run when the Google Visualization API is loaded. google.setOnLoadCallback(drawChart); // Callback that creates and populates a data table, // instantiates the pie chart, passes in the data and // draws it. function drawChart() { var this_js_script = $('script[src*=generateReport]'); var jsondata = this_js_script.attr('data-json_value'); var cdate = this_js_script.attr('data-req_date'); jsondata = JSON.parse(jsondata); Date.prototype.yyyymmdd = function() { var yyyy = this.getFullYear().toString(); var mm = (this.getMonth() + 1).toString(); // getMonth() is zero-based var dd = this.getDate().toString(); return yyyy + "-" + (mm[1] ? mm : "0" + mm[0]) + "-" + (dd[1] ? dd : "0" + dd[0]); // padding }; var d = new Date(); d.yyyymmdd(); var setDate = cdate; var data; var now = new Date(); var oneYr = new Date(); oneYr.setYear(now.getFullYear() + 1); if(setDate<'2014-12-31'){ alert("Hotel created on 1st Jan 2015. Enter date after this date"); } else if(setDate>oneYr.yyyymmdd()){ alert("Enter date within next year"); } else if (setDate == d.yyyymmdd()) { // present day if(jsondata.occupiedrooms != null) { var occupiedCount = jsondata.occupiedrooms.length; } else { var occupiedCount = 0; } var notOccupied = jsondata.notOccupiedCount[0]; if(jsondata.reservedrooms != null) { var reserved = jsondata.reservedrooms.length; } else { var reserved = 0; } // Create the data table. data = new google.visualization.DataTable(); data.addColumn('string', 'Occupancy'); data.addColumn('number', 'Count'); data.addRows([ ['Rooms Occupied: ' + occupiedCount, occupiedCount], ['Rooms Reserved: ' + reserved, reserved], ['Empty Rooms: ' + notOccupied, notOccupied], ]); } else if (setDate > d.yyyymmdd()) { //future day var notOccupied = jsondata.notOccupiedCount[0]; if(jsondata.reservedrooms != null) { var reserved = jsondata.reservedrooms.length; } else { var reserved = 0; } // Create the data table. var data = new google.visualization.DataTable(); data.addColumn('string', 'Occupancy'); data.addColumn('number', 'Count'); data.addRows([ ['Rooms Reserved: ' + reserved, reserved], ['Empty Rooms: ' + notOccupied, notOccupied] ]); } else if (setDate < d.yyyymmdd()) { // past date if(jsondata.occupiedrooms != null) { var occupiedCount = jsondata.occupiedrooms.length; } else { var occupiedCount = 0; } var notOccupied = jsondata.notOccupiedCount[0]; // Create the data table. data = new google.visualization.DataTable(); data.addColumn('string', 'Occupancy'); data.addColumn('number', 'Count'); data.addRows([ ['Rooms Occupied: ' + occupiedCount, occupiedCount], ['Empty Rooms: ' + notOccupied, notOccupied] ]); } // Set chart options var options = { 'title': 'Hotel availability status on '+cdate, 'width': 900, 'height': 500 }; // Instantiate and draw our chart, passing in some options. var chart = new google.visualization.PieChart(document.getElementById('chart_div')); chart.draw(data, options); }
mit
hackzhou/AutoPlatform
src/main/webapp/plugins/bower_components/Magnific-Popup-master/src/js/ajax.js
1569
var AJAX_NS = 'ajax', _ajaxCur, _removeAjaxCursor = function() { if(_ajaxCur) { $(document.body).removeClass(_ajaxCur); } }, _destroyAjaxRequest = function() { _removeAjaxCursor(); if(mfp.req) { mfp.req.abort(); } }; $.magnificPopup.registerModule(AJAX_NS, { options: { settings: null, cursor: 'mfp-ajax-cur', tError: '<a href="%url%">The content</a> could not be loaded.' }, proto: { initAjax: function() { mfp.types.push(AJAX_NS); _ajaxCur = mfp.st.ajax.cursor; _mfpOn(CLOSE_EVENT+'.'+AJAX_NS, _destroyAjaxRequest); _mfpOn('BeforeChange.' + AJAX_NS, _destroyAjaxRequest); }, getAjax: function(item) { if(_ajaxCur) { $(document.body).addClass(_ajaxCur); } mfp.updateStatus('loading'); var opts = $.extend({ url: item.src, success: function(data, textStatus, jqXHR) { var temp = { data:data, xhr:jqXHR }; _mfpTrigger('ParseAjax', temp); mfp.appendContent( $(temp.data), AJAX_NS ); item.finished = true; _removeAjaxCursor(); mfp._setFocus(); setTimeout(function() { mfp.wrap.addClass(READY_CLASS); }, 16); mfp.updateStatus('ready'); _mfpTrigger('AjaxContentAdded'); }, error: function() { _removeAjaxCursor(); item.finished = item.loadError = true; mfp.updateStatus('error', mfp.st.ajax.tError.replace('%url%', item.src)); } }, mfp.st.ajax.settings); mfp.req = $.ajax(opts); return ''; } } });
mit
simonjaeger/dynamic-dialog-bot-sample
DynamicDialogApi/DynamicDialogApi/Models/Data/DbLanguage.cs
272
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DynamicDialogApi.Models.Data { public class DbLanguage { public string Id { get; set; } public string Description { get; set; } } }
mit
CivicCommons/CivicCommons
db/migrate/20140808180254_remove_required_email.rb
129
class RemoveRequiredEmail < ActiveRecord::Migration def change change_column :people, :email, :string, null: true end end
mit
cubeme/ssharp
Tests/Normalization/LiftedExpressions/Lifted/line break preservation.cs
2372
// The MIT License (MIT) // // Copyright (c) 2014-2016, Institute for Software & Systems Engineering // // 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. namespace Tests.Normalization.LiftedExpressions.Lifted { using System; using System.Linq.Expressions; using SafetySharp.CompilerServices; internal class Test5 { public Test5() { } public Test5([LiftExpression] int i) { } public Test5(Expression<Func<int>> i) { } protected int M(int i) { return 0; } protected int N([LiftExpression] int i) { return 0; } protected int N(Expression<Func<int>> i) { return 0; } protected int O([LiftExpression] int i, [LiftExpression] int j) { return 0; } protected int O(Expression<Func<int>> i, Expression<Func<int>> j) { return 0; } } [CheckTrivia(TriviaType.All)] internal class In5 : Test5 { private void M() { new Test5(1 + 1); O(M(2 - 1) + 0, 3 - N( 2 * 5)); } } [CheckTrivia(TriviaType.All)] internal class Out5 : Test5 { private void M() { new Test5(()=>1 + 1); O(()=>M(2 - 1) + 0, ()=> 3 - N( ()=> 2 * 5)); } } }
mit
OpenCollective/opencollective-api
server/lib/sanitize-html.ts
6473
import config from 'config'; import { truncate, uniq } from 'lodash'; import prependHttp from 'prepend-http'; import LibSanitize from 'sanitize-html'; import { isValidUploadedImage } from './images'; interface AllowedContentType { /** Allows titles supported by RichTextEditor (`h3` only) */ titles?: boolean; /** Allow h1/h2. This option should not be used in places where we embed content as it can mess up with our layout */ mainTitles?: boolean; /** Includes bold, italic, strong and strike */ basicTextFormatting?: boolean; /** Includes multiline rich text formatting like lists or code blocks */ multilineTextFormatting?: boolean; /** Allow <a href="..."/> */ links?: boolean; /** Allow images */ images?: boolean; /** Allow video iframes from trusted providers */ videoIframes?: boolean; /** Allow tables */ tables?: boolean; } interface SanitizeOptions { allowedTags: string[]; allowedAttributes: Record<string, unknown>; allowedIframeHostnames: string[]; transformTags: Record<string, unknown>; } export const buildSanitizerOptions = (allowedContent: AllowedContentType = {}): SanitizeOptions => { // Nothing allowed by default const allowedTags = []; const allowedAttributes = {}; const allowedIframeHostnames = []; const transformTags = { a: function (_, attribs) { return { tagName: 'a', attribs: { ...attribs, href: formatLinkHref(attribs.href), }, }; }, }; // Titles if (allowedContent.mainTitles) { allowedTags.push('h1', 'h2', 'h3'); } else if (allowedContent.titles) { allowedTags.push('h3'); transformTags['h1'] = 'h3'; transformTags['h2'] = 'h3'; } // Multiline text formatting if (allowedContent.basicTextFormatting) { allowedTags.push('b', 'i', 'strong', 'em', 'strike', 'del'); } // Basic text formatting if (allowedContent.multilineTextFormatting) { allowedTags.push('p', 'ul', 'ol', 'nl', 'li', 'blockquote', 'code', 'pre', 'br', 'div'); } // Images if (allowedContent.images) { allowedTags.push('img', 'figure', 'figcaption'); allowedAttributes['img'] = ['src']; } // Links if (allowedContent.links) { allowedTags.push('a'); allowedAttributes['a'] = ['href', 'name', 'target']; } // Tables if (allowedContent.tables) { allowedTags.push('table', 'thead', 'caption', 'tbody', 'tr', 'th', 'td'); } // IFrames if (allowedContent.videoIframes) { allowedTags.push('iframe', 'figure'); allowedIframeHostnames.push('www.youtube.com', 'www.youtube-nocookie.com', 'player.vimeo.com', 'anchor.fm'); allowedAttributes['figure'] = ['data-trix-content-type']; allowedAttributes['iframe'] = [ 'src', 'allowfullscreen', 'frameborder', 'autoplay', 'width', 'height', { name: 'allow', multiple: true, values: ['autoplay', 'encrypted-media', 'gyroscope'], }, ]; } return { allowedTags: uniq(allowedTags), allowedAttributes, allowedIframeHostnames, transformTags, }; }; /** Default options to strip everything */ const optsStripAll = buildSanitizerOptions(); const optsSanitizeSummary = buildSanitizerOptions({ links: true, basicTextFormatting: true }); /** * Sanitize the given input to strip the HTML content. * * This function is a specialization of the one provided by `sanitize-html` with * smart defaults to match our use cases. It works as a whitelist, so by default all * tags will be stripped out. */ export function sanitizeHTML(content: string, options: SanitizeOptions = optsStripAll): string { return LibSanitize(content, options); } /** * Will remove all HTML content from the string. */ export const stripHTML = (content: string): string => sanitizeHTML(content, optsStripAll); /** * An helper to generate a summary for an HTML content. A summary is defined as a single * line content truncated to a max length, with tags like code blocks removed. It still * allows the use of bold, italic and other single-line format options. */ export const generateSummaryForHTML = (content: string, maxLength = 255): string => { if (!content) { return null; } const cleanStr = content .replace(/(<br\/?>)|(\n)/g, ' ') // Replace all new lines by separators .replace(/<\/p>/g, '</p> ') // Add a space after each paragraph to mark the separation .replace(/<\/h3>/g, '</h3> · '); // Separate titles from then rest with a midpoint; // Sanitize: `<li><strong> Test with spaces </strong></li>` ==> `<strong> Test with spaces </strong>` const sanitized = sanitizeHTML(cleanStr, optsSanitizeSummary); // Trim: `<strong> Test with spaces </strong>` ==> <strong>Test with spaces</strong> const trimmed = sanitized.trim().replace('\n', ' ').replace(/\s+/g, ' '); const isTruncated = trimmed.length > maxLength; let cutLength = maxLength; let summary = trimmed; while (summary.length > maxLength) { // Truncate summary = truncate(summary, { length: cutLength, omission: '' }); // Second sanitize pass: an additional precaution in case someones finds a way to play with the trimmed version summary = sanitizeHTML(summary, optsSanitizeSummary); cutLength--; } // Check to see if the second sanitization cuts a html tag in the middle if (isTruncated) { return `${summary.trim()}...`; } else { return summary; } }; const formatLinkHref = (url: string): string => { if (!url) { return ''; } const baseUrl = prependHttp(url); if (isTrustedLinkUrl(baseUrl)) { return baseUrl; } else { return `${config.host.website}/redirect?url=${encodeURIComponent(baseUrl)}`; } }; const isTrustedLinkUrl = (url: string): boolean => { let parsedUrl = null; try { parsedUrl = new URL(url); } catch { throw new Error(`Invalid URL: ${url}`); } if (!['http:', 'https:', 'ftp:', 'mailto:'].includes(parsedUrl.protocol)) { throw new Error(`Invalid link protocol: ${parsedUrl.protocol}`); } const rootDomain = parsedUrl.host.replace(/^www\./, ''); const trustedDomains = [ new RegExp(`^(.+\\.)?${config.host.website.replace(/^https?:\/\//, '')}$`), /^(.+\.)?opencollective.com$/, /^(.+\.)?github.com$/, /^(.+\.)?meetup.com$/, /^(.+\.)?twitter.com$/, /^(.+\.)?wikipedia.com$/, ]; return trustedDomains.some(regex => rootDomain.match(regex)) || isValidUploadedImage(url, false); };
mit
Narwhalprime/simcity201-team-project
src/simcity/test/mock/EventLog.java
2190
package simcity.test.mock; import java.util.LinkedList; /** * This class should be used by Mock agents to log significant events. For * example, you might write a log entry every time a Mock receives a message. * The class exposes some helper methods to allow you to easily parse and search * these log files. * * @author Sean Turner */ public class EventLog { /** * This is the backing data store for the list of events. */ private LinkedList<LoggedEvent> events = new LinkedList<LoggedEvent>(); /** * Add a new event to the log. * * @param e */ public void add(LoggedEvent e) { events.add(e); } /** * Clear the event log */ public void clear() { events.clear(); } /** * @return the number of events in the log */ public int size() { return events.size(); } /** * Searches all of the messages contained in the log for the specified * string. If the specified string is contained in any messages in the log * file, returns true. * * @param message * the string to search for * @return true if string is contained somewhere within the text of a logged * event. False otherwise. */ public boolean containsString(String message) { for (LoggedEvent e : events) { if (e.getMessage().contains(message)) { return true; } } return false; } /** * Similar to retains string, except returns the LoggedEvent object * * @param message * the message to search for * @return the first LoggedEvent which contains the given * string */ public LoggedEvent getFirstEventWhichContainsString(String message) { for (LoggedEvent e : events) { if (e.getMessage().contains(message)) { return e; } } return null; } /** * @return the most recently LoggedEvent */ public LoggedEvent getLastLoggedEvent() { return events.getLast(); } public String toString() { StringBuilder text = new StringBuilder(); String newLine = System.getProperty("line.separator"); if (events.size() == 0) { return "Log is empty."; } for (LoggedEvent e : events) { text.append(e.toString()); text.append(newLine); } return text.toString(); } }
mit
olojiang/AngularJsDemo
vendor/angular-i18n/angular-locale_ug-cn.js
4763
'use strict'; angular.module("ngLocale", [], ["$provide", function ($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "\u0686\u06c8\u0634\u062a\u0649\u0646 \u0628\u06c7\u0631\u06c7\u0646", "\u0686\u06c8\u0634\u062a\u0649\u0646 \u0643\u06d0\u064a\u0649\u0646" ], "DAY": [ "\u064a\u06d5\u0643\u0634\u06d5\u0646\u0628\u06d5", "\u062f\u06c8\u0634\u06d5\u0646\u0628\u06d5", "\u0633\u06d5\u064a\u0634\u06d5\u0646\u0628\u06d5", "\u0686\u0627\u0631\u0634\u06d5\u0646\u0628\u06d5", "\u067e\u06d5\u064a\u0634\u06d5\u0646\u0628\u06d5", "\u062c\u06c8\u0645\u06d5", "\u0634\u06d5\u0646\u0628\u06d5" ], "ERANAMES": [ "\u0645\u0649\u0644\u0627\u062f\u0649\u064a\u06d5\u062f\u0649\u0646 \u0628\u06c7\u0631\u06c7\u0646", "\u0645\u0649\u0644\u0627\u062f\u0649\u064a\u06d5" ], "ERAS": [ "BCE", "\u0645\u0649\u0644\u0627\u062f\u0649\u064a\u06d5" ], "FIRSTDAYOFWEEK": 6, "MONTH": [ "\u064a\u0627\u0646\u06cb\u0627\u0631", "\u0641\u06d0\u06cb\u0631\u0627\u0644", "\u0645\u0627\u0631\u062a", "\u0626\u0627\u067e\u0631\u06d0\u0644", "\u0645\u0627\u064a", "\u0626\u0649\u064a\u06c7\u0646", "\u0626\u0649\u064a\u06c7\u0644", "\u0626\u0627\u06cb\u063a\u06c7\u0633\u062a", "\u0633\u06d0\u0646\u062a\u06d5\u0628\u0649\u0631", "\u0626\u06c6\u0643\u062a\u06d5\u0628\u0649\u0631", "\u0646\u0648\u064a\u0627\u0628\u0649\u0631", "\u062f\u06d0\u0643\u0627\u0628\u0649\u0631" ], "SHORTDAY": [ "\u064a\u06d5", "\u062f\u06c8", "\u0633\u06d5", "\u0686\u0627", "\u067e\u06d5", "\u062c\u06c8", "\u0634\u06d5" ], "SHORTMONTH": [ "\u064a\u0627\u0646\u06cb\u0627\u0631", "\u0641\u06d0\u06cb\u0631\u0627\u0644", "\u0645\u0627\u0631\u062a", "\u0626\u0627\u067e\u0631\u06d0\u0644", "\u0645\u0627\u064a", "\u0626\u0649\u064a\u06c7\u0646", "\u0626\u0649\u064a\u06c7\u0644", "\u0626\u0627\u06cb\u063a\u06c7\u0633\u062a", "\u0633\u06d0\u0646\u062a\u06d5\u0628\u0649\u0631", "\u0626\u06c6\u0643\u062a\u06d5\u0628\u0649\u0631", "\u0646\u0648\u064a\u0627\u0628\u0649\u0631", "\u062f\u06d0\u0643\u0627\u0628\u0649\u0631" ], "STANDALONEMONTH": [ "\u064a\u0627\u0646\u06cb\u0627\u0631", "\u0641\u06d0\u06cb\u0631\u0627\u0644", "\u0645\u0627\u0631\u062a", "\u0626\u0627\u067e\u0631\u06d0\u0644", "\u0645\u0627\u064a", "\u0626\u0649\u064a\u06c7\u0646", "\u0626\u0649\u064a\u06c7\u0644", "\u0626\u0627\u06cb\u063a\u06c7\u0633\u062a", "\u0633\u06d0\u0646\u062a\u06d5\u0628\u0649\u0631", "\u0626\u06c6\u0643\u062a\u06d5\u0628\u0649\u0631", "\u0646\u0648\u064a\u0627\u0628\u0649\u0631", "\u062f\u06d0\u0643\u0627\u0628\u0649\u0631" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE\u060c MMMM d\u060c y", "longDate": "MMMM d\u060c y", "medium": "MMM d\u060c y h:mm:ss a", "mediumDate": "MMM d\u060c y", "mediumTime": "h:mm:ss a", "short": "M/d/yy h:mm a", "shortDate": "M/d/yy", "shortTime": "h:mm a" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "\u00a5", "DECIMAL_SEP": ".", "GROUP_SEP": ",", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-\u00a4", "negSuf": "", "posPre": "\u00a4", "posSuf": "" } ] }, "id": "ug-cn", "localeID": "ug_CN", "pluralCat": function (n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (i == 1 && vf.v == 0) { return PLURAL_CATEGORY.ONE; } return PLURAL_CATEGORY.OTHER; } }); }]);
mit
bemineni/eldam
test/remove/start.py
1974
import os import sys import yaml import traceback import transaction from eldam.elasticdatamanager import ElasticDataManager if __name__ == "__main__": test_name = "Remove" configpath = os.path.abspath('./edm.yml') if os.path.exists('./edm.yml') else sys.exit(1) config = None with open(configpath, 'r') as stream: try: config = yaml.load(stream) except yaml.YAMLError as e: raise Exception from e ret = 0 # print(config) try: edm = ElasticDataManager() edm.connect(config, config['default_index']) # result = edm.connection.get(index=config['default_index'], # doc_type='group' # id=2) # print(result) edm.add({'_type': 'group', '_id': '2', '_source': {"gid": 234, "owner": "bemineni", "name": "Sammy", "grp_hash": "456678", "description": "Sammy group" } }) edm.remove({'_type': 'group', '_id': '2'}) # check for the existence of this document then remove edm.remove({'_type': 'group', '_id': '3'}, True) transaction.commit() try: data = edm.connection.get(index=config['default_index'], doc_type="group", id="2") if '_source' in data: raise Exception("Remove id 2 failed") except Exception as e: # not found, the item got deleted # that is what we are looking for. print("Test passed") except Exception as e: print("Failed to remove item") print("Test failed") traceback.print_exc() ret = 1 finally: print(test_name + " Test complete") sys.exit(ret)
mit
habermann24/number_to_text
lib/number_to_text.rb
334
require 'number_to_text/version' require 'active_support' require 'active_support/core_ext' module NumberToText extend ActiveSupport::Autoload eager_autoload do autoload :NumberToTextConverter end module_function def number_to_text(number, options = {}) NumberToTextConverter.convert(number, options) end end
mit
zhhz/red
lib/red/executable.rb
4162
module Red # :nodoc: def build_red_plugin_for_rails(display_message = true) @files ||= '' self.make_plugin_directory('vendor/plugins/red', true) self.create_plugin_file(:open, 'vendor/plugins/red/init.rb', "require 'rubygems'\nrequire 'red'\n\nRed.rails\n") self.make_plugin_directory('public/javascripts/red') return unless display_message puts @files && exit end # def add_unobtrusive(library) # @files ||= '' # self.build_red_plugin_for_rails(false) # self.create_plugin_file(:copy, 'public/javascripts/dom_ready.js', File.join(File.dirname(__FILE__), "../javascripts/#{(library || '').downcase}_dom_ready.js")) # self.create_plugin_file(:copy, 'public/javascripts/red/unobtrusive.red', File.join(File.dirname(__FILE__), "../javascripts/red/unobtrusive.red")) # # rescue Errno::ENOENT # puts "There is no Unobtrusive Red support for #{library}" # ensure # puts @files && exit # end def make_plugin_directory(dir, only_this_directory = false) parent_dir = File.dirname(dir) self.make_plugin_directory(parent_dir) unless File.exists?(parent_dir) || only_this_directory directory_status = File.exists?(dir) ? 'exists' : Dir.mkdir(dir) && 'create' @files << " %s %s\n" % [directory_status, dir] rescue SystemCallError puts "Unable to create directory in #{parent_dir}" && exit end def create_plugin_file(operation, filename, contents) file_status = self.check_if_plugin_file_exists(filename) case operation when :open : File.open(filename, 'w') { |f| f.write(contents) } if file_status == 'create' when :copy : File.copy(contents, filename) end @files << " %s %s\n" % [file_status, filename] end def check_if_plugin_file_exists(filename) if File.exists?(filename) print "File #{filename} exists. Overwrite [yN]? " return (gets =~ /y/i ? 'create' : 'exists') else return 'create' end end def direct_translate(string) print_js(hush_warnings { string.translate_to_sexp_array }.red!) exit end def translate_to_string_including_ruby(string) js_output = hush_warnings { string.translate_to_sexp_array }.red! ruby_js = compile_ruby_js_source return ruby_js + js_output end def hush_warnings $stderr = File.open('spew', 'w') output = yield $stderr = $> File.delete('spew') return output end def convert_red_file_to_js(filename, dry_run = false) unless File.exists?(file = "%s.red" % [filename]) || File.exists?(file = "%sred/%s.red" % [(dir = "public/javascripts/"), filename]) puts "File #{filename}.red does not exist." exit end js_output = hush_warnings { File.read(file).translate_to_sexp_array }.red! ruby_js = compile_ruby_js_source File.open("%s%s.js" % [dir, filename], 'w') {|f| f.write(ruby_js + js_output)} unless dry_run print_js(js_output, filename, dry_run) end def compile_ruby_js_source cache_known_constants = @@red_constants @@red_constants = [] @@red_import = true ruby_js = hush_warnings { File.read(File.join(File.dirname(__FILE__), "../source/ruby.rb")).translate_to_sexp_array }.red! @@red_constants = cache_known_constants @@red_methods = INTERNAL_METHODS @@red_import = false return ruby_js end def print_js(js_output, filename = nil, dry_run = true) # :nodoc: puts RED_MESSAGES[:output] % [("- #{filename}.js" unless dry_run), js_output] end RED_MESSAGES = {} RED_MESSAGES[:banner] = <<-MESSAGE Description: Red converts Ruby to JavaScript. For more information see http://github.com/jessesielaff/red/wikis Usage: red [filename] [options] Options: MESSAGE RED_MESSAGES[:invalid] = <<-MESSAGE You used an %s Use red -h for help. MESSAGE RED_MESSAGES[:missing] = <<-MESSAGE You had a %s <ruby-string> Use red -h for help. MESSAGE RED_MESSAGES[:usage] = <<-MESSAGE Usage: red [filename] [options] Use red -h for help. MESSAGE RED_MESSAGES[:output] = <<-MESSAGE %s ================================= %s ================================= MESSAGE end
mit
rasyidmujahid/tan
web/app/themes/showshop/admin/layouts/skin_10.php
6497
<?php if( !isset($_GET['activated'])) { header("Content-type: text/css; charset: UTF-8"); }; $skin_styles = ""; $skin_styles .= ' html, body { font-size:16px; } body { /* BODY FONT STYLE - GOOGLE FONT */ font-family:"Tienne", Helvetica, Arial, sans-serif !important; font-weight:400; color:#333333; } .button, .onsale, .taxonomy-menu h4, button, input#s, input[type="button"], input[type="email"], input[type="reset"], input[type="submit"], input[type="text"], select, textarea { font-family: Tienne, Helvetica, Arial, sans-serif !important; } /* HEADING STYLE - GOOGLE FONT */ h1, h2, h3, h4, h5, h6 { font-family: "Rufina", Helvetica, Arial, sans-serif !important; font-weight: 400; text-transform: capitalize !important; } /* LINKS TEXT COLOR */ a, a:link, a:visited, .breadcrumbs > * , .has-tip, .has-tip:focus, .tooltip.opened, .panel.callout a:not(.button) , .side-nav li a:not(.button), .side-nav li.heading { color: #c68b00 } /* LINKS HOVER TEXT COLOR */ a:hover, a:focus, .breadcrumbs > *:hover, .has-tip:hover { color: #dd9933 } /* BUTTONS BACK AND TEXT COLORS */ button, .button, a.button, button.disabled, button[disabled], button.disabled:focus, button[disabled]:focus, .woocommerce .quantity .plus, .woocommerce .quantity .minus, .woocommerce #content .quantity .plus, .woocommerce #content .quantity .minus, .woocommerce-page .quantity .plus, .woocommerce-page .quantity .minus, .woocommerce-page #content .quantity .plus, .woocommerce-page #content .quantity .minus { background-color: rgba(221, 221, 221, 1);color: #e2b03b } /* BUTTONS HOVER BACK AND TEXT COLORS */ button:hover, .button:hover, a.button:hover, button.disabled:hover, button[disabled]:hover, .woocommerce .quantity .plus:hover, .woocommerce .quantity .minus:hover, .woocommerce #content .quantity .plus:hover, .woocommerce #content .quantity .minus:hover, .woocommerce-page .quantity .plus:hover, .woocommerce-page .quantity .minus:hover, .woocommerce-page #content .quantity .plus:hover, .woocommerce-page #content .quantity .minus:hover { background-color: rgba(206, 206, 206, 1) !important; color: #e29e00; } /* BUTTONS FOCUS BACK AND TEXT COLORS */ button:focus, .button:focus, a.button:focus, button.disabled:focus, button[disabled]:focus, .woocommerce .quantity .plus:focus, .woocommerce .quantity .minus:focus, .woocommerce #content .quantity .plus:focus, .woocommerce #content .quantity .minus:focus, .woocommerce-page .quantity .plus:focus, .woocommerce-page .quantity .minus:focus, .woocommerce-page #content .quantity .plus:focus, .woocommerce-page #content .quantity .minus:focus { background-color: rgba(226, 126, 59, 1) !important; } /* HEADER BACK COLOR */ #site-menu.horizontal { background-color:rgba(255, 255, 255, 0.95); } /* SIDEMENU BACK COLOR */ #site-menu.vertical { background-color:rgba(255, 255, 255, 0.95); } .stick-it-header { background-color:rgba(255, 255, 255, 0.9 ); } /* SUBS, MEGAS and MINI CART back color */ .mega-clone, .sub-clone, .sub-clone li .sub-menu ,.mobile-sticky.stuck, .secondary .sub-menu { background-color: #ffffff; } .menu-border:before { background-color:#ffffff; } .active-mega span { border-right-color:#ffffff } /* UNDER PAGE TITLE IMAGE OPACITY */ .header-background{ opacity: 0.6 !important; } /* BORDERS, OUTLINES COLOR */ select, input[type="text"], input[type="password"], input[type="date"], input[type="datetime"], input[type="datetime-local"], input[type="month"], input[type="week"], input[type="email"], input[type="number"], input[type="search"], input[type="tel"], input[type="time"], input[type="url"], input[type="color"], textarea, #site-menu.horizontal .topbar, .border-bottom, .border-top, #secondary .widget h4, #site-menu .widget h4, .lookbook-product, article, .woocommerce.widget_layered_nav li, article h2.post-title, .horizontal .horizontal-menu-wrapper ul.navigation > li > a, .product-filters h4.widget-title, .woocommerce ul.products.list li:after, .woocommerce.widget_product_categories li, .product-filters-wrap, .woocommerce .woocommerce-ordering select, .woocommerce-page .woocommerce-ordering select, nav.gridlist-toggle a, .summary .product_meta, .summary .product_meta > span, .woocommerce div.product .woocommerce-tabs, body.vertical-layout .mega-clone, body.vertical-layout .sub-clone, .wpb_tabs_nav:before, .wpb_tabs_nav:after , .taxonomy-menu:before, .taxonomy-menu:after , .wpb_accordion .wpb_accordion_wrapper .wpb_accordion_section .wpb_accordion_header, .vc_toggle_title { border-color:rgba(86, 86, 86, 0.4); } article.sticky { box-shadow: inset 0 0 0px 1px rgba(86, 86, 86, 0.4); } /* LOGO HEIGHT - FOR HORIZ LAYOUT */ .horizontal-layout #site-title h1 img { max-height: 25px } /* SITE TITLE FONT SIZE */ #site-title h1, .stick-it-header h1 { font-size: 100%; } /* COLOR PALLETES: */ .accent-1-transp-90 { background-color: rgba(221, 221, 221, 0.1); } .accent-1-transp-70 { background-color: rgba(221, 221, 221, 0.3); } .accent-1-transp-60 { background-color: rgba(221, 221, 221, 0.4); } ::-moz-selection { background: rgba(221, 221, 221, 0.4); } ::selection { background: rgba(221, 221, 221, 0.4); } .accent-1-light-45, .owl-prev, .prev, .owl-next, .next { background-color: #fff; } .accent-1-light-40, .owl-prev:hover, .prev:hover, .owl-next:hover, .next:hover { background-color: #fff; } .accent-1-light-30 { background-color: #fff; } h2.post-title, .accent-2-a { background-color: rgba(206, 206, 206, 0.2); } .accent-2-b { background-color: rgba(206, 206, 206, 0.4); } .accent-2-c { background-color: rgba(206, 206, 206, 0.7); } .accent-2-light-47 { background-color: #fff; } .accent-2-light-40 { background-color: #faf0e2; } .accent-2-light-30 { background-color: #f3dbb6; } h2.post-title { padding: 1rem; } article > a.author { padding: 0.5rem 1rem; } /* HEADER SIZES ADJUST */ .header-bar { height: 5rem; } .right-button, .left-button { padding: 2.3975rem; } /* HEADER COLOR */ .header-bar { background-color: rgba(255, 255, 255, 0.95); } /* THEME OPTIONS CUSTOM CSS STYLES */ #secondary .widget h4, #site-menu .widget h4, .product-filters h4.widget-title, .bottom-widgets .widget h4, footer .widget h5, .custom-widget-area h4, .custom-widget-area h5 { font-weight: 400; font-size: 0.9rem; } .taxonomy-menu li.category-link a, .taxonomy-menu li.one-pager-item a, .wpb_tabs_nav li a, select.sort-options { font-weight: 400; } '; echo wp_kses_decode_entities($skin_styles); ?>
mit
adessoAG/JenkinsHue
main/src/test/java/de/adesso/jenkinshue/service/TeamServiceImplTest.java
2389
package de.adesso.jenkinshue.service; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import de.adesso.jenkinshue.common.dto.team.TeamRenameDTO; import de.adesso.jenkinshue.common.dto.team.TeamUpdateDTO; import de.adesso.jenkinshue.exception.EmptyInputException; import de.adesso.jenkinshue.exception.TeamDoesNotExistException; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import de.adesso.jenkinshue.TestCase; import de.adesso.jenkinshue.common.dto.team.TeamCreateDTO; import de.adesso.jenkinshue.common.dto.team.TeamLampsDTO; import de.adesso.jenkinshue.common.service.TeamService; import de.adesso.jenkinshue.repository.TeamRepository; /** * * @author wennier * */ public class TeamServiceImplTest extends TestCase { @Autowired private TeamService teamService; @Autowired private TeamRepository teamRepository; @Test public void testCreate() { assertEquals(0, teamService.count()); TeamCreateDTO teamCreateDTO1 = new TeamCreateDTO("Team 1"); TeamLampsDTO teamDTO1 = teamService.create(teamCreateDTO1); assertEquals(1, teamService.count()); assertEquals("Team 1", teamRepository.findOne(teamDTO1.getId()).getName()); TeamCreateDTO teamCreateDTO2 = new TeamCreateDTO("Team 2"); TeamLampsDTO teamDTO2 = teamService.create(teamCreateDTO2); assertEquals(2, teamService.count()); assertEquals("Team 2", teamRepository.findOne(teamDTO2.getId()).getName()); } @Test(expected = EmptyInputException.class) public void testCreateTeamWithoutName() { try { teamService.create(new TeamCreateDTO(null)); } catch (EmptyInputException eie) { teamService.create(new TeamCreateDTO("")); } fail(); } @Test(expected = TeamDoesNotExistException.class) public void testUpdateTeamWithoutValidId() { teamService.update(new TeamUpdateDTO(-1, null)); fail(); } @Test(expected = TeamDoesNotExistException.class) public void testRenameTeamWithoutValidId() { teamService.rename(new TeamRenameDTO(-1, "Team 2")); fail(); } @Test(expected = EmptyInputException.class) public void testRenameTeamWithEmptyInput() { TeamLampsDTO team = teamService.create(new TeamCreateDTO("Team 1")); try { teamService.rename(new TeamRenameDTO(team.getId(), null)); } catch(EmptyInputException eie) { teamService.rename(new TeamRenameDTO(team.getId(), "")); } } }
mit
Martinspire/UBHI
frontend/joey/jqueryChart/gulpfile.js
3604
var gulp = require('gulp'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), util = require('gulp-util'), jshint = require('gulp-jshint'), size = require('gulp-size'), connect = require('gulp-connect'), replace = require('gulp-replace'), inquirer = require('inquirer'), semver = require('semver'), exec = require('child_process') .exec, fs = require('fs'), package = require('./package.json'), bower = require('./bower.json'); var srcDir = './src/'; /* * Usage : gulp build --types=Bar,Line,Doughnut * Output: - A built Chart.js file with Core and types Bar, Line and Doughnut concatenated together * - A minified version of this code, in Chart.min.js */ gulp.task('build', function () { // Default to all of the chart types, with Chart.Core first var srcFiles = [FileName('Core')], isCustom = !!(util.env.types), outputDir = (isCustom) ? 'custom' : '.'; if (isCustom) { util.env.types.split(',') .forEach(function (type) { return srcFiles.push(FileName(type)) }); } else { // Seems gulp-concat remove duplicates - nice! // So we can use this to sort out dependency order - aka include Core first! srcFiles.push(srcDir + '*'); } return gulp.src(srcFiles) .pipe(concat('Chart.js')) .pipe(replace('{{ version }}', package.version)) .pipe(gulp.dest(outputDir)) .pipe(uglify( { preserveComments: 'some' })) .pipe(concat('Chart.min.js')) .pipe(gulp.dest(outputDir)); function FileName(moduleName) { return srcDir + 'Chart.' + moduleName + '.js'; }; }); /* * Usage : gulp bump * Prompts: Version increment to bump * Output: - New version number written into package.json & bower.json */ gulp.task('bump', function (complete) { util.log('Current version:', util.colors.cyan(package.version)); var choices = ['major', 'premajor', 'minor', 'preminor', 'patch', 'prepatch', 'prerelease'].map(function (versionType) { return versionType + ' (v' + semver.inc(package.version, versionType) + ')'; }); inquirer.prompt( { type: 'list', name: 'version', message: 'What version update would you like?', choices: choices }, function (res) { var increment = res.version.split(' ')[0], newVersion = semver.inc(package.version, increment); // Set the new versions into the bower/package object package.version = newVersion; bower.version = newVersion; // Write these to their own files, then build the output fs.writeFileSync('package.json', JSON.stringify(package, null, 2)); fs.writeFileSync('bower.json', JSON.stringify(bower, null, 2)); complete(); }); }); gulp.task('release', ['build'], function () { exec('git tag -a v' + package.version); }); gulp.task('jshint', function () { return gulp.src(srcDir + '*.js') .pipe(jshint()) .pipe(jshint.reporter('default')); }); gulp.task('library-size', function () { return gulp.src('Chart.min.js') .pipe(size( { gzip: true })); }); gulp.task('module-sizes', function () { return gulp.src(srcDir + '*.js') .pipe(uglify( { preserveComments: 'some' })) .pipe(size( { showFiles: true, gzip: true })) }); gulp.task('watch', function () { gulp.watch('./src/*', ['build']); }); gulp.task('test', ['jshint']); gulp.task('size', ['library-size', 'module-sizes']); gulp.task('default', ['build', 'watch']); gulp.task('server', function () { connect.server( { port: 8000, }); }); // Convenience task for opening the project straight from the command line gulp.task('_open', function () { exec('open http://localhost:8000'); exec('subl .'); }); gulp.task('dev', ['server', 'default']);
mit
rkastilani/PowerOutagePredictor
Docs/_build/searchindex.js
393
Search.setIndex({docnames:["index"],envversion:51,filenames:["index.rst"],objects:{"":{Linear:[0,0,0,"-"],SVM:[0,0,0,"-"],Tree:[0,0,0,"-"]}},objnames:{"0":["py","module","Python module"]},objtypes:{"0":"py:module"},terms:{index:0,modul:0,page:0,search:0},titles:["Welcome to PowerOutagePredictor&#8217;s documentation!"],titleterms:{document:0,indic:0,poweroutagepredictor:0,tabl:0,welcom:0}})
mit
0xd4d/iced
src/rust/iced-x86/src/formatter/fast/enums.rs
1363
// SPDX-License-Identifier: MIT // Copyright [email protected] // Copyright iced contributors // GENERATOR-BEGIN: FastFmtFlags // ⚠️This was generated by GENERATOR!🦹‍♂️ pub(crate) struct FastFmtFlags; #[allow(dead_code)] impl FastFmtFlags { pub(crate) const NONE: u32 = 0x0000_0000; pub(crate) const HAS_VPREFIX: u32 = 0x0000_0001; pub(crate) const SAME_AS_PREV: u32 = 0x0000_0002; pub(crate) const FORCE_MEM_SIZE: u32 = 0x0000_0004; pub(crate) const PSEUDO_OPS_KIND_SHIFT: u32 = 0x0000_0003; pub(crate) const CMPPS: u32 = 0x0000_0008; pub(crate) const VCMPPS: u32 = 0x0000_0010; pub(crate) const CMPPD: u32 = 0x0000_0018; pub(crate) const VCMPPD: u32 = 0x0000_0020; pub(crate) const CMPSS: u32 = 0x0000_0028; pub(crate) const VCMPSS: u32 = 0x0000_0030; pub(crate) const CMPSD: u32 = 0x0000_0038; pub(crate) const VCMPSD: u32 = 0x0000_0040; pub(crate) const PCLMULQDQ: u32 = 0x0000_0048; pub(crate) const VPCLMULQDQ: u32 = 0x0000_0050; pub(crate) const VPCOMB: u32 = 0x0000_0058; pub(crate) const VPCOMW: u32 = 0x0000_0060; pub(crate) const VPCOMD: u32 = 0x0000_0068; pub(crate) const VPCOMQ: u32 = 0x0000_0070; pub(crate) const VPCOMUB: u32 = 0x0000_0078; pub(crate) const VPCOMUW: u32 = 0x0000_0080; pub(crate) const VPCOMUD: u32 = 0x0000_0088; pub(crate) const VPCOMUQ: u32 = 0x0000_0090; } // GENERATOR-END: FastFmtFlags
mit
B2MSolutions/node-imei
index.js
589
var checkdigit = require('checkdigit'); var imei = {}; imei.isValid = function(i) { return i.length === 15 && checkdigit.mod10.isValid(i); }; imei.next = function(prev, done) { if(!imei.isValid(prev)) { return done('invalid imei'); } var serialNumber = prev.substr(8, 6); if(serialNumber === '999999') { return done('no more IMEIs in TAC range'); } var withoutLuhn = prev.substr(0, 14); var nextWithoutLuhn = parseInt(withoutLuhn, 10) + 1; var next = checkdigit.mod10.apply(nextWithoutLuhn.toString()); return done(null, next); }; module.exports = imei;
mit
glhrmfrts/TokuNoSora
core/src/com/habboi/tns/states/MenuState.java
4635
package com.habboi.tns.states; import aurelienribon.tweenengine.Tween; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.audio.Music; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.PerspectiveCamera; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.math.Matrix4; import com.badlogic.gdx.math.Vector3; import com.habboi.tns.Game; import com.habboi.tns.GameConfig; import com.habboi.tns.rendering.Renderer; import com.habboi.tns.rendering.Scene; import com.habboi.tns.worlds.Universe; import com.habboi.tns.worlds.World; import com.habboi.tns.ui.GameTweenManager; import com.habboi.tns.ui.MainMenu; import com.habboi.tns.ui.Menu; import com.habboi.tns.ui.Rect; import com.habboi.tns.ui.Text; import com.habboi.tns.utils.InputManager; import com.habboi.tns.utils.MusicWrapper; import java.util.Stack; /** * Handles the menu screen state. */ public class MenuState extends GameState { static final float VEL = 10; static final float CAM_DIST = 20; static final float CAM_Y = 10; static final float CAM_LOOKAT_Y = 6; public MusicWrapper currentMusic = new MusicWrapper(); Vector3 bgPos = new Vector3(); World world; PerspectiveCamera worldCam; Text titleText; Stack<Menu> menuStack = new Stack<>(); Rect screenRect; Scene scene; public MenuState(Game g, Text t, Music m) { super(g); titleText = t; currentMusic.setMusic(m); } @Override public void create() { game.getSpriteBatch().setTransformMatrix(new Matrix4().idt()); game.getShapeRenderer().setTransformMatrix(new Matrix4().idt()); addMenu(new MainMenu(this, game)); scene = new Scene(game.getWidth(), game.getHeight()); world = Universe.get().worlds.get(0); for (World w : Universe.get().worlds) { w.addToScene(scene); w.fragment.visible(false); } world.fragment.visible(true); scene.setBackgroundTexture(world.background); worldCam = scene.getCamera(); worldCam.position.x = 0; worldCam.position.y = CAM_Y; screenRect = game.getRenderer().getScreenRect(); GameTweenManager.get().register("menu_state_in", new GameTweenManager.GameTween() { @Override public Tween tween() { return screenRect.getFadeTween(1, 0, 2); } @Override public void onComplete() { } }); } @Override public void resume() { game.getSpriteBatch().setTransformMatrix(new Matrix4().idt()); game.getShapeRenderer().setTransformMatrix(new Matrix4().idt()); worldCam.position.x = 0; worldCam.position.y = CAM_Y; menuStack.peek().resume(); GameTweenManager.get().start("menu_state_in"); if (currentMusic.getMusic().isPlaying()) { return; } Music menuMusic = game.getAssetManager().get("audio/menu.ogg"); menuMusic.setVolume(GameConfig.get().getMusicVolume()); menuMusic.setLooping(true); menuMusic.play(); currentMusic.setMusic(menuMusic); } public MusicWrapper getCurrentMusic() { return currentMusic; } public void setWorld(World newWorld) { world.fragment.visible(false); world = newWorld; world.fragment.visible(true); scene.setBackgroundTexture(world.background); } public void addMenu(Menu menu) { menuStack.add(menu); } public Menu popMenu() { Menu m = menuStack.pop(); m.remove(); return m; } public Menu setMenu(Menu menu) { Menu m = popMenu(); addMenu(menu); return m; } @Override public void update(float dt) { InputManager.getInstance().menuInteraction(menuStack.peek()); worldCam.position.z -= VEL * dt; worldCam.lookAt(0, CAM_LOOKAT_Y, worldCam.position.z - CAM_DIST); bgPos.set(worldCam.position); bgPos.y -= CAM_LOOKAT_Y; world.setCenterX(0); world.update(bgPos, VEL, dt); } @Override public void render() { Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT); Renderer gr = game.getRenderer(); SpriteBatch sb = game.getSpriteBatch(); gr.render(scene); menuStack.peek().render(); sb.begin(); titleText.draw(sb, true); sb.end(); screenRect.draw(game.getShapeRenderer()); } @Override public void dispose() { GameTweenManager.get().remove("menu_state_in"); } }
mit
tdmitriy/RWR
src/main/java/com/rwr/entity/ims/ImsType.java
742
package com.rwr.entity.ims; import com.rwr.entity.BaseEntity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; @Entity @Table(name = "IMS_TYPE") public class ImsType extends BaseEntity { @Column(name = "type") private String typeName; public ImsType() { } public ImsType(Integer id) { super.setId(id); } public ImsType(String typeName) { this.typeName = typeName; } public ImsType(Integer id, String typeName) { super.setId(id); this.typeName = typeName; } public String getTypeName() { return typeName; } public void setTypeName(String typeName) { this.typeName = typeName; } }
mit
raysuelzer/mushroom-observer
app/classes/query/external_link_all.rb
127
class Query::ExternalLinkAll < Query::ExternalLinkBase def initialize_flavor add_sort_order_to_title super end end
mit
mkaul/ccm-components
cryptoblock/resources/tests.js
1004
/** * @overview unit tests of ccm component for cryptoblock * @author Manfred Kaul <[email protected]> 2017 * @license The MIT License (MIT) */ ccm.files[ 'tests.js' ] = { setup: ( suite, callback ) => { suite.ccm.component( '../cryptoblock/ccm.cryptoblock.js', component => { suite.component = component; callback(); } ); }, fundamental: { tests: { componentName: suite => { suite.component.instance( instance => suite.assertSame( 'cryptoblock', instance.component.name ) ); } } }, tests: { oneInput: suite => { suite.component.start( { inner: suite.ccm.helper.html( { tag: 'input', type: 'text', name: 'foo', value: 'bar' } ), onfinish: ( instance, result ) => suite.assertEquals( { foo: 'bar' }, result ) }, instance => { console.log( instance.element ); instance.element.querySelector( '#cryptoblock' ).click(); } ); } } };
mit
musicdsp/audio-algo-chunkware
audio/algo/chunkware/GateRms.hpp
1941
/** * @author Bojan MARKOVIC * @author Edouard DUPIN * @copyright 2006, ChunkWare Music Software, OPEN-SOURCE * @license BSD-1 (see license file) * * 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. */ #pragma once #include <audio/algo/chunkware/Gate.hpp> namespace audio { namespace algo { namespace chunkware { class GateRms : public Gate { public: GateRms(); virtual ~GateRms() {} // sample rate virtual void setSampleRate(double _sampleRate); // RMS window virtual void setWindow(double _ms); virtual double getWindow() const { return m_averager.getTc(); } public: virtual void init(); protected: virtual void processDouble(double* _out, const double* _in, int8_t _nbChannel); private: audio::algo::chunkware::EnvelopeDetector m_averager; //!< averager double m_averageSquares; //!< average of squares }; } } }
mit
dachengxi/spring1.1.1_source
src/org/springframework/jms/UncategorizedJmsException.java
1124
/* * Copyright 2002-2004 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jms; /** * JmsException to be thrown when no other matching subclass found. * @author Juergen Hoeller * @since 1.1 */ public class UncategorizedJmsException extends JmsException { public UncategorizedJmsException(String msg) { super(msg); } public UncategorizedJmsException(String msg, Throwable cause) { super(msg, cause); } public UncategorizedJmsException(Throwable cause) { super("Uncategorized exception occured during JMS processing", cause); } }
mit
rhomobile/RMS-Testing
auto/feature_def/auto_common_spec/app/helpers/specHelpers.js
4982
/* Basic test methods */ function isAndroidPlatform() { return "ANDROID" == Rho.System.platform; } function isApplePlatform() { return "APPLE" == Rho.System.platform; } function isWindowsMobilePlatform() { return "WINDOWS" == Rho.System.platform; } function isWindowsDesktopPlatform() { return "WINDOWS_DESKTOP" == Rho.System.platform; } function isWindowsPhone8Platform() { return "WP8" == Rho.System.platform; } function isUWPPlatform() { return "UWP" == Rho.System.platform; } /* Complex test methods */ function isAnyWindowsFamilyPlatform() { return isWindowsMobilePlatform() || isWindowsDesktopPlatform() || isWindowsPhone8Platform(); } function isWindowsMobileOrWindowsDesktopPlatform() { return isWindowsMobilePlatform() || isWindowsDesktopPlatform(); } function isAnyButWindowsFamilyPlatform() { return !isAnyWindowsFamilyPlatform(); } function isAnyButApplePlatform() { return !isApplePlatform(); } function isAnyButAppleAndWindowsMobilePlatform() { return !(isApplePlatform() || isWindowsMobilePlatform()); } function isWindowsMobileOrAndroidPlatform() { return isAndroidPlatform() || isWindowsMobilePlatform(); } function isAndroidOrApplePlatform() { return isAndroidPlatform() || isApplePlatform(); } //Add user log to log file. var writeIntoLog = function (desc, data){ } function leftZeroFill(number, targetLength) { var output = number + ''; while (output.length < targetLength) { output = '0' + output; } return output; } //Display Results on Device var displayResult = function (desc, data){ $('#myList').empty(); if (desc != "Output: ") { var node=document.createElement("LI"); var textnode =document.createTextNode(desc); node.appendChild(textnode); document.getElementById("myList").appendChild(node); } node = document.createElement("LI"); textnode = document.createTextNode("Output:"); node.appendChild(textnode); list = document.createElement("ul"); node.appendChild(list); lines = data.split(/\r\n|\r|\n|<br>|<br\/>/g); var len = lines.length, i; for(i = 0; i < len; i++ ) lines[i] && lines.push(lines[i]); lines.splice(0 , len); if (lines.length > 1) { var time = new Date(); lines.unshift("Time: " + leftZeroFill(time.getHours(),2) + ":" + leftZeroFill(time.getMinutes(),2) + ":" + leftZeroFill(time.getSeconds(),2) + "." + leftZeroFill(~~(time.getMilliseconds()/10),2)); } Rho.Log.info(lines.join('\n'),"GOT IT!"); for(var cnt = 0 ; cnt < lines.length; cnt++ ) { list.appendChild(document.createElement("LI")).appendChild(document.createTextNode(lines[cnt])); } document.getElementById("myList").appendChild(node); } var dispCurrentProcess = function (data){ document.getElementById('detailsdiv').innerHTML = data; } // Get Random Name {Used in Database to get Random table name for each test} function getRandomName() { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; for( var i=0; i < 5; i++ ) text += possible.charAt(Math.floor(Math.random() * possible.length)); return text; } //Add Html Element Dynamically function add(type) { //Create an input type dynamically. var element = document.createElement("input"); //Assign different attributes to the element. element.setAttribute("type", type); element.setAttribute("value", type); element.setAttribute("name", type); element.setAttribute("id", type); var foo = document.getElementById("fooBar"); //Append the element in page (in span). foo.appendChild(element); } function isTestApplicable (anArray){ var platform = Rho.System.platform; return (anArray.indexOf(platform) == -1) ? false : true ; } var specHelpers = {}; specHelpers.loadEvent = function() { var title = document.createElement('h1'); title.textContent = document.getElementsByTagName('title')[0].textContent; var div = document.createElement('div'); div.id = 'detailsdiv'; var ul = document.createElement('ul'); ul.id = 'myList'; var outputElement = document.createElement('div'); outputElement.id = 'output' outputElement.style = 'display:none'; document.body.appendChild(title); // document.body.appendChild(div); document.body.appendChild(ul); document.body.appendChild(outputElement); } window.addEventListener('DOMContentLoaded', specHelpers.loadEvent); //Common Method for ruby method call from javascript var Ruby = { data: undefined, call: function(controller,method){ Ruby.data = undefined; url = '/app/'+controller+'/'+method $.get(url) .success(function(data){ }); return false; }, sendValueToJS: function(data){ //Send data from ruby controller to js Ruby.data = data; }, getReturnedValue: function(){ return Ruby.data; } }
mit
eropple/Exor
Exor.Core.Tests.ContentB/Properties/AssemblyInfo.cs
1460
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Exor.Core.Tests.ContentB")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Exor.Core.Tests.ContentB")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("f05a8667-5d94-416b-924d-ebf2ad4e78a2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mit
hexparrot/thudgame
gui.py
27466
"""A python3 implementation of the Thud! boardgame """ __author__ = "William Dizon" __license__ = "MIT License" __version__ = "1.8.0" __email__ = "[email protected]" from thudclasses import * from thud import * import copy import tkinter import tkinter.filedialog import math import re import itertools import random import sys import threading class RepeatTimer(threading.Thread): """ This borrowed class repeats at 1 second intervals to see if it is a computer's turn to act on behalf of the troll/dwarf. # Copyright (c) 2009 Geoffrey Foster # http://g-off.net/software/a-python-repeatable-threadingtimer-class """ def __init__(self, interval, function, iterations=0, args=[], kwargs={}): threading.Thread.__init__(self) self.interval = interval self.function = function self.iterations = iterations self.args = args self.kwargs = kwargs self.finished = threading.Event() def run(self): count = 0 while not self.finished.is_set() and (self.iterations <= 0 or count < self.iterations): self.finished.wait(self.interval) if not self.finished.is_set(): self.function(*self.args, **self.kwargs) count += 1 def cancel(self): self.finished.set() class DesktopGUI(tkinter.Frame): """Implements the main desktop GUI""" def __init__(self, master): master.title('Thud') self.sprites = {} self.sprite_lifted = False self.review_mode = False self.selection_mode = 'false' self.selected_pieces = [] self.displayed_ply = 0 self.delay_ai = False self.compulsory_capturing = tkinter.BooleanVar() self.allow_illegal_play = tkinter.BooleanVar() self.cpu_troll = tkinter.BooleanVar() self.cpu_dwarf = tkinter.BooleanVar() self.alt_iconset = tkinter.BooleanVar() self.lookahead_count = 3 self.draw_ui(master) self.user_notice.set("") self.compulsory_capturing.set(True) self.allow_illegal_play.set(False) self.alt_iconset.set(False) def draw_ui(self, master): """Loads all the images and widgets for the UI""" BOARD_SIZE = 600 self.square_size = int(BOARD_SIZE / 15) self.image_board = tkinter.PhotoImage(file='tb.gif') self.image_troll = tkinter.PhotoImage(file='rook.gif') self.image_dwarf = tkinter.PhotoImage(file='pawn.gif') self.image_thudstone = tkinter.PhotoImage(file='thudstone.gif') #notation list box and scroll bars self.scrollbar = tkinter.Scrollbar(master, orient='vertical') self.listbox = tkinter.Listbox(master, yscrollcommand=self.scrollbar.set) self.listbox.config(width=30, font=("Courier", 10), selectmode='single') self.scrollbar.config(command=self.listbox.yview) self.scrollbar.pack(side='right', fill='y') self.listbox.pack(side='right', fill='both', expand=1) #"status bar" frame self.canvas = tkinter.Canvas(root, width=BOARD_SIZE, height=BOARD_SIZE) self.canvas.pack(expand=True) self.clear_sprites_all() self.subframe = tkinter.Frame(master, height=50, borderwidth=2, relief='groove') self.subframe.pack(side='bottom') self.subframe2 = tkinter.Frame(self.subframe, height=50, borderwidth=2, relief='raised') self.subframe2.pack(side='right') #"status bar" labels for images and piece counts self.dwarf_count = tkinter.StringVar() self.troll_count = tkinter.StringVar() self.user_notice = tkinter.StringVar() self.subframe_label = tkinter.Label(master, textvariable=self.user_notice, width=80) self.subframe_label.pack(side='left') self.d = tkinter.Label(self.subframe, image=self.image_dwarf) self.d.pack(side='left') tkinter.Label(self.subframe, textvariable=self.dwarf_count).pack(side='left') self.t = tkinter.Label(self.subframe, image=self.image_troll) self.t.pack(side='left') tkinter.Label(self.subframe, textvariable=self.troll_count).pack(side='left') #playback controls self.subframe2_button1 = tkinter.Button(self.subframe2, text="|<<") self.subframe2_button1.pack(side='left') self.subframe2_button2 = tkinter.Button(self.subframe2, text=" < ") self.subframe2_button2.pack(side='left') self.subframe2_button3 = tkinter.Button(self.subframe2, text=" > ") self.subframe2_button3.pack(side='left') self.subframe2_button4 = tkinter.Button(self.subframe2, text=">>|") self.subframe2_button4.pack(side='left') #playback bindings self.subframe2_button1.bind('<Button-1>', self.goto_ply) self.subframe2_button2.bind('<Button-1>', self.goto_ply) self.subframe2_button3.bind('<Button-1>', self.goto_ply) self.subframe2_button4.bind('<Button-1>', self.goto_ply) menubar = tkinter.Menu(root) root.config(menu=menubar) game_dropdown = tkinter.Menu(menubar) option_dropdown = tkinter.Menu(menubar) #menubar dropdowns menubar.add_cascade(label="Game", menu=game_dropdown) menubar.add_cascade(label="Options", menu=option_dropdown) game_dropdown.new_branch = tkinter.Menu(game_dropdown) game_dropdown.add_cascade(label='New',menu=game_dropdown.new_branch) game_dropdown.new_branch.add_command(label='Classic', command=self.newgame_classic) game_dropdown.new_branch.add_command(label='Koom Valley', command=self.newgame_kvt) game_dropdown.new_branch.add_command(label='Klash', command=self.newgame_klash) game_dropdown.new_branch2 = tkinter.Menu(game_dropdown) game_dropdown.add_cascade(label='CPU Controlled',menu=game_dropdown.new_branch2) game_dropdown.new_branch2.add_checkbutton(label='Troll', variable=self.cpu_troll) game_dropdown.new_branch2.add_checkbutton(label='Dwarf', variable=self.cpu_dwarf) game_dropdown.add_command(label='Open', command=self.file_opengame) game_dropdown.add_command(label='Save', command=self.file_savegame) game_dropdown.add_command(label='Exit', command=sys.exit) option_dropdown.add_checkbutton(label='Compulsory Capturing', \ variable=self.compulsory_capturing) option_dropdown.add_checkbutton(label='Allow Illegal Moves', \ variable=self.allow_illegal_play) option_dropdown.add_checkbutton(label='Alternative Iconset', \ variable=self.alt_iconset, \ command=self.change_iconset) def change_iconset(self): """ Toggles between the chess piece icon set or the iconset for the previous thud application. Freely available source & use. # Copyright Marc Boeren # http://www.million.nl/thudboard/ """ try: if self.alt_iconset.get(): self.image_troll = tkinter.PhotoImage(file='troll.gif') self.image_dwarf = tkinter.PhotoImage(file='dwarf.gif') self.image_thudstone = tkinter.PhotoImage(file='rock.gif') self.d.configure(image=self.image_dwarf) self.t.configure(image=self.image_troll) else: self.image_troll = tkinter.PhotoImage(file='rook.gif') self.image_dwarf = tkinter.PhotoImage(file='pawn.gif') self.image_thudstone = tkinter.PhotoImage(file='thudstone.gif') self.d.configure(image=self.image_dwarf) self.t.configure(image=self.image_troll) except Exception as e: print(e) self.user_notice.set("Required files not found--maintaining iconset") self.alt_iconset.set(not self.alt_iconset.get()) self.change_iconset() self.sync_sprites() def goto_ply(self, event): """Advances or reverses game based on playback widgets""" button_clicked = { self.subframe2_button1: 0, self.subframe2_button2: max(self.displayed_ply - 1, 0), self.subframe2_button3: min(self.displayed_ply + 1, len(self.board.ply_list) - 1), self.subframe2_button4: len(self.board.ply_list) - 1 }[event.widget] self.play_out_moves(self.board.ply_list, button_clicked) def update_ui(self): """Updates UI piece count to reflect current live pieces""" self.dwarf_count.set("Dwarfs Remaining: " + str(len(self.board.dwarfs))) self.troll_count.set("Trolls Remaining: " + str(len(self.board.trolls))) self.user_notice.set("") def file_opengame(self): """Displays file dialog and then plays out game to end""" side = { 'd': 'dwarf', 'T': 'troll', 'R': 'thudstone' } self.cpu_troll.set(False) self.cpu_dwarf.set(False) imported_plies = [] regex_ply_notation = r"([T|d|R])([A-HJ-P][0-9]+)-([A-HJ-P][0-9]+)(.*)" compiled_notation = re.compile(regex_ply_notation) filename = tkinter.filedialog.askopenfilename(title="Open Thudgame", \ multiple=False, \ filetypes=[('thud-game files', '*.thud')]) if not filename: return with open(filename, "r") as thud_file: for i,line in enumerate(thud_file): m = compiled_notation.search(line) if m: p = Ply(side.get(m.group(1)), \ Ply.notation_to_position(m.group(2)), \ Ply.notation_to_position(m.group(3)), \ list(map(Ply.notation_to_position, m.group(4).split('x')[1:]))) imported_plies.append(p) else: piece_list = line.split(',') if len(piece_list) == 41 or len(piece_list) == 40: self.board.ruleset = 'classic' elif 'dH9' in piece_list: self.board.ruleset = 'kvt' else: self.board.ruleset = 'klash' self.displayed_ply = 0 if self.play_out_moves(imported_plies, len(imported_plies) - 1): self.play_out_moves(imported_plies, 0) def file_savegame(self): """Opens save dialog box and exports moves to text file (.thud)""" def tostr(token, piece_list): '''pc_string = [] for np in piece_list: pc_string.append(token + str(np))''' pc_string = map(Ply.position_to_notation, piece_list) return (','+token).join(pc_string) filename = tkinter.filedialog.asksaveasfilename(title="Save Thudgame", \ filetypes=[('thud-game files', '*.thud')]) if not filename: return try: f = open(filename, 'w') first_string = 'd' + tostr('d',self.board.get_default_positions('dwarf', self.board.ruleset)) first_string += ',T' + tostr('T',self.board.get_default_positions('troll', self.board.ruleset)) first_string += ',R' + tostr('R',self.board.get_default_positions('thudstone', self.board.ruleset)) f.write(first_string + '\n') for k in self.board.ply_list: f.write(str(k) + '\n') except: pass def sync_sprites(self): """Clears all loaded sprites and reloads according to current game positions""" self.clear_sprites_all() for i in self.board.trolls.get_bits(): self.create_sprite('troll', i) for i in self.board.dwarfs.get_bits(): self.create_sprite('dwarf', i) for i in self.board.thudstone.get_bits(): self.create_sprite('thudstone', i) def create_sprite(self, token, position): """Creates a sprite at the given notation and binds mouse events""" if token == 'troll': sprite = self.canvas.create_image(0,0, image=self.image_troll, anchor='nw') elif token == 'dwarf': sprite = self.canvas.create_image(0,0, image=self.image_dwarf, anchor='nw') elif token == 'thudstone': sprite = self.canvas.create_image(0,0, image=self.image_thudstone, anchor='nw') self.canvas.tag_bind(sprite, "<Button-1>", self.mouseDown) self.canvas.tag_bind(sprite, "<B1-Motion>", self.mouseMove) self.canvas.tag_bind(sprite, "<ButtonRelease-1>", self.mouseUp) self.sprites[position] = sprite self.move_sprite(sprite, position) def move_sprite(self, sprite, position): """Moves a piece to destination, resetting origin square to empty""" file, rank = Ply.position_to_tuple(position) self.canvas.coords(sprite, \ self.square_size * (file - 1), \ self.square_size * (rank - 1)) self.sprites[position] = sprite def clear_sprite(self, sprite): """Removes sprite from canvas""" self.canvas.delete(sprite) def clear_sprites_all(self): """Removes all sprites on the canvas and re-adds gameboard image""" self.canvas.delete(self.canvas.find_all()) board = self.canvas.create_image(0, 0, image=self.image_board, anchor='nw') self.canvas.tag_bind(board, "<Button-1>", self.boardClick) def newgame_classic(self): """Menu handler for creating a new classic game""" self.newgame_common('classic') def newgame_kvt(self): """Menu handler for creating a new kvt game""" self.newgame_common('kvt') def newgame_klash(self): """Menu handler for creating a new klash game""" self.newgame_common('klash') def newgame_common(self, ruleset='classic'): """Executes common commands for creating a new game""" self.board = Gameboard(ruleset) self.sync_sprites() self.listbox.delete(0, 'end') self.update_ui() self.review_mode = False def boardClick(self, event): """Responds to clicks that DO not occur by sprite (used for troll materialization""" notation = (int(event.x // self.square_size), int(event.y // self.square_size)) position = notation[1] * self.board.BOARD_WIDTH + \ notation[0] + self.board.BOARD_WIDTH + 1 if self.allow_illegal_play.get() or \ (self.board.ruleset == 'klash' and \ self.board.turn_to_act() == 'troll' and \ self.board.klash_trolls < 6) and \ position in self.board.get_default_positions('troll', 'classic'): ply = Ply('troll', position, position, '') self.board.add_troll(position) self.board.ply_list.append(ply) self.notate_move(ply) self.sync_sprites() def mouseDown(self, event): """This function will record the notation of all clicks determined to have landed on a sprite (see create_piece) """ self.posx = event.x self.posy = event.y pickup_notation = (int(event.x // self.square_size), \ int(event.y // self.square_size)) self.pickup = pickup_notation[1] * self.board.BOARD_WIDTH + \ pickup_notation[0] + self.board.BOARD_WIDTH + 1 if self.review_mode: return elif self.cpu_troll.get() and self.board.turn_to_act() == 'troll' or \ self.cpu_dwarf.get() and self.board.turn_to_act() == 'dwarf': return elif self.board.ruleset == 'kvt' and \ self.board.ply_list and \ self.board.ply_list[-1].token == 'troll' and \ self.board.ply_list[-1].captured: if self.board.ply_list[-2].token == 'troll' and \ self.board.ply_list[-3].token == 'troll' and \ int(self.board.trolls[self.pickup]): return self.sprite_lifted = True self.canvas.tag_raise('current') elif self.selection_mode == 'selecting' or \ self.allow_illegal_play.get() or \ self.board.game_winner or \ self.board.token_at(self.pickup) == self.board.turn_to_act() or \ (int(self.board.thudstone[self.pickup]) and \ self.board.turn_to_act() == 'dwarf' and \ self.board.ruleset == 'kvt'): self.sprite_lifted = True self.canvas.tag_raise('current') def mouseMove(self, event): """Activated only on a mouseDown-able sprite, this keeps the piece attached to the mouse""" if self.sprite_lifted: self.canvas.move('current', event.x - self.posx, event.y - self.posy) self.posx = event.x self.posy = event.y def mouseUp(self, event): """ After piece is dropped, call logic function and execute/revert move. This function also handles manual selection (noncompulsory capture) logic. """ dropoff_notation = (int(event.x // self.square_size), int(event.y // self.square_size)) self.dropoff = dropoff_notation[1] * self.board.BOARD_WIDTH + \ dropoff_notation[0] + self.board.BOARD_WIDTH + 1 if not self.sprite_lifted: return elif not self.compulsory_capturing.get(): if self.selection_mode == 'false': valid = self.board.validate_move(self.pickup, self.dropoff) if valid[2]: self.user_notice.set("Select each piece to be captured and click capturing piece to finish.") self.selected_pieces = [] self.selection_mode = 'selecting' self.pickup_remembered = self.pickup self.dropoff_remembered = self.dropoff elif valid[0]: self.execute_ply(Ply(self.board.token_at(self.pickup), \ self.pickup, \ self.dropoff, \ [])) else: self.move_sprite(self.sprites[self.pickup], \ self.pickup) elif self.selection_mode == 'selecting': self.user_notice.set("Piece at " + str(self.dropoff) + " selected") self.selected_pieces.append(self.dropoff) if self.dropoff == self.dropoff_remembered: self.selection_mode = 'false' valid = self.check_logic(Ply(self.board.token_at(self.pickup_remembered), \ self.pickup_remembered, \ self.dropoff_remembered, self.selected_pieces)) if valid[0]: self.execute_ply(valid[1]) self.board.game_winner = self.board.get_game_outcome() else: self.move_sprite(self.sprites[self.pickup_remembered], \ self.pickup_remembered) else: valid = self.check_logic(Ply(self.board.token_at(self.pickup), \ self.pickup, \ self.dropoff, \ [])) if valid[0]: self.execute_ply(valid[1]) self.board.game_winner = self.board.get_game_outcome() else: self.move_sprite(self.sprites[self.pickup], \ self.pickup) if self.board.game_winner != None: self.review_mode = True self.user_notice.set(str(self.board.game_winner) + ' win!') self.sprite_lifted = False def check_logic(self, ply): """ Returns the submitted PLY if move/capture is legal else, return None-filled Ply, which will revert attemtped move on UI. """ result = self.board.validate_move(ply.origin, ply.dest) if self.allow_illegal_play.get(): result = { True: (True, True, ply.captured), False:(True, False, []) }[bool(ply.captured)] if result[1] or result[0]: if self.compulsory_capturing.get(): approved_captures = result[2] else: approved_captures = set(ply.captured).intersection(set(result[2])) #if it would be a legal capture move, but no captures selected, invalid ply if not result[0] and result[1] and not approved_captures: return (False, Ply(None,None,None,None)) #if a legal move, but not a legal capture, but capture is notated, invalid ply if result[0] and not result[1] and ply.captured: return (False, Ply(None,None,None,None)) return (True, Ply(self.board.token_at(ply.origin), ply.origin, ply.dest, approved_captures)) return (False, Ply(None,None,None,None)) def execute_ply(self, fullply): """Shortcut function to execute all backend updates along with UI sprites""" for target in fullply.captured: self.clear_sprite(self.sprites[target]) self.move_sprite(self.sprites[fullply.origin], fullply.dest) self.board.apply_ply(fullply) self.board.ply_list.append(fullply) self.notate_move(fullply) self.displayed_ply = len(self.board.ply_list) - 1 def play_out_moves(self, ply_list, stop_at): def is_review_mode(last_ply): if last_ply >= len(self.board.ply_list) - 1: return False return True def notate_append(ply): self.board.ply_list.append(ply) self.notate_move(ply) """Go through ply list and execute each until stop_at number""" self.cpu_troll.set(False) self.cpu_dwarf.set(False) self.newgame_common(self.board.ruleset) for a, b in enumerate(ply_list): if a <= stop_at: valid = self.board.validate_move(b.origin,b.dest) if self.allow_illegal_play.get(): self.board.apply_ply(b) notate_append(b) continue if len(b.captured) > len(valid[2]): #if game notation is broken, and displays broken ply notate_append(b) self.user_notice.set('Illegal move/capture attempt at move: ' + \ str((a+2.0)/2.0) + \ ". Enable 'allow illegal moves' to see game as notated.") return False elif valid[0] or valid[1]: #valid move or cap self.board.apply_ply(b) notate_append(b) elif not valid[0] and not valid[1] and valid[2]: #materializing troll self.board.add_troll(b.origin) notate_append(b) else: notate_append(b) self.sync_sprites() self.listbox.see(stop_at) self.displayed_ply = stop_at self.review_mode = is_review_mode(stop_at) return True def notate_move(self, ply): """Add move to the listbox of moves""" ply_num = str((len(self.board.ply_list) + 1)/2).ljust(5) self.listbox.insert('end', ply_num + str(ply)) # Colorize alternating lines of the listbox for i in range(0,self.listbox.size(),2): self.listbox.itemconfigure(i, background='#f0f0ff') self.listbox.bind('<<ListboxSelect>>', self.click_listbox_left) self.listbox.yview_moveto(1.0) self.update_ui() def click_listbox_left(self, event): """Retrieves the clicked ply and play_out_move till that point""" try: self.displayed_ply = int(self.listbox.curselection()[0]) except: self.displayed_ply = len(self.board.ply_list) - 1 self.play_out_moves(self.board.ply_list, self.displayed_ply) def is_cpu_turn(self): """ This is the function called 1/second to determine if CPU AI should begin calculating potential moves. """ if self.cpu_troll.get() and self.board.turn_to_act() == 'troll' or \ self.cpu_dwarf.get() and self.board.turn_to_act() == 'dwarf' and \ not self.delay_ai and not self.review_mode and not self.board.game_winner: self.delay_ai = True self.user_notice.set("Computer is thinking...") try: ai_thread = threading.Thread(target=AIEngine.calculate_best_move(self.board, \ self.board.turn_to_act(), \ self.lookahead_count)) ai_thread.start() ai_thread.join() self.execute_ply(ai.decision) self.delay_ai = False except NoMoveException as ex: print("{0} has no moves available.".format(ex.token)) self.delay_ai = True finally: self.board.game_winner = self.board.get_game_outcome() if not self.board.game_winner: self.user_notice.set("") class tkinter_game: def simulate_set(self, trials=5): results = [] for i in range(trials): results.append(self.simulate_game()) print(results) def simulate_game(self): global ui print('game in progress...') ui.newgame_classic() ui.cpu_troll.set(True) ui.cpu_dwarf.set(True) while not ui.board.game_winner: ui.is_cpu_turn() if not len(ui.board.ply_list) % 10: print('Ply {0}: trolls {1} to dwarf {2}'.format( \ len(ui.board.ply_list), \ len(ui.board.trolls), \ len(ui.board.dwarfs))) print('{0} win! trolls {1} to dwarf {2}'.format(ui.board.game_winner, \ len(ui.board.trolls), \ len(ui.board.dwarfs))) return ui.board.game_winner def play_game(self): global ui global root ui.newgame_classic() r = RepeatTimer(.2, ui.is_cpu_turn) r.start() root.mainloop() if __name__ == '__main__': root = tkinter.Tk() root.wm_resizable(0,0) ui = DesktopGUI(root) game = tkinter_game() game.play_game() #game.simulate_set(15)
mit
outr/arangodb-scala
api/src/main/scala/com/outr/arango/api/APIReplicationLoggerFollow.scala
801
package com.outr.arango.api import com.outr.arango.api.model._ import io.youi.client.HttpClient import io.youi.http.HttpMethod import io.youi.net._ import io.circe.Json import scala.concurrent.{ExecutionContext, Future} object APIReplicationLoggerFollow { def get(client: HttpClient, from: Option[Double] = None, to: Option[Double] = None, chunkSize: Option[Double] = None, includeSystem: Option[Boolean] = None)(implicit ec: ExecutionContext): Future[Json] = client .method(HttpMethod.Get) .path(path"/_api/replication/logger-follow", append = true) .param[Option[Double]]("from", from, None) .param[Option[Double]]("to", to, None) .param[Option[Double]]("chunkSize", chunkSize, None) .param[Option[Boolean]]("includeSystem", includeSystem, None) .call[Json] }
mit
brandondahler/Data.HashFunction
src/OpenSource.Data.HashFunction.Test/SpookyHash/SpookyHashV2_Implementation_Tests.cs
12902
using Moq; using MoreLinq; using System; using System.Collections.Generic; using OpenSource.Data.HashFunction.SpookyHash; using OpenSource.Data.HashFunction.Test._Utilities; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using Xunit; namespace OpenSource.Data.HashFunction.Test.SpookyHash { public class SpookyHashV2_Implementation_Tests { #region Constructor [Fact] public void SpookyHashV2_Implementation_Constructor_ValidInputs_Works() { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { spookyHashConfigMock.SetupGet(xhc => xhc.HashSizeInBits) .Returns(32); spookyHashConfigMock.SetupGet(xhc => xhc.Seed) .Returns(0UL); spookyHashConfigMock.SetupGet(xhc => xhc.Seed2) .Returns(0UL); spookyHashConfigMock.Setup(xhc => xhc.Clone()) .Returns(() => spookyHashConfigMock.Object); } GC.KeepAlive( new SpookyHashV2_Implementation(spookyHashConfigMock.Object)); } #region Config [Fact] public void SpookyHashV2_Implementation_Constructor_Config_IsNull_Throws() { Assert.Equal( "config", Assert.Throws<ArgumentNullException>( () => new SpookyHashV2_Implementation(null)) .ParamName); } [Fact] public void SpookyHashV2_Implementation_Constructor_Config_IsCloned() { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { spookyHashConfigMock.Setup(xhc => xhc.Clone()) .Returns(() => new SpookyHashConfig() { HashSizeInBits = 32, }); } GC.KeepAlive( new SpookyHashV2_Implementation(spookyHashConfigMock.Object)); spookyHashConfigMock.Verify(xhc => xhc.Clone(), Times.Once); spookyHashConfigMock.VerifyGet(xhc => xhc.HashSizeInBits, Times.Never); spookyHashConfigMock.VerifyGet(xhc => xhc.Seed, Times.Never); spookyHashConfigMock.VerifyGet(xhc => xhc.Seed2, Times.Never); } #region HashSizeInBits [Fact] public void SpookyHashV2_Implementation_Constructor_Config_HashSizeInBits_IsInvalid_Throws() { var invalidHashSizes = new[] { -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 31, 33, 63, 65, 127, 129, 65535 }; foreach (var invalidHashSize in invalidHashSizes) { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { spookyHashConfigMock.SetupGet(pc => pc.HashSizeInBits) .Returns(invalidHashSize); spookyHashConfigMock.Setup(pc => pc.Clone()) .Returns(() => spookyHashConfigMock.Object); } Assert.Equal( "config.HashSizeInBits", Assert.Throws<ArgumentOutOfRangeException>( () => new SpookyHashV2_Implementation(spookyHashConfigMock.Object)) .ParamName); } } [Fact] public void SpookyHashV2_Implementation_Constructor_Config_HashSizeInBits_IsValid_Works() { var validHashSizes = new[] { 32, 64, 128 }; foreach (var validHashSize in validHashSizes) { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { spookyHashConfigMock.SetupGet(pc => pc.HashSizeInBits) .Returns(validHashSize); spookyHashConfigMock.Setup(pc => pc.Clone()) .Returns(() => spookyHashConfigMock.Object); } GC.KeepAlive( new SpookyHashV2_Implementation(spookyHashConfigMock.Object)); } } #endregion #endregion #endregion #region ComputeHash [Fact] public void SpookyHashV2_Implementation_ComputeHash_HashSizeInBits_MagicallyInvalid_Throws() { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { var readCount = 0; spookyHashConfigMock.SetupGet(xhc => xhc.HashSizeInBits) .Returns(() => { readCount += 1; if (readCount == 1) return 32; return 33; }); spookyHashConfigMock.Setup(xhc => xhc.Clone()) .Returns(() => spookyHashConfigMock.Object); } var spookyHashV2 = new SpookyHashV2_Implementation(spookyHashConfigMock.Object); Assert.Throws<NotImplementedException>( () => spookyHashV2.ComputeHash(new byte[1])); Assert.Throws<NotImplementedException>( () => spookyHashV2.ComputeHash(new byte[200])); } #endregion #region ComputeHashAsync [Fact] public async Task SpookyHashV2_Implementation_ComputeHashAsync_HashSizeInBits_MagicallyInvalid_Throws() { var spookyHashConfigMock = new Mock<ISpookyHashConfig>(); { var readCount = 0; spookyHashConfigMock.SetupGet(xhc => xhc.HashSizeInBits) .Returns(() => { readCount += 1; if (readCount == 1) return 32; return 33; }); spookyHashConfigMock.Setup(xhc => xhc.Clone()) .Returns(() => spookyHashConfigMock.Object); } var spookyHashV2 = new SpookyHashV2_Implementation(spookyHashConfigMock.Object); using (var memoryStream = new MemoryStream(new byte[1])) { await Assert.ThrowsAsync<NotImplementedException>( () => spookyHashV2.ComputeHashAsync(memoryStream)); } using (var memoryStream = new MemoryStream(new byte[200])) { await Assert.ThrowsAsync<NotImplementedException>( () => spookyHashV2.ComputeHashAsync(memoryStream)); } } #endregion public class IStreamableHashFunction_Tests_SpookyHashV2 : IStreamableHashFunction_TestBase<ISpookyHashV2> { protected override IEnumerable<KnownValue> KnownValues { get; } = new KnownValue[] { new KnownValue(32, TestConstants.FooBar, 0x03edde99), new KnownValue(64, TestConstants.FooBar, 0x86c057a503edde99), new KnownValue(128, TestConstants.FooBar, "0x65178fe24e37629a86c057a503edde99"), new KnownValue(32, TestConstants.LoremIpsum.Take(32), 0xa5bd393f), new KnownValue(64, TestConstants.LoremIpsum.Take(32), 0x44721abda5bd393f), new KnownValue(128, TestConstants.LoremIpsum.Take(32), "0xc380651a01d2145a44721abda5bd393f"), new KnownValue(32, TestConstants.LoremIpsum, 0x31721b83), new KnownValue(64, TestConstants.LoremIpsum, 0x4fbc4fc931721b83), new KnownValue(128, TestConstants.LoremIpsum, "0xe73a09a9e9444fbf4fbc4fc931721b83"), new KnownValue(32, TestConstants.LoremIpsum.Repeat(2).Take(192), 0x0e765526), new KnownValue(64, TestConstants.LoremIpsum.Repeat(2).Take(192), 0x67863a1c0e765526), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2).Take(192), "0xe9e372a07a93d03967863a1c0e765526"), new KnownValue(32, TestConstants.LoremIpsum.Repeat(2), 0xdfb234f5), new KnownValue(64, TestConstants.LoremIpsum.Repeat(2), 0xf74f56b5dfb234f5), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2), "0x77e5497a48eb7d87f74f56b5dfb234f5"), }; protected override ISpookyHashV2 CreateHashFunction(int hashSize) => new SpookyHashV2_Implementation( new SpookyHashConfig() { HashSizeInBits = hashSize }); } public class IStreamableHashFunction_Tests_SpookyHashV2_DefaultConstructor : IStreamableHashFunction_TestBase<ISpookyHashV2> { protected override IEnumerable<KnownValue> KnownValues { get; } = new KnownValue[] { new KnownValue(128, TestConstants.FooBar, "0x65178fe24e37629a86c057a503edde99"), new KnownValue(128, TestConstants.LoremIpsum.Take(32), "0xc380651a01d2145a44721abda5bd393f"), new KnownValue(128, TestConstants.LoremIpsum, "0xe73a09a9e9444fbf4fbc4fc931721b83"), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2).Take(192), "0xe9e372a07a93d03967863a1c0e765526"), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2), "0x77e5497a48eb7d87f74f56b5dfb234f5"), }; protected override ISpookyHashV2 CreateHashFunction(int hashSize) => new SpookyHashV2_Implementation( new SpookyHashConfig()); } public class IStreamableHashFunction_Tests_SpookyHashV2_WithInitVals : IStreamableHashFunction_TestBase<ISpookyHashV2> { protected override IEnumerable<KnownValue> KnownValues { get; } = new KnownValue[] { new KnownValue(32, TestConstants.FooBar, 0x483d3ccb), new KnownValue(64, TestConstants.FooBar, 0xbae646079590f776), new KnownValue(128, TestConstants.FooBar, "0x2c4b1133420215fb7ede1820d78879c0"), new KnownValue(32, TestConstants.LoremIpsum.Take(32), 0x0634d287), new KnownValue(64, TestConstants.LoremIpsum.Take(32), 0x667c9542154e1fef), new KnownValue(128, TestConstants.LoremIpsum.Take(32), "0xdd855bfaf2f512db303aa37ebfabe0e2"), new KnownValue(32, TestConstants.LoremIpsum, 0xea0be1ba), new KnownValue(64, TestConstants.LoremIpsum, 0xae0e662599259866), new KnownValue(128, TestConstants.LoremIpsum, "0x5bc551262e72f6ee47fdf637e6979f99"), new KnownValue(32, TestConstants.LoremIpsum.Repeat(2).Take(192), 0xc6b86135), new KnownValue(64, TestConstants.LoremIpsum.Repeat(2).Take(192), 0x82ae10987beb42e3), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2).Take(192), "0x184eae95e673e6c09e485a8437aad039"), new KnownValue(32, TestConstants.LoremIpsum.Repeat(2), 0x24b0ca21), new KnownValue(64, TestConstants.LoremIpsum.Repeat(2), 0x360ee3ab3d90bb39), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2), "0xa5b26b9158f37618d5aa11f954f74544"), }; protected override ISpookyHashV2 CreateHashFunction(int hashSize) => new SpookyHashV2_Implementation( new SpookyHashConfig() { HashSizeInBits = hashSize, Seed = 0x7da236b987930b75U, Seed2 = 0x2eb994a3851d2f54U }); } public class IStreamableHashFunction_Tests_SpookyHashV2_WithInitVals_DefaultHashSize : IStreamableHashFunction_TestBase<ISpookyHashV2> { protected override IEnumerable<KnownValue> KnownValues { get; } = new KnownValue[] { new KnownValue(128, TestConstants.FooBar, "0x2c4b1133420215fb7ede1820d78879c0"), new KnownValue(128, TestConstants.LoremIpsum.Take(32), "0xdd855bfaf2f512db303aa37ebfabe0e2"), new KnownValue(128, TestConstants.LoremIpsum, "0x5bc551262e72f6ee47fdf637e6979f99"), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2).Take(192), "0x184eae95e673e6c09e485a8437aad039"), new KnownValue(128, TestConstants.LoremIpsum.Repeat(2), "0xa5b26b9158f37618d5aa11f954f74544"), }; protected override ISpookyHashV2 CreateHashFunction(int hashSize) => new SpookyHashV2_Implementation( new SpookyHashConfig() { Seed = 0x7da236b987930b75U, Seed2 = 0x2eb994a3851d2f54U }); } } }
mit
munkey01/DukeJavaStructuredData
src/test/Week2/testGladLibs.java
262
package Week2; import src.java.Week2.GladLib; /** * Created by jgrant on 1/27/2017. */ public class testGladLibs { public static void main(String[] args) { GladLib glad = new GladLib(); System.out.println(glad.createStory()); } }
mit
davidedantonio/mantis
public/dashboard/controllers/ModalDeleteDashboardController.js
475
app.controller('ModalDeleteDashboardController', function ($scope, $modalInstance, $http, $location, params) { $scope.dashboardId = params.id; $scope.deleteDashboard = function () { $http.delete('/dashboards/delete/'+$scope.dashboardId) .success(function(data, status, headers, config) { if (status == 200) { $modalInstance.close(data); } }); }; $scope.cancel = function () { $modalInstance.dismiss('cancel'); }; });
mit
joek/picoborgrev
picoborgrev_suite_test.go
206
package picoborgrev_test import ( . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "testing" ) func TestPicoborgrev(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Picoborgrev Suite") }
mit