code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import { Component, HostListener } from '@angular/core'; import { RedditService } from '../../shared/services/reddit.service'; import { Comment } from '../../shared/models/comment'; @Component({ selector: 'my-app', templateUrl: 'app/components/main/app.component.html', styleUrls: ['app/components/main/app.css'], providers: [RedditService] }) export class AppComponent { constructor(private redditService: RedditService) { } name: string = 'Steven'; content: string = 'fuckits'; currentImage: string; comments: Comment[]; windowObject:any; imageHeight:string; currentPostPosition:number = 0; arrayOfPostUrls: Array<string> = []; @HostListener('window:keydown', ['$event']) onKeyDown(event) { if (event.code==='ArrowRight'){ if (this.currentPostPosition<this.arrayOfPostUrls.length){ this.currentPostPosition+=1; this.getRealGirlsPosts(); } } else if (event.code==='ArrowLeft'){ if (this.currentPostPosition!=0){ this.currentPostPosition-=1; this.getRealGirlsPosts(); } } } ngOnInit(){ console.log('I am inniting'); this.getRealGirlsPosts(); // size the image this.windowObject = window["mainScreen"]; //access global (renderer.js is not working so i moved the global to index.html) console.log(this.windowObject.workAreaSize.height); this.imageHeight = String(Number(this.windowObject.workAreaSize.height)-100); } getComments(permalink) { this.redditService.getDetailedRedditPost(permalink).subscribe(data => { console.log(data); this.currentImage = data[0].data.children[0].data.url; this.comments = data[1].data.children; console.log(this.comments); }); } getRealGirlsPosts(){ this.redditService.getRealGirlsPosts() .subscribe(data=>{ console.log('real girls'); console.log(data); data.data.children.forEach((post, key)=>{ console.log(post.data.permalink); this.arrayOfPostUrls.push(post.data.permalink); }); this.getComments(this.arrayOfPostUrls[this.currentPostPosition]); }) } setName(newName: string) { this.name = newName; } }
satoshi-fapamoto/guzl
app/components/main/app.component.ts
TypeScript
mit
2,077
package hr.hrg.hipster.sql; public interface Key<K> { public Class<K> getType(); public int ordinal(); }
hrgdavor/java-hipster-sql
sql/src/main/java/hr/hrg/hipster/sql/Key.java
Java
mit
109
package com.syntacticsugar.vooga.gameplayer.universe.map.tiles.effects; import com.syntacticsugar.vooga.gameplayer.attribute.TimedDespawnAttribute; import java.io.Serializable; import com.syntacticsugar.vooga.gameplayer.event.implementations.HealthChangeEvent; import com.syntacticsugar.vooga.gameplayer.event.implementations.ObjectSpawnEvent; import com.syntacticsugar.vooga.gameplayer.objects.GameObject; import com.syntacticsugar.vooga.gameplayer.objects.GameObjectType; import com.syntacticsugar.vooga.gameplayer.objects.IGameObject; import com.syntacticsugar.vooga.gameplayer.universe.IGameUniverse; import com.syntacticsugar.vooga.gameplayer.universe.map.IGameMap; public class TileDamageTemporaryEffect extends AbstractTileEffect implements Serializable { private static final long serialVersionUID = 10L; private Double myDamage; private int myDelay; private int myFrameCount; private String myHitImagePath; private int myImagePersistenceLength; public TileDamageTemporaryEffect(Double d, int time) { myDamage = d; myDelay = time; myFrameCount = 0; myHitImagePath = null; myImagePersistenceLength = 20; } @Override protected void doEffect(IGameUniverse universe) { if (myFrameCount >= myDelay) { IGameMap map = universe.getMap(); for (IGameObject obj: universe.getGameObjects()){ if (map.getTile(obj.getBoundingBox().getPoint()).equals(myTile)) { HealthChangeEvent health = new HealthChangeEvent(myDamage); health.executeEvent(obj); } } if (myHitImagePath != null) { IGameObject obj = new GameObject(GameObjectType.ITEM, myTile.getPoint(), map.getTileSize(), map.getTileSize(), myHitImagePath); TimedDespawnAttribute timer = new TimedDespawnAttribute(); timer.setTimeHere(myImagePersistenceLength); obj.addAttribute(timer); timer.setParent(obj); ObjectSpawnEvent event = new ObjectSpawnEvent(obj); universe.postEvent(event); } myTile.setTileEffect(null); } myFrameCount++; } @Override public String getEffectName() { return this.getClass().getSimpleName().substring(4, this.getClass().getSimpleName().length() - 6); } public String getHitImagePath() { return myHitImagePath; } public void setHitImagePath(String hitImagePath) { this.myHitImagePath = hitImagePath; } public int getImagePersistenceLength() { return myImagePersistenceLength; } public void setImagePersistenceLength(int ImagePersistenceLength) { this.myImagePersistenceLength = ImagePersistenceLength; } }
nbv3/voogasalad_CS308
src/com/syntacticsugar/vooga/gameplayer/universe/map/tiles/effects/TileDamageTemporaryEffect.java
Java
mit
2,517
<?php namespace Dboss\Repository; use Doctrine\ORM\EntityRepository; use Dboss\Entity; use Dboss\Xtea; class UserRepository extends EntityRepository { /** * **/ public function findActiveUsers() { $criteria = array('deletion_date' => null); return $this->findBy($criteria); } /** * **/ public function findInactiveUsers() { $qb = $this->createQueryBuilder('u'); $qb->where($qb->expr()->isNotNull('u.deletion_date')); return $qb->getQuery()->getResult(); } /** * */ public function findByUserName($security, $user_name = null) { if (is_null($user_name)) { return; } $xtea = new Xtea($security['salt_key']); $encrypted_user_name = $xtea->encrypt($user_name); $criteria = array('user_name' => $encrypted_user_name); return $this->findOneBy($criteria); } }
jschneider98/dBoss
module/Dboss/src/Dboss/Repository/UserRepository.php
PHP
mit
942
// // HW1_4a.cpp // Homework 1 // // Raymond Dam // // #include <iostream> #include <fstream> //file io stuff #include <cstring> //using strings #include <sstream> #include <stdlib.h> //atoi to convert string to int #include <ctime> //for timing using namespace std; //***function prototypes & global variables***// int recursion (int n, int &sum); void fileio (string inputfile, int n); int *a; //********************************************// int main () { int n; // number of elements in the array a int sum = 0; // we’ll use this for adding numbers string inputfile; // holds name of the input file //ask user how many elements there are in the array cout << endl; cout << "How many numbers are in your dataset?" << endl; cout << "User Entry: "; cin >> n; //ask user to enter name of input file cout << endl; cout << "Please the name of your input file." << endl; cout << "User Entry: "; cin >> inputfile; //dynamically allocate an array based on user entry to pointer, a a = new int [n]; //call fileio function fileio(inputfile, n); //subtract by one so we stay within the array when we do recursion n -= 1; //***start the clock!!***// clock_t start, finish; double dur; start = clock(); //***********************// /* //for loop method sum = 0; for (int i = 0; i < n; i ++) { sum += a[i]; } */ //call recursion function to sum up array recursion(n, sum); //***stop the clock!!***// finish = clock(); dur = (double)(finish - start); dur /= CLOCKS_PER_SEC; cout << "Elapsed seconds: " << scientific << dur << endl; //**********************// cout << endl; cout << sum << endl; //release dynamically allocated memory delete [] a; return 0; } //recursive algorithm that sums the array int recursion (int n, int &sum) { if (n == 0) { sum += a[n]; //a[0] is still storing a value return sum; } else { sum += a[n]; return recursion (n-1, sum); } } //reads in a file with a list of numbers and stores the dataset in the array void fileio (string inputfile, int n) { ifstream filein(inputfile.c_str()); //if and else statements for input validation of the user file if (!filein) { cout << endl; cout << "Invalid file. Please check the name and location of your file and try again." << endl; cout << endl; cout << "----------------------------------------------------------------------------" << endl; } else { for (int i = 0; i < n; i++) { int temp; //parses file for data filein >> temp; //store data in array a[i] = temp; } } filein.close(); }
sh0rtfuse/CS104_DataStructures
IntroProgram/Problem4a/HW1_4a.cpp
C++
mit
3,192
""" Django settings for ecommerce project. Generated by 'django-admin startproject' using Django 1.8. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) #root of project #BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'csqwlmc8s55o($rt6ozh7u+ui9zb-et00w$d90j8$^!nvj41_r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ['*'] EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'stroms38@gmail.com' EMAIL_HOST_PASSWORD = 'yourpassword' EMAIL_PORT = 587 EMAIL_USE_TLS = True ''' If using gmail, you will need to unlock Captcha to enable Django to send for you: https://accounts.google.com/displayunlockcaptcha ''' # Application definition INSTALLED_APPS = ( #django app 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', #third party apps 'crispy_forms', 'registration', #my apps 'answers', 'newsletter', "products", "carts", "billing", "django_filters", "storages", 'gunicorn', "djstripe", ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', ) ROOT_URLCONF = 'ecommerce.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, "templates")], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'ecommerce.wsgi.application' # Database # https://docs.djangoproject.com/en/1.8/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Internationalization # https://docs.djangoproject.com/en/1.8/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'EST' USE_I18N = True USE_L10N = True USE_TZ = True '''Image storage Amazon S3''' AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'examplefy' S3_URL = 'http://%s.s3.amazonaws.com/' % AWS_STORAGE_BUCKET_NAME STATIC_URL = S3_URL AWS_QUERYSTRING_AUTH = False # Honor the 'X-Forwarded-Proto' header for request.is_secure() SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' '''Static storage''' # # Static files (CSS, JavaScript, Images) # # https://docs.djangoproject.com/en/1.8/howto/static-files/ # STATIC_ROOT = 'staticfiles' # STATIC_URL = '/static/' # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "static_root") # MEDIA_URL = '/media/' # MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "media_root") # PROTECTED_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static_in_env", "protected_root") # STATICFILES_DIRS = ( # os.path.join(BASE_DIR, "static", "static_root"), # #os.path.join(BASE_DIR, "static_in_env"), # #'/var/www/static/', # ) #Production Code #Parse database configuration from $DATABASE_URL #import dj_database_url #DATABASES['default'] = dj_database_url.config() # #BOTO S3 Storage for Production ONLY STATICFILES_STORAGE = 'storages.backends.s3boto.S3BotoStorage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static', "static_root"), ) # Simplified static file serving. # https://warehouse.python.org/project/whitenoise/ # STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' # STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static_root") MEDIA_URL = S3_URL MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media_root") PROTECTED_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "protected_root") # TEMPLATE_DIRS = ( # os.path.join(BASE_DIR, "templates"), # ) # here() gives us file paths from the root of the system to the directory # holding the current file. here = lambda * x: os.path.join(os.path.abspath(os.path.dirname(__file__)), *x) PROJECT_ROOT = here("..") # root() gives us file paths from the root of the system to whatever # folder(s) we pass it starting at the parent directory of the current file. root = lambda * x: os.path.join(os.path.abspath(PROJECT_ROOT), *x) TEMPLATE_DIRS = ( root('templates'), ) #Crispy FORM TAGs SETTINGS CRISPY_TEMPLATE_PACK = 'bootstrap3' #DJANGO REGISTRATION REDUX SETTINGS ACCOUNT_ACTIVATION_DAYS = 7 REGISTRATION_AUTO_LOGIN = True SITE_ID = 1 LOGIN_REDIRECT_URL = '/' #Braintree BRAINTREE_PUBLIC = "hsjhmqhy73rvpqbv" BRAINTREE_PRIVATE = "37b06da7e2cdb493bf0e0ddb1c47cbcd" BRAINTREE_MERCHANT = "bgd7scxjbcrz6dd2" BRAINTREE_ENVIRONMENT = "Sandbox" #Stripe STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "pk_test_lLFAbBOc7bHtpxq5QnIp94xh") STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "sk_test_hWkIxMrsvR3IGJIRKLRy1Rts") CURRENCIES = getattr(settings, "DJSTRIPE_CURRENCIES", ( ('usd', 'U.S. Dollars',), ('gbp', 'Pounds (GBP)',), ('eur', 'Euros',)) ) DJSTRIPE_PLANS = { "one-time": { "stripe_plan_id": "one-time", "name": "Examplefy ($0.99)", "description": "A one-time buy to Examplefy", "price": 99, # $0.99 "currency": "usd", "interval": "day" }, "monthly": { "stripe_plan_id": "pro-monthly", "name": "Examplefy Pro ($4.99/month)", "description": "The monthly subscription plan to Examplefy", "price": 499, # $4.99 "currency": "usd", "interval": "month", "interval_count": 1 }, "yearly": { "stripe_plan_id": "pro-yearly", "name": "Examplefy Prime ($49/year)", "description": "The annual subscription plan to Examplefy", "price": 4900, # $49.00 "currency": "usd", "interval": "year", "interval_count": 1 } }
Maelstroms38/ecommerce
src/ecommerce/settings/local.py
Python
mit
7,411
<?php /** * @package uUtilitiesPlugin * @subpackage uCron * @author Henning Glatter-Gotz <henning@glatter-gotz.com> */ class uCron { /** * Creates a shell script (.sh) in $scriptFullPath that calls a symfony task * $sfTaskCall. It then creates a symlink to the shell scrip from $cronPath. * * $cronPath must be one of the following: * - /etc/cron.hourly * - /etc/cron.daily * - /etc/cron.weekly * - /etc/cron.monthly * * This of course requires that the system is setup for this type of * configuration. The method is called generic because it makes use of one of * these pre-defined time slots. * * $scripFullPath must be a valid path including the name of the script file. * It is recommended that this be in the application directory called scripts. * * Example: /var/www/httpdocs/backend/1.0.2/apps/cron/scripts/myTaskCall.sh * * $sfTaskCall must be the complete command line to call the symfony task * including the full path and all parameters and options. * * Example: /var/www/httpdocs/backend/1.0.2/symfony ns:task --option=something * * @param string $cronPath Path to cron script call (ex: /etc/cron.hourly) * @param strint $scriptFullPath The full path of the script that cron will call * @param string $sfTaskCall The sf task that the script should call (including parameters) */ public static function generic($scriptFullPath, $sfTaskCall, $cronPath) { $DS = DIRECTORY_SEPARATOR; $pi = pathinfo($scriptFullPath); $scriptPath = $pi['dirname']; uFs::mkdir($scriptPath, true); uFs::chmod($scriptPath, 0755, true); $sh = '#!/bin/bash'.PHP_EOL; $sh .= 'php '.sfConfig::get('sf_root_dir').$DS.$sfTaskCall.PHP_EOL; $linkName = $cronPath.$DS.$pi['filename']; $target = $scriptFullPath; uFs::file_put_contents($scriptFullPath, $sh); uFs::chmod($scriptFullPath, 0777, true); uFs::symlink($target, $linkName, true); } /** * Install a cron job that runs at a custom time (other than the .hourly/ * .daily/.weekly/.monthly. A file in the same format as /etc/crontab is * created in /etc/cron.d with permissions 644. * * $fileName should not have any extension and is the name of the file that * wil be created in $cronPath. * * $time is a string that represents the customary cron time format: * minute hour day month dayofweek * * minute - any integer from 0 to 59 * hour - any integer from 0 to 23 * day - any integer from 1 to 31 (must be a valid day if a month is * specified) * month - any integer from 1 to 12 (or the short name of the month such * as jan or feb) * dayofweek - any integer from 0 to 7, where 0 or 7 represents Sunday (or * the short name of the week such as sun or mon) * * Example: run the command at 7 am every day * 0 7 * * * * * $sfTaskCall is the symfony command line that the script should execute. * * @param <type> $cronPath Path to the cron directory (must be /etc/cron.d) * @param <type> $fileName Name of the file to be created in $cronPath * @param <type> $time Cron time format (see above) * @param <type> $sfTaskCall The command to call */ static public function custom($fileName, $time, $sfTaskCall, $cronPath = '/etc/cron.d') { $DS = DIRECTORY_SEPARATOR; $fullPath = $cronPath.$DS.$fileName; $command = $time.' root php '.sfConfig::get('sf_root_dir').$DS.$sfTaskCall.PHP_EOL; uFs::file_put_contents($fullPath, $command); uFs::chmod($fullPath, 0644, true); } /** * Determine if a cron scheduling string is equivalent to the dateTime string * passed as the second paramter. * * Example: * $cron = '* * * * *'; * $dateString = '2010-08-10 22:02:00'; * * In this case the function would return true since the cron string * indicates that the job should execute every minute. * * $cron = '* 15 * * *'; * $dateString = '2010-08-10 22:02:00'; * * This would result in false, since the hour in the cron string is 15 and * the hour in the dateTime string is 22. Therefor no match. * * @param string $cron * @param string $dateString * @return boolean */ public static function matchCronToTimeStamp($cron, $dateString) { $cr = self::cronStringToArray($cron); $str = self::timeStampToArray($dateString); if ($cr['minute'] != $str['minute'] && $cr['minute'] != '*') { return false; } if ($cr['hour'] != $str['hour'] && $cr['hour'] != '*') { return false; } if ($cr['day'] != $str['day'] && $cr['day'] != '*') { return false; } if ($cr['month'] != $str['month'] && $cr['month'] != '*') { return false; } if ($cr['day_of_week'] != $str['day_of_week'] && $cr['day_of_week'] != '*') { return false; } return true; } /** * Return an array that contains the parts of a cron configuration string. * * @return array */ protected static function getCronPartsArray() { return array('minute' => '', 'hour' => '', 'day' => '', 'month' => '', 'day_of_week' => ''); } /** * Convert a cron configuration string into an array. * * @param string $cron * @return array */ protected static function cronStringToArray($cron) { $parts = self::getCronPartsArray(); list($parts['minute'], $parts['hour'], $parts['day'], $parts['month'], $parts['day_of_week']) = explode(' ', $cron); if ($parts['day_of_week' == '0']) { $parts['day_of_week'] = '7'; } return $parts; } /** * Convert a date time string into the components of a cron configuration * string. * * @param string $dateString * @return array */ protected static function timeStampToArray($dateString) { $parts = self::getCronPartsArray(); $timeStamp = uDateTime::strtotime($dateString); $parts['minute'] = intval(date("i", $timeStamp)); $parts['hour'] = date("G", $timeStamp); $parts['day'] = date("j", $timeStamp); $parts['month'] = date("n", $timeStamp); $parts['day_of_week'] = date("N", $timeStamp); return $parts; } }
hglattergotz/uUtilitiesPlugin
lib/uCron.class.php
PHP
mit
6,322
"""geo.py: Implementation of class AbstractTwitterGeoCommand and its subclasses. """ from argparse import ArgumentParser from . import (AbstractTwitterCommand, call_decorator) from ..parsers import (filter_args, cache) # GET geo/id/:place_id # POST geo/place DEPRECATED # GET geo/reverse_geocode # GET geo/search GEO_ID_PLACE_ID = ('geo/id/:place_id', 'id') GEO_REVERSE_GEOCODE = ('geo/reverse_geocode', 'reverse') GEO_SEARCH = ('geo/search', 'search') # pylint: disable=abstract-method class AbstractTwitterGeoCommand(AbstractTwitterCommand): """n/a""" pass class IdPlaceId(AbstractTwitterGeoCommand): """Output all the information about a known place.""" def create_parser(self, subparsers): parser = subparsers.add_parser( GEO_ID_PLACE_ID[0], aliases=GEO_ID_PLACE_ID[1:], help=self.__doc__) parser.add_argument( 'place_id', help='a place in the world where can be retrieved ' 'from geo/reverse_geocode') return parser @call_decorator def __call__(self): """Request GET geo/id/:place_id for Twitter.""" # pylint: disable=protected-access kwargs = dict(_id=self.args.place_id) return kwargs, self.twhandler.geo.id._id # hack? class ReverseGeocode(AbstractTwitterGeoCommand): """Search for up to 20 places that can be used as a place_id.""" def create_parser(self, subparsers): parser = subparsers.add_parser( GEO_REVERSE_GEOCODE[0], aliases=GEO_REVERSE_GEOCODE[1:], parents=[parser_geo_common()], help=self.__doc__) parser.add_argument( 'long', metavar='{-180.0..180.0}', help='the longitude to search around') parser.add_argument( 'lat', metavar='{-90.0..90.0}', help='the latitude to search around') return parser @call_decorator def __call__(self): """Request GET geo/reverse_geocode for Twitter.""" kwargs = filter_args( vars(self.args), 'lat', 'long', 'accuracy', 'granularity', 'max_results') return kwargs, self.twhandler.geo.reverse_geocode class Search(AbstractTwitterGeoCommand): """Search for places that can be attached to a statuses/update.""" def create_parser(self, subparsers): parser = subparsers.add_parser( GEO_SEARCH[0], aliases=GEO_SEARCH[1:], parents=[parser_geo_common()], help=self.__doc__) parser.add_argument( '--long', metavar='{-180.0..180.0}', help='the longitude to search around') parser.add_argument( '--lat', metavar='{-90.0..90.0}', help='the latitude to search around') parser.add_argument( '-q', '--query', metavar='<text>', help='free-form text to match against ' 'while executing a geo-based query') parser.add_argument( '-i', '--ip-address', dest='ip', metavar='<ip-address>', help='an IP address') parser.add_argument( '-c', '--contained-within', dest='contained_within', metavar='<place_id>', help='the place_id which you would like ' 'to restrict the search results to') parser.add_argument( '-s', '--street-address', dest='street_address', metavar='<text>', help='search for places which have this given street address') return parser @call_decorator def __call__(self): """Request GET geo/search for Twitter.""" kwargs = filter_args( vars(self.args), 'lat', 'long', 'accuracy', 'granularity', 'max_results', 'query', 'ip', 'contained_within', 'street_address') return kwargs, self.twhandler.geo.search def make_commands(manager): """Prototype""" # pylint: disable=no-member return (cmd_t(manager) for cmd_t in AbstractTwitterGeoCommand.__subclasses__()) CHOICES = ('poi', 'neighborhood', 'city', 'admin', 'country') @cache def parser_geo_common(): """Return the parser for common arguments.""" parser = ArgumentParser(add_help=False) parser.add_argument( '-a', '--accuracy', help='a hint on the region in which to search') parser.add_argument( '-g', '--granularity', choices=CHOICES, metavar='|'.join(CHOICES), help='the minimal granularity of place types to return') parser.add_argument( '-m', '--max-results', type=int, dest='max_results', help='a hint as to the number of results to return') return parser
showa-yojyo/bin
twmods/commands/geo.py
Python
mit
4,854
+(function (factory) { if (typeof exports === 'undefined') { factory(webduino || {}); } else { module.exports = factory; } }(function (scope) { 'use strict'; // source: // https://raw.githubusercontent.com/twistdigital/es6-promisify/release/2.0.0/lib/promisify.js // Promise Context object constructor. function Context(resolve, reject, custom) { this.resolve = resolve; this.reject = reject; this.custom = custom; } // Default callback function - rejects on truthy error, otherwise resolves function callback(ctx, err, result) { if (typeof ctx.custom === 'function') { var cust = function () { // Bind the callback to itself, so the resolve and reject // properties that we bound are available to the callback. // Then we push it onto the end of the arguments array. return ctx.custom.apply(cust, arguments); }; cust.resolve = ctx.resolve; cust.reject = ctx.reject; cust.call(null, err, result); } else { if (err) { return ctx.reject(err); } ctx.resolve(result); } } function promisify(original, custom) { return function () { // Store original context var that = this, args = Array.prototype.slice.call(arguments); // Return the promisified function return new Promise(function (resolve, reject) { // Create a Context object var ctx = new Context(resolve, reject, custom); // Append the callback bound to the context args.push(callback.bind(null, ctx)); // Call the function original.apply(that, args); }); }; } scope.util.promisify = promisify; }));
marty5499/webduino
bower_components/webduino-js/src/util/promisify.js
JavaScript
mit
1,708
<?php namespace Preferans\Oauth\Entities; /** * Preferans\Oauth\Entities\ClientEntityInterface * * @package Preferans\Oauth\Entities */ interface ClientEntityInterface { /** * Get the client's identifier. * * @return string */ public function getIdentifier(); /** * Get the client's name. * * @return string */ public function getName(); /** * Returns the registered redirect URI (as a string). * * Alternatively return an indexed array of redirect URIs. * * @return string|string[] */ public function getRedirectUri(); }
preferans/oauth-bridge
src/Entities/ClientEntityInterface.php
PHP
mit
624
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_72a.cpp Label Definition File: CWE78_OS_Command_Injection.strings.label.xml Template File: sources-sink-72a.tmpl.cpp */ /* * @description * CWE: 78 OS Command Injection * BadSource: console Read input from the console * GoodSource: Fixed string * Sinks: w32_spawnv * BadSink : execute command with wspawnv * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> #include <wchar.h> #ifdef _WIN32 #define COMMAND_INT_PATH L"%WINDIR%\\system32\\cmd.exe" #define COMMAND_INT L"cmd.exe" #define COMMAND_ARG1 L"/c" #define COMMAND_ARG2 L"dir" #define COMMAND_ARG3 data #else /* NOT _WIN32 */ #include <unistd.h> #define COMMAND_INT_PATH L"/bin/sh" #define COMMAND_INT L"sh" #define COMMAND_ARG1 L"ls" #define COMMAND_ARG2 L"-la" #define COMMAND_ARG3 data #endif using namespace std; namespace CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_72 { #ifndef OMITBAD /* bad function declaration */ void badSink(vector<wchar_t *> dataVector); void bad() { wchar_t * data; vector<wchar_t *> dataVector; wchar_t dataBuffer[100] = L""; data = dataBuffer; { /* Read input from the console */ size_t dataLen = wcslen(data); /* if there is room in data, read into it from the console */ if (100-dataLen > 1) { /* POTENTIAL FLAW: Read data from the console */ if (fgetws(data+dataLen, (int)(100-dataLen), stdin) != NULL) { /* The next few lines remove the carriage return from the string that is * inserted by fgetws() */ dataLen = wcslen(data); if (dataLen > 0 && data[dataLen-1] == L'\n') { data[dataLen-1] = L'\0'; } } else { printLine("fgetws() failed"); /* Restore NUL terminator if fgetws fails */ data[dataLen] = L'\0'; } } } /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); badSink(dataVector); } #endif /* OMITBAD */ #ifndef OMITGOOD /* good function declarations */ /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<wchar_t *> dataVector); static void goodG2B() { wchar_t * data; vector<wchar_t *> dataVector; wchar_t dataBuffer[100] = L""; data = dataBuffer; /* FIX: Append a fixed string to data (not user / external input) */ wcscat(data, L"*.*"); /* Put data in a vector */ dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); dataVector.insert(dataVector.end(), 1, data); goodG2BSink(dataVector); } void good() { goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on * its own for testing or for building a binary to use in testing binary * analysis tools. It is not used when compiling all the testcases as one * application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_72; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
maurer/tiamat
samples/Juliet/testcases/CWE78_OS_Command_Injection/s06/CWE78_OS_Command_Injection__wchar_t_console_w32_spawnv_72a.cpp
C++
mit
4,013
<?php namespace application\components; use \Yii; use \CException; /** * Active Form Widget * * @author Zander Baldwin <mynameiszanders@gmail.com> * @link https://github.com/mynameiszanders/yii-forms * @copyright 2013 Zander Baldwin * @license MIT/X11 <http://j.mp/license> * @package application.components */ class ActiveForm extends \CActiveForm { /** * Constructor Method * * @access public * @return void */ public function __construct($owner = null) { parent::__construct($owner); \application\components\EventManager::attach($this); } /** * Render: Input Field * * @access public * @param \CForm $form * @param string $field * @param array $htmlOptions * @return string */ public function input(\CForm $form, $attribute, $htmlOptions = array()) { // Firstly, does the element with the specified field name exist? if(!isset($form->elements[$attribute])) { throw new CException( is_string($attribute) ? Yii::t('application', 'Invalid form element identifier "{element}" was passed to "application\\components\\Form.input()".', array('{element}' => $attribute)) : Yii::t('application', 'Invalid data type passed to "application\\components\\Form.input()". A string is required to identify a form element.') ); } // Assign the $element variable the instance of the actual element, instead of just its string identifier. $element = $form->elements[$attribute]; // If the element type maps to a method of CHtml, use that to render it. if(isset($element::$coreTypes[$element->type])) { $method = $element::$coreTypes[$element->type]; // Merge the HTML options passed with the attributes set in the form configuration, this is also used to // override options in the form configuration on a per-theme basis. $htmlOptions = \CMap::mergeArray($element->attributes, $htmlOptions); // Render element. return strpos($method, 'List') !== false // If the method contains the word "List", then it means that it needs items to populate that list. ? \CHtml::$method($form->model, $element->name, $element->items, $htmlOptions) // Otherwise we can omit that requirement and skip items, jumping straight to the HTML options. : \CHtml::$method($form->model, $element->name, $htmlOptions); } // If it doesn't map to a method of CHtml, then assume that the type specified is a widget to run. else { $element->attributes['htmlOptions'] = isset($element->attributes['htmlOptions']) ? CMap::mergeArray($element->attributes['htmlOptions'], $htmlOptions) : $htmlOptions; $element->attributes['model'] = $form->model; $element->attributes['attribute'] = $element->name; ob_start(); $form->getOwner()->widget($element->type, $element->attributes); return ob_get_clean(); } } /** * Render: Button * * @access public * @param \CForm $form * @param string $button * @param array $htmlOptions * @return string */ public function button(\CForm $form, $attribute, array $htmlOptions = array()) { // Firstly, does the button with the specified name exist? if(!isset($form->buttons[$attribute])) { throw new CException( is_string($attribute) ? Yii::t('application', 'Invalid form button identifier "{button}" was passed to "application\\components\\Form.button()".', array('{button}' => $attribute)) : Yii::t('application', 'Invalid data type passed to "application\\components\\Form.button()". A string is required to identify a form button.') ); } // Assign the $button variable the instance of the actual button, instead of just its string identifier. $button = $form->buttons[$attribute]; // If the button type maps to a method of CHtml, use that to render it. if(isset($button::$coreTypes[$button->type])) { $method = $button::$coreTypes[$button->type]; // Merge the HTML options passed with the attributes set in the form configuration, this is also used to // override options in the form configuration on a per-theme basis. $button->attributes = \CMap::mergeArray($button->attributes, $htmlOptions); switch($method) { case 'linkButton': $attributes['params'][$this->name] = isset($button->attributes['params'][$this->name]) ? $attributes['params'][$this->name] : 1; break; case 'htmlButton': switch($button->type) { case 'htmlSubmit': $button->attributes['type'] = 'submit'; break; case 'htmlReset': $button->attributes['type'] = 'reset'; break; default: $button->attributes['type'] = 'button'; break; } $button->attributes['name'] = $button->name; break; default: $button->attributes['name'] = $button->name; } return $method === 'imageButton' ? \CHtml::$method(isset($button->attributes['src']) ? $button->attributes['src'] : '', $button->attributes) : \CHtml::$method($button->label, $button->attributes); } else { $button->attributes['htmlOptions'] = isset($button->attributes['htmlOptions']) ? CMap::mergeArray($button->attributes['htmlOptions'], $htmlOptions) : $htmlOptions; $button->attributes['name'] = $button->name; ob_start(); $form->getOwner()->widget($button->type, $button->attributes); return ob_get_clean(); } } /** * Label * * A wrapper for CHtml::activeLabel(). It overrides the label() method in the parent class, CActiveForm, to * allow for form objects to be passed as well as form models. * * @access public * @param CForm|CModel $formModel * @param string $attribute * @param array $htmlOptions * @return string */ public function label($formModel, $attribute, $htmlOptions = array()) { if($formModel instanceof \CForm && isset($formModel->model) && $formModel->model instanceof \CModel) { $formModel = $formModel->model; } return parent::label($formModel, $attribute, $htmlOptions); } /** * Label (Extra) * * A wrapper for CHtml::activeLabelEx(). It overrides the labelEx() method in the parent class, CActiveForm, to * allow for form objects to be passed as well as form models. * * @access public * @param CForm|CModel $formModel * @param string $attribute * @param array $htmlOptions * @return string */ public function labelEx($formModel, $attribute, $htmlOptions = array()) { if($formModel instanceof \CForm && isset($formModel->model) && $formModel->model instanceof \CModel) { $formModel = $formModel->model; } return parent::labelEx($formModel, $attribute, $htmlOptions); } /** * Error * * A wrapper for the error() method in the parent class, CActiveForm, to allow for form objects to be passed as * well as form models. It also disabled the client and AJAX validation by default. * * @access public * @param CForm|CModel $formModel * @param string $attribute * @param array $htmlOptions * @param boolean $enableAjaxValidation * @param boolean $enableClientValidation * @return string */ public function error($formModel, $attribute, $htmlOptions = array(), $enableAjaxValidation = false, $enableClientValidation = false) { if($formModel instanceof \CForm && isset($formModel->model) && $formModel->model instanceof \CModel) { $formModel = $formModel->model; } return parent::error($formModel, $attribute, $htmlOptions, $enableAjaxValidation, $enableClientValidation); } /** * Error Summary * * A wrapper for the errorSummary() method in the parent class, CActiveForm, to allow for form objects to be * passed as well as form models. * * @access public * @param CForm|CModel $formModel * @param string $header * @param string $footer * @param array $htmlOptions * @return string */ public function errorSummary($formModel, $header = null, $footer = null, $htmlOptions = array()) { if($formModel instanceof \CForm && isset($formModel->model) && $formModel->model instanceof \CModel) { $formModel = $formModel->model; } return parent::errorSummary($formModel, $header, $footer, $htmlOptions); } /** * Hint * * @access public * @param CForm $form * @param string $attribute * @param string $tag * @param array $htmlOptions * @return string */ public function hint(\CForm $form, $attribute, $tag = null, $htmlOptions = array()) { // Check that a hint exists for the form attribute specified. If one doesn't just return an empty string. // Only check the data type of the hint, and not the value. This allows for an empty string to be defined in // the form configuration to echo the hint tag (with HTML options), without the hint having any content. if(!isset($form->elements[$attribute]->hint) || !is_string($form->elements[$attribute]->hint)) { return ''; } // Return the value of the hint, wrapping in a HTML tag if specified; raw text (on its own) otherwise. return is_string($tag) ? \CHtml::tag($tag, $htmlOptions, $form->elements[$attribute]->hint) : $form->elements[$attribute]->hint; } }
zanderbaldwin/yiiskeleton
application/components/ActiveForm.php
PHP
mit
11,420
import ContactList from './ContactList' export default ContactList
iibing/chell
src/client/components/ChatPanel/ContactList/index.js
JavaScript
mit
67
from __future__ import absolute_import from collections import defaultdict as ddict import os.path as op def enum(**enums): """#enumeration #backward compatible :param enums: """ return type('Enum', (), enums) IONISATION_MODE = enum(NEG=-1, POS=1) class ExperimentalSettings(object): """ :param mz_tol_ppm: :param ionisation_mode: :param is_dims_experiment: """ ADDUCTS_POS = op.abspath("mzos/ressources/POS_ADDUCTS_IMS.csv") ADDUCTS_NEG = op.abspath("mzos/ressources/NEG_ADDUCTS_IMS.csv") FRAGMENTS = op.abspath("mzos/ressources/FRAGMENTS_IMS.csv") def __init__(self, mz_tol_ppm, polarity, is_dims_exp, frag_conf=None, neg_adducts_conf=None, pos_adducts_conf=None): self.samples = set() self.polarity = polarity # warning is an ENUM self.mz_tol_ppm = mz_tol_ppm self.is_dims_exp = is_dims_exp # self.databases = databases self.group_by_id = ddict(set) self.group_by_sample = {} # setting isos file, same for both polarity # self.isos_file = ExperimentalSettings.ISOS # setting good frags_file self.frags_file = frag_conf or ExperimentalSettings.FRAGMENTS self.adducts_file = neg_adducts_conf or ExperimentalSettings.ADDUCTS_NEG \ if polarity == IONISATION_MODE.NEG else pos_adducts_conf or ExperimentalSettings.ADDUCTS_POS def get_frags(self): """ :return: """ lines = list() with open(self.frags_file) as f: lines += [l.split(",") for l in f.readlines()[1:]] return [((float(l[3]), 1), l[0]) for l in lines] def get_adducts(self): """ :return: """ lines = list() with open(self.adducts_file) as f: lines += [l.split(",") for l in f.readlines()[1:]] return [((float(l[3]), 1), l[0]) for l in lines] def get_mass_to_check(self): """ :return: """ if self.is_dims_exp: return self.get_frags() return self.get_adducts() + self.get_frags() def create_group(self, id_, samples): """ :param id_: :param samples: :return: """ group = Group(id_, samples) for s in list(samples): self.group_by_sample[s] = group self.group_by_id[id_] = group self.samples.union(set(samples)) return group def get_group(self, id_): """ :param id_: :return: """ return self.group_by_id.get(id_) def get_group_of(self, sample): """ :param sample: :return: return group or None """ return self.group_by_sample.get(sample) def get_group_id_of(self, sample): """ :param sample: :return: """ group = self.get_group_of(sample) if group is None: return None return group.name_id class Group(list): """ :param name_id: :param samples: :param description: """ def __init__(self, name_id, samples, description=""): super(Group, self).__init__() self.samples = samples self.description = description self.name_id = name_id
jerkos/mzOS
mzos/exp_design.py
Python
mit
3,317
<?php /* 복수 인자의 사용 */ function get_two_argument($arg1, $arg2){ return $arg1 * $arg2; } print get_two_argument(1, 200); print '<br/>'; print get_two_argument(100, 200); ?>
jwlee0208/php_exercise
function/multi_argument.php
PHP
mit
186
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("05. Sorting")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("05. Sorting")] [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("d7dae97d-d34f-4676-84c5-a114850b070a")] // 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")]
StefanSinapov/TelerikAcademy
12. Data Structures & Algorithms/14. Exam/Exam/05. Sorting/Properties/AssemblyInfo.cs
C#
mit
1,398
/*global module:false*/ module.exports = function(grunt) { // Load all tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/*! <%= pkg.title || pkg.name %> - v<%= pkg.version %> - ' + '<%= pkg.homepage ? "* " + pkg.homepage : "" %>' + '* Copyright (c) <%= grunt.template.today("yyyy") %> <%= pkg.author.name %>;' + ' Licensed <%= pkg.licenses.map(function(license) { return license.type; }).join(", ") %> */' }, concat: { dist: { src: ['src/<%= pkg.name %>.js'], dest: 'dist/<%= pkg.name %>.js' } }, qunit: { files: ['test/**/*.html'] }, watch: { files: '<%= jshint.all %>', tasks: [ 'jshint', 'qunit', 'concat', 'uglify' ] }, jshint: { options: { jshintrc: '.jshintrc' }, all: ['src/**/*.js', 'test/**/*.js'] }, uglify: { options: { banner: '<%= meta.banner %>' }, dist: { src: ['<%= concat.dist.dest %>'], dest: 'dist/<%= pkg.name %>.min.js' } } }); // Register tasks grunt.registerTask('default', [ 'build' ]); grunt.registerTask('dev', [ 'build', 'watch' ]); grunt.registerTask('build', [ 'jshint', 'qunit', 'concat', 'uglify' ]); grunt.registerTask('test', [ 'jshint', 'qunit' ]); };
kadamwhite/jquery.rot13
Gruntfile.js
JavaScript
mit
1,494
import { applyMiddleware, compose } from 'redux'; import history from './history'; import { routerMiddleware } from 'react-router-redux'; import thunk from 'redux-thunk'; export default compose( applyMiddleware(thunk, routerMiddleware(history)) );
raccoon-app/ui-kit
src/front/js/store/enhancers.js
JavaScript
mit
253
#include "models/crbm/crbm.h" #include "models/crbm/layers/conv.h" #include "generator/onehut/onehut.h" #include "generator/psr/psr.h" #include "utils/putils.h" #include <stdio.h> #include <string.h> int main(int argc, char **argv) { OneHut *oh = new OneHut(21, 21, 10, 10); PSR *psr = new PSR(21, 21, 10, 10); Field *f = new Field(21, 21); srand(time(NULL)); CLayer *layer = new ConvLayer(5, 5, 5, 1, 3, 4, 1, 2); CRBM *rbm = new CRBM(); rbm->add_layer(layer); VisibleState *vs = new VisibleState(400); vs->setMask(); printf("Random sampling problem domain."); for (int i = 0; i < 10000; i++) { psr->generate(f); vs->values = f->items; printVisibleState(vs->values, 20, 20); ConvState *cs = new ConvState(20, 20, 1); memcpy(cs->values, vs->values, 20 * 20 * sizeof(int)); rbm->train(cs); } VisibleState *sample = new VisibleState(400); VisibleState *buffer = new VisibleState(400); buffer->resetMask(); buffer->values[5 * 20 + 10] = 1; buffer->values[5 * 20 + 9] = 1; buffer->values[5 * 20 + 11] = 1; buffer->values[5 * 20 + 12] = 1; buffer->mask[5 * 20 + 10] = 1; buffer->mask[5 * 20 + 9] = 1; buffer->mask[5 * 20 + 11] = 1; buffer->mask[5 * 20 + 12] = 1; printf("OBSERVED: \n"); printVisibleState(buffer->values, 20, 20); for (int i = 0; i < 2; i++) { //rbm->sample( buffer, sample ); printf("Sample: \n"); printVisibleState(sample->values, 20, 20); } }
bitesandbytes/supreme-octo-adventure
CRBMTestExperiment.cpp
C++
mit
1,469
import DateTimeCore from './DateTimeCore'; let DateTime = { mixins : [DateTimeCore], data : function () { return {}; }, methods : { _dtParseRelativeDatetimeToObj : function (val) { return this._dtcoreParseRelativeToObj('datetime', val); }, _dtIsRelativeDatetime : function (val) { return this._dtcoreIsRelative('datetime', val); }, _dtGetRelativeDatetime : function (relativeDate) { return this._dtcoreGetRelativeObj('datetime', relativeDate); } } }; export default DateTime;
Morning-UI/morning-ui
src/lib/utils/DateTime.js
JavaScript
mit
614
<?php return array( 'dbhelper/admin' => 'dbhelper/admin/index', );
OkveeNet/fuel-start
fuel/app/modules/dbhelper/config/routes.php
PHP
mit
70
<?php /** * Pages about view. * * Copyright 2016 Mammoth. All rights reserved. * See LICENCE for license details. */ ?> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script> <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script> <![endif]-->
oluijks/mammoth
app/Modules/Views/partials/ie8.blade.php
PHP
mit
313
<?php namespace Core\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\ORM\Event\LifecycleEventArgs; /** * Agenda * * @ORM\Table(name="saa.agenda") * @ORM\Entity(repositoryClass="Core\Repository\AgendaRepository") * @ORM\HasLifecycleCallbacks */ class Agenda { /** * @var integer * * @ORM\Column(name="id", type="bigint", nullable=false) * @ORM\Id * @ORM\GeneratedValue(strategy="SEQUENCE") * @ORM\SequenceGenerator(sequenceName="saa.agenda_id_seq", allocationSize=1, initialValue=1) */ private $id; /** * @var \DateTime * * @ORM\Column(name="data", type="date", nullable=false) */ private $data; /** * @var boolean * * @ORM\Column(name="fl_ocorreu", type="boolean", nullable=false) */ private $flOcorreu; /** * @var \DateTime * * @ORM\Column(name="hora_inicio", type="time", nullable=true) */ private $horaInicio; /** * @var \DateTime * * @ORM\Column(name="hora_fim", type="time", nullable=true) */ private $horaFim; /** * @var \Doctrine\Common\Collections\Collection * * @ORM\ManyToMany(targetEntity="Core\Entity\Acompanhamento", mappedBy="idAgenda") */ private $idAcompanhamento; /** * Constructor */ public function __construct() { $this->idAcompanhamento = new \Doctrine\Common\Collections\ArrayCollection(); } /** * @ORM\PostLoad */ public function postLoad( LifecycleEventArgs $event ) { $obj = $event->getObject(); if( $obj instanceof \Core\Entity\Agenda ) { $this->data = $obj->data->format( "d/m/Y" ); $this->horaInicio = $obj->horaInicio->format( "H:i" ); $this->horaFim = $obj->horaFim->format( "H:i" ); } } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set data * * @param \DateTime $data * @return Agenda */ public function setData($data) { $this->data = $data; return $this; } /** * Get data * * @return \DateTime */ public function getData() { return $this->data; } /** * Set flOcorreu * * @param boolean $flOcorreu * @return Agenda */ public function setFlOcorreu($flOcorreu) { $this->flOcorreu = $flOcorreu; return $this; } /** * Get flOcorreu * * @return boolean */ public function getFlOcorreu() { return $this->flOcorreu; } /** * Set horaInicio * * @param \DateTime $horaInicio * @return Agenda */ public function setHoraInicio($horaInicio) { $this->horaInicio = $horaInicio; return $this; } /** * Get horaInicio * * @return \DateTime */ public function getHoraInicio() { return $this->horaInicio; } /** * Set horaFim * * @param \DateTime $horaFim * @return Agenda */ public function setHoraFim($horaFim) { $this->horaFim = $horaFim; return $this; } /** * Get horaFim * * @return \DateTime */ public function getHoraFim() { return $this->horaFim; } /** * Add idAcompanhamento * * @param \Core\Entity\Acompanhamento $idAcompanhamento * @return Agenda */ public function addIdAcompanhamento(\Core\Entity\Acompanhamento $idAcompanhamento) { $this->idAcompanhamento[] = $idAcompanhamento; return $this; } /** * Remove idAcompanhamento * * @param \Core\Entity\Acompanhamento $idAcompanhamento */ public function removeIdAcompanhamento(\Core\Entity\Acompanhamento $idAcompanhamento) { $this->idAcompanhamento->removeElement($idAcompanhamento); } /** * Get idAcompanhamento * * @return \Doctrine\Common\Collections\Collection */ public function getIdAcompanhamento() { return $this->idAcompanhamento; } public function exchangeArray($data) { $this->id = (!empty($data['id'])) ? $data['id'] : null; $this->data = (!empty($data['data'])) ? \DateTime::createFromFormat('d/m/Y', $data['data']) : null; $this->flOcorreu = (!empty($data['fl_ocorreu'])) ? $data['fl_ocorreu'] : false; $this->horaInicio = (!empty($data['horaInicio'])) ? \DateTime::createFromFormat('H:i', $data['horaInicio']) : null; $this->horaFim = (!empty($data['horaFim'])) ? \DateTime::createFromFormat('H:i', $data['horaFim']) : null; } public function getArrayCopy() { return get_object_vars($this); } }
ifce-gp-20151/saa
module/Core/src/Core/Entity/Agenda.php
PHP
mit
4,827
$(document).on("ready" ,function(){ listaBrecha();// LLamar al metodo para listar las brechas //Inicio cargar combo servicio public $("#btn-NuevaBrecha").click(function()//para que cargue el como una vez echo click sino repetira datos { //alert('hola'); listaSerPubAsocCombo();//para llenar el combo de servicio publico asociado }); //fin cargar combo servicio public //AGREGAR UNA NUEVA BRECHA $("#form-addBrecha").submit(function(event) { event.preventDefault(); $.ajax({ url:base_url+"index.php/MantenimientoBrecha/AddBrecha", type:$(this).attr('method'), data:$(this).serialize(), success:function(resp){ var registros = eval(resp); for (var i = 0; i < registros.length; i++) { if(registros[i]["VALOR"]==1){ swal("",registros[i]["MENSAJE"], "success"); $('#form-addBrecha')[0].reset(); $("#VentanaRegistraBrecha").modal("hide"); }else{ swal('',registros[i]["MENSAJE"],'error' ) } /*swal("", registros[i]["MENSAJE"], "success");*/ }; $('#table-brecha').dataTable()._fnAjaxUpdate(); //SIRVE PARA REFRESCAR LA TABLA } }); }); //FIN AGREGAR UNA NUEVA BRECHA }); //-------------------------MANTENIMIENTO DE BRECHAS ---------------------------- //TRAER DATOS EN UN COMBO DE SERVICIOS PUBLICO ASOCIADO var listaSerPubAsocCombo=function(id_serv_pub_asoc) //PARA RECIR PARAMETRO PARA MANTENER VALOR DEL CAMBO { html=""; $("#cbxServPubAsoc").html(html); //nombre del selectpicker RUBRO DE EJECUCION $("#cbxSerPubAsocModificar").html(html); event.preventDefault(); $.ajax({ "url":base_url +"index.php/ServicioPublico/GetServicioAsociado", type:"POST", success:function(respuesta){ // alert(respuesta); var registros = eval(respuesta); for (var i = 0; i <registros.length;i++) { html +="<option value="+registros[i]["id_serv_pub_asoc"]+"> "+ registros[i]["nombre_serv_pub_asoc"]+" </option>"; }; $("#cbxServPubAsoc").html(html);// //MODIFICAR $("#cbxSerPubAsocModificar").html(html); $('select[name=cbxSerPubAsocModificar]').val(id_serv_pub_asoc) // VALOR DEL COMBO SELECCIONADO $('select[name=cbxSerPubAsocModificar]').change(); //FIN MODIFICAR $('.selectpicker').selectpicker('refresh'); } }); } //FIN TRAER DATOS EN UN COMBO DE RUBRO EJECUCION /*listar las brechas en el datatable*/ var listaBrecha=function() { var table=$("#table-brecha").DataTable({ "processing":true, "serverSide":false, destroy:true, "ajax":{ "url":base_url +"index.php/MantenimientoBrecha/GetBrecha", "method":"POST", "dataSrc":"" }, "columns":[ {"data":"id_brecha"}, {"data":"id_serv_pub_asoc"}, {"data":"nombre_serv_pub_asoc"}, //DATO DEL SERVICIO PUB ASOCIADO PARA ENVIAR DATO AL COMBO ACTUALIZAR Y SE MANTENGA EL VALOR {"data":"nombre_brecha"}, {"data":"descripcion_brecha"}, {"defaultContent":"<button type='button' class='editar btn btn-primary btn-xs' data-toggle='modal' data-target='#VentanaModificarBrecha'><i class='ace-icon fa fa-pencil bigger-120'></i></button><button type='button' class='eliminar btn btn-danger btn-xs' data-toggle='modal' data-target='#'><i class='fa fa-trash-o'></i></button>"} ], "language":idioma_espanol }); BrechaData("#table-brecha",table); //TRAER LA DATA DE LAS BRECHAS PARA ACTUALIZAR EliminarBrechaLista("#table-brecha",table);//TRAER LA DATA DE LAS BRECHAS PARA ELIMINAR } /*fin de listar las brechas en el datatable*/ //ACTUALIZAR UNA BRECHA $("#form-ActualizarBrecha").submit(function(event) { event.preventDefault(); $.ajax({ url:base_url+"index.php/MantenimientoBrecha/UpdateBrecha", type:$(this).attr('method'), data:$(this).serialize(), success:function(resp){ swal("ACTUALIZADO!", resp, "success"); $('#table-brecha').dataTable()._fnAjaxUpdate(); } }); }); //FIN ACTUALIZAR UNA BRECHA // CAMPOS QUE SE ACTUALIZARAN DE LAS BRECHAS var BrechaData=function(tbody,table){ $(tbody).on("click","button.editar",function(){ var data=table.row( $(this).parents("tr")).data(); var id_brecha=$('#txt_IdBrechaModif').val(data.id_brecha); var id_serv_pub_asoc=data.id_serv_pub_asoc; var nombre_brecha=$('#txt_NombreBrechaU').val(data.nombre_brecha); var descripcion_brecha=$('#txtArea_DescBrechaU').val(data.descripcion_brecha); listaSerPubAsocCombo(id_serv_pub_asoc);//llamar al evento de combo box para actualizar }); } // FIN DE CAMPOS QUE SE ACTUALIZARAN DE LAS BRECHAS //ELIMINAR UNA BRECHA var EliminarBrechaLista=function(tbody,table){ $(tbody).on("click","button.eliminar",function(){ var data=table.row( $(this).parents("tr")).data(); var id_brecha=data.id_brecha; swal({ title: "Esta seguro que desea eliminar la brecha?", text: "", type: "warning", showCancelButton: true, confirmButtonColor: "#DD6B55", confirmButtonText: "SI,ELIMINAR", closeOnConfirm: false }, function(){ $.ajax({ url:base_url+"index.php/MantenimientoBrecha/DeleteBrecha", type:"POST", data:{id_brecha:id_brecha}, success:function(respuesta) { swal("ELIMINADO!", "Se elimino correctamente la brecha.", "success"); $('#table-brecha').dataTable()._fnAjaxUpdate(); }//para actualizar mi datatablet datatablet }); }); }); } //FIN ELIMINAR UNA BRECHA /* //Manda datos en consola de la tabla brecha function lista() { event.preventDefault(); $.ajax({ "url":base_url +"index.php/MantenimientoBrecha/GetBrecha", type:"POST", success:function(respuesta) { console.log(respuesta); } }); } *///fin datos en consola de la tabla brecha //-------------------------FIN MANTENIMIENTO DE BRECHAS ----------------------------
smptracing/SMP
assets/js/administrador/MBrecha.js
JavaScript
mit
8,825
<?php /** * PluginSetting form. * * @package runforever * @subpackage form * @author Your name here * @version SVN: $Id: PluginSettingForm.class.php 28974 2010-04-04 22:59:54Z Kris.Wallsmith $ */ abstract class PluginSettingForm extends BaseSettingForm { }
jtarleton/runforever-www
lib/plugins/sfDoctrinePlugin/test/functional/fixtures/plugins/SettingsPlugin/lib/form/doctrine/PluginSettingForm.class.php
PHP
mit
275
using System; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Net; using Vita.Entities; using BookStore; using BookStore.Api; using System.Threading.Tasks; using Vita.Tools.Testing; using Arrest; using Arrest.Sync; namespace Vita.Testing.WebTests { public partial class BooksApiTests { // Tests special methods in controller [TestMethod] public void TestSpecialMethods() { var client = Startup.Client; Logout(); // just in case there's still session there from other tests //Test values handling in URL var gd = new Guid("729C7EA4-F3C5-11E4-88C8-F0DEF1783701"); var foo = client.Get<string>("api/special/foo/{0}/{1}", 1, gd); //foo/(int)/(guid) Assert.AreEqual("Foo:1," + gd, foo); // 'bars' method requires login var exc = TestUtil.ExpectFailWith<RestException>(() => client.Get<string>("api/special/bars?q=Q")); Assert.AreEqual(HttpStatusCode.Unauthorized, exc.Status, "Expected Unauthorized"); LoginAs("Dora"); var bars = client.Get<string>("api/special/bars?q=Q"); Assert.AreEqual("bars:Q", bars); Logout(); // Call getBook with bad book id - will return NotFound custom code - // it is done on purpose by controller, instead of simply returning null var apiExc = TestUtil.ExpectFailWith<RestException>(() => client.Get<Book>("api/special/books/{0}", Guid.NewGuid())); Assert.AreEqual(HttpStatusCode.NotFound, apiExc.Status, "Expected NotFound status"); //Test redirect; when we create WebApiClient in SetupHelper, we set: Client.InnerHandler.AllowRedirect = false; so it will bring error on redirect apiExc = TestUtil.ExpectFailWith<RestException>(() => client.Get<HttpStatusCode>("api/special/redirect")); Assert.AreEqual(HttpStatusCode.Redirect, apiExc.Status, "Expected redirect status"); } [TestMethod] public void TestDiagnosticsController() { var client = Startup.Client; var acceptText = "application/text,text/plain"; //Heartbeat DiagnosticsController.Reset(); var serverStatus = client.GetString("api/diagnostics/heartbeat", null, acceptText); Assert.AreEqual("StatusOK", serverStatus, "Expected StatusOK in heartbeat"); // throw error DiagnosticsController.Reset(); var exc = TestUtil.ExpectFailWith<Exception>(() => client.GetString("api/diagnostics/throwerror", null, acceptText)); Assert.IsTrue(exc.Message.Contains("TestException"), "Expected TestException thrown"); //get/set time offset // current should be zero var currOffset = client.GetString("api/diagnostics/timeoffset", null, acceptText); Assert.IsTrue(currOffset.StartsWith("Current offset: 0 minutes"), "Expected no offset"); // set 60 minutes forward currOffset = client.GetString("api/diagnostics/timeoffset/60", null, acceptText); Assert.IsTrue(currOffset.StartsWith("Current offset: 60 minutes"), "Expected 60 minutes offset"); // set back to 0 currOffset = client.GetString("api/diagnostics/timeoffset/0", null, acceptText); Assert.IsTrue(currOffset.StartsWith("Current offset: 0 minutes"), "Expected no offset"); /* //test that heartbeat call is not logged in web log - controller method sets log level to None var serverSession = TestStartup.BooksApp.OpenSession(); // fix this var hbeatEntry = serverSession.EntitySet<IWebCallLog>().Where(wl => wl.Url.Contains("heartbeat")).FirstOrDefault(); Assert.IsNull(hbeatEntry, "Expected no heartbeat entry in web log."); */ } // Tests KeepOpen connection mode (default for web controllers). In this mode, the connection to database is kept alive in entity session between db calls, // to avoid extra work on acquiring connection from pool, and on making 'reset connection' roundtrip to db (done by connection pool when it gives connection from the pool) // Web call is usually very quick, so it's reasonable to hold on to open connection until the end. If the connection is not closed explicitly // by controller method, it is closed automatically by Web call handler (conn is registered in OperationContext.Disposables). // The following test verifies this behavior. We make a test call which executes a simple query to database, // then checks that connection is still alive and open (saved in session.CurrentConnection). // Then it sets up an event handler that would register the conn.Close call (conn.StateChanged event) which will happen when Web call completes; // the handler saves a 'report' in a static field in controller. // We then retrieve this report thru second call and verify that connection was in fact closed properly. [TestMethod] public void TestDbConnectionHandling() { var client = Startup.Client; var ok = client.Get<string>("api/special/connectiontest"); Assert.AreEqual("OK", ok, "Connection test did not return OK"); //get report var report = client.Get<string>("api/special/connectiontestreport"); // values: State is closed, DataConnection.Close was called, WebCallContextHandler.PostProcessResponse was called Assert.AreEqual("True,True,True", report, "Connection report does not match expected value"); } }//class }
rivantsov/vita
src/6.UnitTests/Vita.Testing.WebTests/BooksApiTests_SpecialCases.cs
C#
mit
5,352
<?php namespace Servinow\EntitiesBundle; use Symfony\Component\HttpKernel\Bundle\Bundle; class ServinowEntitiesBundle extends Bundle { }
Servinow/servinowServer
src/Servinow/EntitiesBundle/ServinowEntitiesBundle.php
PHP
mit
140
package com.ucloud.ulive.example.utils; import android.util.Log; import static android.content.ContentValues.TAG; public class AverageAudioMixer { public byte[] scale(byte[] orignBuff, int size, float volumeScale) { for (int i = 0; i < size; i += 2) { short origin = (short) (((orignBuff[i + 1] << 8) | orignBuff[i] & 0xff)); origin = (short) (origin * volumeScale); orignBuff[i + 1] = (byte) (origin >> 8); orignBuff[i] = (byte) (origin); } return orignBuff; } public byte[] mixRawAudioBytes(byte[][] bMulRoadAudioes) { if (bMulRoadAudioes == null || bMulRoadAudioes.length == 0) { return null; } byte[] realMixAudio = bMulRoadAudioes[0]; if (bMulRoadAudioes.length == 1) { return realMixAudio; } for (int rw = 0; rw < bMulRoadAudioes.length; ++rw) { if (bMulRoadAudioes[rw].length != realMixAudio.length) { Log.e(TAG, "lifecycle->demo->AverageAudioMixer->column of the road of audio + " + rw + " is diffrent!"); return null; } } int row = bMulRoadAudioes.length; int column = realMixAudio.length / 2; short[][] sMulRoadAudioes = new short[row][column]; for (int r = 0; r < row; ++r) { for (int c = 0; c < column; ++c) { sMulRoadAudioes[r][c] = (short) ((bMulRoadAudioes[r][c * 2] & 0xff) | (bMulRoadAudioes[r][c * 2 + 1] & 0xff) << 8); } } short[] sMixAudio = new short[column]; int mixVal; int sr; for (int sc = 0; sc < column; ++sc) { mixVal = 0; sr = 0; for (; sr < row; ++sr) { mixVal += sMulRoadAudioes[sr][sc]; } sMixAudio[sc] = (short) (mixVal / row); } for (sr = 0; sr < column; ++sr) { realMixAudio[sr * 2] = (byte) (sMixAudio[sr] & 0x00FF); realMixAudio[sr * 2 + 1] = (byte) ((sMixAudio[sr] & 0xFF00) >> 8); } return realMixAudio; } }
umdk/UCDLive_Android
ulive-demo/src/main/java/com/ucloud/ulive/example/utils/AverageAudioMixer.java
Java
mit
2,131
<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?> <div class="container-fluid"> <div class="row"> <?php $this->load->view('templates/toolbars/computing-support/disposals.php'); ?> <div class="col-lg-12"> <h1 class="page-header">Disposals</h1> <p>Device added to disposals.</p> <meta http-equiv="refresh" content="1; URL='/dashboard/computing-support/disposals/current'" /> <i class="fa fa-circle-o-notch fa-spin" aria-hidden="true"></i> Redirecting... </div> <!-- END col-lg-12 --> </div> <!-- END row --> </div> <!-- END container-fluid -->
East-Kent-Partnership/Intranet
dashboard/application/views/computing-support/disposals/created.php
PHP
mit
647
if (!com) var com = {} if (!com.corejsf) { com.corejsf = { showProgress: function(data) { var inputId = data.source.id var progressbarId = inputId.substring(0, inputId.length - "name".length) + "pole"; if (data.status == "begin") Element.show(progressbarId); else if (data.status == "success") Element.hide(progressbarId); } } }
thescouser89/snippets
jsf/javaee/ch10/requestMonitor/web/resources/javascript/login.js
JavaScript
mit
420
package edu.byu.cs.vv.Parser; import edu.byu.cs.vv.Syntax.Operations.Operation; import edu.byu.cs.vv.Syntax.Operations.Receive; import edu.byu.cs.vv.Syntax.Operations.Send; import edu.byu.cs.vv.Syntax.Program; import org.antlr.v4.runtime.tree.ErrorNode; import java.lang.*; import java.util.HashMap; import java.util.Map; public class ProgramListener extends edu.byu.cs.vv.Parser.CTPParserBaseListener { @Override public void visitErrorNode(ErrorNode node) { System.out.println("Error in syntax: " + node.toString()); throw new RuntimeException("Error in syntax: " + node.toString()); } private ProgramBuilder programBuilder; private ProcessBuilder processBuilder; private Map<Integer, Integer> sends; private int recv_rank; public Program getProgram() { return programBuilder.finish(); } @Override public void enterProgram(edu.byu.cs.vv.Parser.CTPParser.ProgramContext ctx) { programBuilder = new ProgramBuilder(); super.enterProgram(ctx); } @Override public void enterThread(edu.byu.cs.vv.Parser.CTPParser.ThreadContext ctx) { processBuilder = new ProcessBuilder(); processBuilder.setRank(programBuilder.size()); sends = new HashMap<>(); recv_rank = 0; super.enterThread(ctx); } @Override public void enterThreadHeader(edu.byu.cs.vv.Parser.CTPParser.ThreadHeaderContext ctx) { processBuilder.setName(ctx.children.get(1).getText()); super.enterThreadHeader(ctx); } @Override public void exitThread(edu.byu.cs.vv.Parser.CTPParser.ThreadContext ctx) { programBuilder.addProcess(processBuilder.finish()); super.exitThread(ctx); } // NOTE: This ignores the destination specified in the dsl for the receive, and assumes that the receive // endpoint is the thread it is declared within. @Override public void enterReceive(edu.byu.cs.vv.Parser.CTPParser.ReceiveContext ctx) { int source = Integer.parseInt(ctx.children.get(1).getText()); Operation op = new Receive( processBuilder.rank() + "_" + processBuilder.size(), // Name processBuilder.rank(), // Process Rank recv_rank, // Operation Rank source, // Source processBuilder.rank(), // Destination null, // Matching Send null, // Nearest wait true, // Blocking? (source == -1)); // Wildcard? processBuilder.addOperation(op); recv_rank++; super.enterReceive(ctx); } @Override public void enterSend(edu.byu.cs.vv.Parser.CTPParser.SendContext ctx) { int rank, destination = Integer.parseInt(ctx.children.get(1).getText()); if (sends.containsKey(destination)) { rank = sends.get(destination); } else { rank = 0; } Operation op = new Send( processBuilder.rank() + "_" + processBuilder.size(), // Name processBuilder.rank(), // Process Rank rank, // Operation rank processBuilder.rank(), // Source destination, // Destination null, // Matching receive Integer.parseInt(ctx.children.get(2).getText()), // Value true, // Blocking? null); // Nearest wait processBuilder.addOperation(op); sends.put(destination, rank + 1); super.enterSend(ctx); } }
byu-vv-lab/mercury
src/main/java/edu/byu/cs/vv/Parser/ProgramListener.java
Java
mit
4,182
# This migration comes from facebase (originally 20120329182316) class CreateFacebaseStreams < ActiveRecord::Migration def change create_table :facebase_streams do |t| t.string :name t.integer :campaign_id t.timestamps end end end
leetpcuser/facebase
test/dummy/db/migrate/20120331041868_create_facebase_streams.facebase.rb
Ruby
mit
262
class DbUtil def getCodeFormat(code) if (code.instance_of? String) return validateCode(code) else return validateCode(code.to_i.to_s) end end def getIdDb(name, code) return MdDb::RunDB.select(name, 'id', "code = decode('#{code}', 'hex')") end def validateCode(code) if (code.length == 1) return "000".concat(code) elsif (code.length == 2) return "00".concat(code) elsif (code.length == 3) return "0".concat(code) else return code end end end
EnglishLesson/dc_procxls
db/dbutil.rb
Ruby
mit
552
(function () { 'use strict'; angular.module('UserSearch') .controller('UserSearchController', ['searchService', UserSearchController]); function UserSearchController(searchService) { var self = this; self.user = {}; self.searchFilter = ''; self.showSpinner = true; init(); function init() { return searchService.getAllUserData().then(function (response) { if (response.data !== null) { self.userData = response; self.getUserDetails(0); self.showSpinner = false; } else { self.error = "Oops. Looks like we hit a snag, try reloading."; self.showSpinner = false; } }); } self.getUserDetails = function (index) { if (self.userData[index]) { self.user = self.userData[index]; } }; } })();
JeremyCarlsten/userSearchChallenge
app/app.js
JavaScript
mit
998
package jpasearch.repository.query; public enum OrderByDirection { ASC, DESC; }
jpasearch/jpasearch
src/main/java/jpasearch/repository/query/OrderByDirection.java
Java
mit
85
package src.enigma.calin.armor; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.Item; /** * Created by Calin on 8/17/2015. */ public class ArmorJihadVest extends Item { public ArmorJihadVest() { setCreativeTab(CreativeTabs.tabCombat); setNoRepair(); this.maxStackSize = 1; } }
GamrCorps/Mod
src/main/java/src/enigma/calin/armor/ArmorJihadVest.java
Java
mit
344
require 'httparty' require 'builder' module Kivot class PivotalPoster def initialize(token, project_id) @token = token @project_id = project_id end def post_story(name, args={}) headers = { 'X-TrackerToken' => @token, 'Content-Type' => 'text/xml' } body = Builder::XmlMarkup.new.story do |s| s.name name s.description(args[:description]) if args[:description] s.owned_by(args[:owner]) if args[:owner] s.requested_by(args[:requester]) if args[:requester] end HTTParty.post(story_path, :headers => headers, :body => body) end private def story_path "http://www.pivotaltracker.com/services/v3/projects/#{@project_id}/stories" end end end
phildarnowsky/kivot
lib/kivot/pivotal_poster.rb
Ruby
mit
772
#include "XantoI2C.h" XantoI2C::XantoI2C(uint8_t clock_pin, uint8_t data_pin, uint16_t delay_time_us): clock_pin(clock_pin), data_pin(data_pin), delay_time_us(delay_time_us) { sdaHi(); sclHi(); } void XantoI2C::i2cDelay() { delayMicroseconds(delay_time_us); } void XantoI2C::sclHi() { pinMode(clock_pin, INPUT_PULLUP); i2cDelay(); } void XantoI2C::sdaHi() { pinMode(data_pin, INPUT_PULLUP); i2cDelay(); } void XantoI2C::sclLo() { digitalWrite(clock_pin, LOW); pinMode(clock_pin, OUTPUT); i2cDelay(); } void XantoI2C::sdaLo() { digitalWrite(data_pin, LOW); pinMode(data_pin, OUTPUT); i2cDelay(); } void XantoI2C::start() { sdaHi(); sclHi(); i2cDelay(); sdaLo(); i2cDelay(); sclLo(); i2cDelay(); } void XantoI2C::stop() { sdaLo(); i2cDelay(); sclHi(); i2cDelay(); sdaHi(); i2cDelay(); } void XantoI2C::clockPulse() { sclHi(); i2cDelay(); sclLo(); } void XantoI2C::writeByte(uint8_t data_byte) { for (uint8_t i = 0; i < 8; i++) { if (bitRead(data_byte, 7 - i)) { sdaHi(); } else { sdaLo(); } clockPulse(); } } uint8_t XantoI2C::readBit() { uint8_t out_bit; sclHi(); out_bit = digitalRead(data_pin); sclLo(); return out_bit; } uint8_t XantoI2C::readByte() { uint8_t out_byte = 0; sdaHi(); for (uint8_t i = 0; i < 8; i++) { bitWrite(out_byte, 7 - i, readBit()); } return out_byte; } /** * Return 0 if ACK was received, else 1 */ uint8_t XantoI2C::readAck() { sdaHi(); return readBit() == 0 ? 0 : 1; } /** * Return 0 if NACK was received, else 1 */ uint8_t XantoI2C::readNack() { sdaHi(); return readBit() == 1 ? 0 : 1; } /** * Return 0 if all steps were executed, else 1 */ uint8_t XantoI2C::doStartWriteAckStop(uint8_t data_byte) { start(); writeByte(data_byte); if (readAck()) { return 1; } stop(); return 0; } /** * Return 0 if all steps were executed, else 1 */ uint8_t XantoI2C::doStartWriteAckStop(uint8_t data_bytes[], uint8_t data_length) { start(); for (uint8_t i = 0; i < data_length; i++) { writeByte(data_bytes[i]); if (readAck()) { return 1; } } stop(); return 0; }
xantorohara/XantoI2C
XantoI2C.cpp
C++
mit
2,172
package org.superboot.utils; import javax.servlet.http.HttpServletRequest; /** * <b> IP校验 </b> * <p> * 功能描述: * </p> */ public class IPUtils { public static String getClientAddress(HttpServletRequest request) { if (request == null) { return "unknown"; } String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Forwarded-For"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("X-Real-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); } return ip; } }
7040210/SuperBoot
super-boot-utils/src/main/java/org/superboot/utils/IPUtils.java
Java
mit
1,101
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="TaskShim.cs" company="Catel development team"> // Copyright (c) 2008 - 2015 Catel development team. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- #if NET40 || SL5 #define USE_TASKEX #endif namespace Catel.Threading { using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; #if USE_TASKEX using Microsoft.Runtime.CompilerServices; #else using System.Runtime.CompilerServices; #endif /// <summary> /// Task wrapper so it works on all platforms. /// </summary> /// <remarks>This code originally comes from https://github.com/StephenCleary/AsyncEx/blob/77b9711c2c5fd4ca28b220ce4c93d209eeca2b4a/Source/Unit%20Tests/Tests%20(NET40)/Internal/TaskShim.cs.</remarks> public static class TaskShim { /// <summary> /// Creates a task that will complete after a time delay. /// </summary> /// <param name="millisecondsDelay">The number of milliseconds to wait before completing the returned task</param> /// <returns>A task that represents the time delay</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="millisecondsDelay" /> is less than -1.</exception> public static Task Delay(int millisecondsDelay) { #if USE_TASKEX return TaskEx.Delay(millisecondsDelay); #else return Task.Delay(millisecondsDelay); #endif } /// <summary> /// Creates a task that will complete after a time delay. /// </summary> /// <param name="millisecondsDelay">The number of milliseconds to wait before completing the returned task</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents the time delay</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="millisecondsDelay" /> is less than -1.</exception> public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Delay(millisecondsDelay, cancellationToken); #else return Task.Delay(millisecondsDelay, cancellationToken); #endif } /// <summary> /// Starts a Task that will complete after the specified due time. /// </summary> /// <param name="dueTime">The delay before the returned task completes.</param> /// <returns>The timed Task.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="dueTime" /> argument must be non-negative or -1 and less than or equal to Int32.MaxValue.</exception> public static Task Delay(TimeSpan dueTime) { #if USE_TASKEX return TaskEx.Delay(dueTime); #else return Task.Delay(dueTime); #endif } /// <summary> /// Starts a Task that will complete after the specified due time. /// </summary> /// <param name="dueTime">The delay before the returned task completes.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The timed Task.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException">The <paramref name="dueTime" /> argument must be non-negative or -1 and less than or equal to Int32.MaxValue.</exception> public static Task Delay(TimeSpan dueTime, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Delay(dueTime, cancellationToken); #else return Task.Delay(dueTime, cancellationToken); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a task handle for that work. /// </summary> /// <param name="action">The work to execute asynchronously.</param> /// <returns>A task that represents the work queued to execute in the ThreadPool.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="action" /> parameter was null.</exception> public static Task Run(Action action) { #if USE_TASKEX return TaskEx.Run(action); #else return Task.Run(action); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a task handle for that work. /// </summary> /// <param name="action">The work to execute asynchronously.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents the work queued to execute in the ThreadPool.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="action" /> parameter was null.</exception> public static Task Run(Action action, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Run(action, cancellationToken); #else return Task.Run(action); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by <paramref name="function" />. /// </summary> /// <param name="function">The work to execute asynchronously.</param> /// <returns>A task that represents a proxy for the task returned by <paramref name="function" />.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task Run(Func<Task> function) { #if USE_TASKEX return TaskEx.Run(function); #else return Task.Run(function); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a proxy for the task returned by <paramref name="function" />. /// </summary> /// <param name="function">The work to execute asynchronously.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A task that represents a proxy for the task returned by <paramref name="function" />.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task Run(Func<Task> function, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Run(function, cancellationToken); #else return Task.Run(function, cancellationToken); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work. /// </summary> /// <typeparam name="TResult">The result type of the task.</typeparam> /// <param name="function">The work to execute asynchronously.</param> /// <returns>A Task(TResult) that represents the work queued to execute in the ThreadPool.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task<TResult> Run<TResult>(Func<TResult> function) { #if USE_TASKEX return TaskEx.Run(function); #else return Task.Run(function); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a Task(TResult) handle for that work. /// </summary> /// <typeparam name="TResult">The result type of the task.</typeparam> /// <param name="function">The work to execute asynchronously.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task(TResult) that represents the work queued to execute in the ThreadPool.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task<TResult> Run<TResult>(Func<TResult> function, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Run(function, cancellationToken); #else return Task.Run(function, cancellationToken); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a proxy for the Task(TResult) returned by <paramref name="function" />. /// </summary> /// <typeparam name="TResult">The type of the result returned by the proxy task.</typeparam> /// <param name="function">The work to execute asynchronously</param> /// <returns>A Task(TResult) that represents a proxy for the Task(TResult) returned by <paramref name="function" />.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task<TResult> Run<TResult>(Func<Task<TResult>> function) { #if USE_TASKEX return TaskEx.Run(function); #else return Task.Run(function); #endif } /// <summary> /// Queues the specified work to run on the ThreadPool and returns a proxy for the Task(TResult) returned by <paramref name="function" />. /// </summary> /// <typeparam name="TResult">The type of the result returned by the proxy task.</typeparam> /// <param name="function">The work to execute asynchronously</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>A Task(TResult) that represents a proxy for the Task(TResult) returned by <paramref name="function" />.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="function" /> parameter was null.</exception> public static Task<TResult> Run<TResult>(Func<Task<TResult>> function, CancellationToken cancellationToken) { #if USE_TASKEX return TaskEx.Run(function, cancellationToken); #else return Task.Run(function, cancellationToken); #endif } /// <summary> /// Creates a <see cref="T:System.Threading.Tasks.Task`1" /> that's completed successfully with the specified result. /// </summary> /// <typeparam name="TResult">The type of the result returned by the task.</typeparam> /// <param name="result">The result to store into the completed task.</param> /// <returns>The successfully completed task.</returns> public static Task<TResult> FromResult<TResult>(TResult result) { #if USE_TASKEX return TaskEx.FromResult(result); #else return Task.FromResult(result); #endif } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <typeparam name="TResult">The type of the completed task.</typeparam> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> collection contained a null task.</exception> public static Task<TResult[]> WhenAll<TResult>(IEnumerable<Task<TResult>> tasks) { #if USE_TASKEX return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <typeparam name="TResult">The type of the completed task.</typeparam> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task.</exception> public static Task<TResult[]> WhenAll<TResult>(params Task<TResult>[] tasks) { #if USE_TASKEX return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> collection contained a null task.</exception> public static Task WhenAll(IEnumerable<Task> tasks) { #if USE_TASKEX return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } /// <summary> /// Creates a task that will complete when all of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of all of the supplied tasks.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task.</exception> public static Task WhenAll(params Task[] tasks) { #if USE_TASKEX return TaskEx.WhenAll(tasks); #else return Task.WhenAll(tasks); #endif } /// <summary> /// Creates an awaitable task that asynchronously yields back to the current context when awaited. /// </summary> /// <returns>A context that, when awaited, will asynchronously transition back into the current context at the time of the await. If the current <see cref="T:System.Threading.SynchronizationContext" /> is non-null, it is treated as the current context. Otherwise, the task scheduler that is associated with the currently executing task is treated as the current context.</returns> public static YieldAwaitable Yield() { #if USE_TASKEX return TaskEx.Yield(); #else return Task.Yield(); #endif } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task, or was empty.</exception> public static Task<Task> WhenAny(params Task[] tasks) { #if USE_TASKEX return TaskEx.WhenAny(tasks); #else return Task.WhenAny(tasks); #endif } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task, or was empty.</exception> public static Task<Task> WhenAny(IEnumerable<Task> tasks) { #if USE_TASKEX return TaskEx.WhenAny(tasks); #else return Task.WhenAny(tasks); #endif } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <typeparam name="TResult">The type of the completed task.</typeparam> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task, or was empty.</exception> public static Task<Task<TResult>> WhenAny<TResult>(params Task<TResult>[] tasks) { #if USE_TASKEX return TaskEx.WhenAny(tasks); #else return Task.WhenAny(tasks); #endif } /// <summary> /// Creates a task that will complete when any of the supplied tasks have completed. /// </summary> /// <typeparam name="TResult">The type of the completed task.</typeparam> /// <param name="tasks">The tasks to wait on for completion.</param> /// <returns>A task that represents the completion of one of the supplied tasks. The return task's Result is the task that completed.</returns> /// <exception cref="T:System.ArgumentNullException">The <paramref name="tasks" /> argument was null.</exception> /// <exception cref="T:System.ArgumentException">The <paramref name="tasks" /> array contained a null task, or was empty.</exception> public static Task<Task<TResult>> WhenAny<TResult>(IEnumerable<Task<TResult>> tasks) { #if USE_TASKEX return TaskEx.WhenAny(tasks); #else return Task.WhenAny(tasks); #endif } } }
blebougge/Catel
src/Catel.Core/Catel.Core.Shared/Threading/Helpers/TaskShim.cs
C#
mit
18,388
/* @Author: John McCain * @Date: 11-30-15 * @Version 1.0 * @Description: Records an audio stream in one hour increments. Labels files. * Note: lines that need to be modified are marked */ import java.net.URLConnection; import java.net.URL; import java.io.InputStream; import java.io.OutputStream; import java.io.FileOutputStream; import java.io.File; import java.util.Date; import java.text.DateFormat; import java.text.SimpleDateFormat; public class StreamRipper { static boolean firstHour; static DateFormat dateFormat = new SimpleDateFormat("MM-dd-yy HHmm"); static DateFormat topOfHourFormat = new SimpleDateFormat("mm"); public static void main(String[] args) { final long MINUTE_IN_MS = 1000 * 60 * 60; boolean errorOccurred = false; Date errorDate = new Date(); while(true) //Master while loop, should only loop if there is an error { System.out.println("Starting the Stream Ripper..."); //Used to cut first export file short as to start on hour firstHour = true; if(errorOccurred) { Date compareDate = new Date(System.currentTimeMillis()-5*MINUTE_IN_MS); if(errorDate.compareTo(compareDate)>=0) { Date nowDate = new Date(); System.out.println("An error occurred! This has happened recently, Stream Rip will wait 5 minutes before trying again. TIME: " + dateFormat.format(nowDate)); try { Thread.sleep(1000*60*5); } catch(Exception e) { e.printStackTrace(); } } else { System.out.println("An error occurred! We still gucci tho"); } errorDate = new Date(); errorOccurred = false; } try { Thread.currentThread().setPriority(Thread.MAX_PRIORITY-3); //Sets priority to just below the maximum (Maximum is real time, which would be bad and starve everything else) (Java priority values range from 1 to 10) //Connects to the stream /********* PUT FULL URL OF DESIRED STREAM HERE *********/ URLConnection myConnection = new URL("YOUR_STREAM_URL_HERE").openConnection(); //Creates input stream to process the stream InputStream instream = myConnection.getInputStream(); while(true) { //Get current date/time for timestamp in filename Date date = new Date(); //Set output filename /********* CHANGE .mp3 TO DESIRED FILE FORMAT IF NECESSARY *********/ String filename = "STRM" + dateFormat.format(date) + ".mp3"; /********* PUT TARGET DIRECTORY HERE *********/ //Note: format like so: "C:/SomeDirectory/Stream Rip/" //This directory must already exist String filepath = "YOUR_DIRECTORY_HERE" + filename; //Creates output steam to export the stream to an mp3 file OutputStream outstream = new FileOutputStream(new File(filepath)); //Buffer byte[] buffer = new byte[16384]; //Stores length of the buffer in bytes int len; //Iterator to limit length of the exported file in bytes. long t = 0; //Make sure the buffer isn't empty while(!(instream.read(buffer)>0)) { //Chill } Thread.sleep(10); //Writes the buffer to the output file when the buffer size is>0 and the length of the output file is < the specified limit and it is not both the top of the hour and the first export file in this succesful run //Note: To calculate bit limit from time, take 128kbps/8bpB to get the number of Bytes per second. Multiply by the number of seconds desired. 57600000 is one hour. while (((len = instream.read(buffer)) > 0 && ((t+=len)<57600000)) && !(firstHour && isOnHour())) { Thread.sleep(10); outstream.write(buffer, 0, len); } outstream.close(); System.out.println("Just exported a file. It is " + t + " bytes and the file name is " + filename); } } catch(Exception e) { e.printStackTrace(); errorOccurred = true; } } } //Pre: topOfHourFormat is a SimpleDateFormat of style "mm", firstHour is a declared boolean //Post: firstHour is set to false if it is the top of the hour //Returns: boolean, true if it is the top of the hour, false if it is not static boolean isOnHour() { Date currentTime = new Date(); if(topOfHourFormat.format(currentTime).equals("00")) { firstHour = false; System.out.println("Exporting a file early in order to start on the hour"); return true; } return false; } }
kjhkit/Public-Stream-Rip
StreamRipper.java
Java
mit
4,459
<?php namespace app\controllers; use common\components\XwcController; use common\models\AuthAssignment; use common\models\Api; use common\models\ProjectSearch; use common\components\CTools; use yii\base\ErrorException; use yii\base\Exception; use Yii; use yii\data\Pagination; use yii\web\ForbiddenHttpException; class ApiController extends XwcController { public $topMenu = 'api'; public $id_or_name; public static function controllerName() { return '接口管理'; } public function actionIndex() { } /** * 列表 * * @return string */ public function actionList(){ $searchParams = Yii::$app->request->get('search'); $model = new Api(); $query = $model->find(); #过滤 if (!empty($searchParams)) { foreach ($searchParams as $key => $value) { if($key != 'fuzzy_param'){ $query->andFilterWhere(['=', $key, $value]); }else{ $query->andwhere([ 'or', ['like','id', $value], ['like','name', $value], ['like','file_name', $value], ['like','remark', $value], ]); } } } $perPage = Yii::$app->request->get('per-page'); $perPage = $perPage ? $perPage : 10; $totalCount = $query->count(); $pages = new Pagination(['totalCount' => $totalCount]); $pages->setPageSize($perPage); $page = Yii::$app->request->get('page'); $page = $page ? $page : 1; $list= $query->orderBy(['id'=> SORT_DESC]) ->offset($pages->offset) ->limit($pages->limit) ->all(); return $this->render('list', [ 'model' => $model, 'list' => $list, 'pages' => $pages, 'page' => $page, 'searchParams' => $searchParams, 'attributes' => $model->attributeLabels(), ]); } /** * 重置搜索列表 * * @return string */ public function actionClearSearch(){ $model = new Api(); $searchParams = $model; $query = $model->find(); $pages = new Pagination(['totalCount' => $query->count()]); $pages->setPageSize(10); $list= $query->orderBy(['id'=> SORT_DESC]) ->offset($pages->offset) ->limit($pages->limit) ->asArray()->all(); return $this->render('list', [ 'model' => $model, 'list' => $list, 'pages' => $pages, 'searchParams' => $searchParams, 'attributes' => $model->attributeLabels(), ]); } /** * 添加 * * @return string */ public function actionAdd(){ $model = new Api(); $model->setDefaultValues(); $models = Api::find()->all(); $model_indexs = []; $model_o_indexs = []; $index = 1; foreach($models as $o){ $model_indexs[$index] = $o->name.' ('.$o->file_name.')'; $model_o_indexs[$index] = $o; $index = $index + 1; } $select_model = $model; $temple_select = Yii::$app->request->post('temple_select'); if($temple_select){ $select_model = $model_o_indexs[$temple_select]; } return $this->render('add', [ 'model' => $model, 'models' => $models, 'select_model' => $select_model, 'model_indexs' => $model_indexs, 'temple_select' => $temple_select, 'attributes' => $model->attributeLabels(), ]); } public function actionTest(){ return $this->render('test'); } /** * 编辑 * * @return string */ public function actionEdit($id=1){ $id = empty($id) ? Yii::$app->request->post('id') :$id ; $model = Api::findOne($id); $post = Yii::$app->request->post(); if(!empty($post)){ try{ if($model->load($post) && $model->save()){ Yii::$app->getSession()->setFlash('success', '保存成功'); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/list'])); }else{ #抛出异常 throw new Exception (CTools::recursiveMultiArray($model->errors)); } }catch (Exception $e){ #捕获抛出的异�? Yii::$app->getSession()->setFlash('error', $e->getMessage()); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/edit','id' => $id])); } } return $this->render('add', [ 'model' => $model, 'select_model' => $model, 'attributes' => $model->attributeLabels(), ]); } /** * save a record. * * @return */ public function actionSave() { $post = Yii::$app->request->post(); if(!empty($post)){ try{ // if (null != Api::findOne(['s_id' =>$post['Api']['id']])){ // throw new Exception ("任务已存在"); // } $model = new Api(); if($model->load($post)){ $model->content_text = CTools::translateRichToText(strip_tags($model->content)); $model->url = \Yii::$app->request->hostInfo.'/'.$model->getFilePathHead().$model->file_name; if($model->save()){ Yii::$app->getSession()->setFlash('success', '保存成功'); // 写入文件 $filepath = $model->getFilePathHead().$model->file_name; CTools::createDir(dirname($filepath)); $file = fopen($filepath, "w"); fwrite($file, $model->content_text); fclose($file); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/list'])); } #抛出异常 throw new Exception (CTools::recursiveMultiArray($model->errors)); }else{ #抛出异常 throw new Exception (CTools::recursiveMultiArray($model->errors)); } }catch (Exception $e){ #捕获抛出的异常 Yii::$app->getSession()->setFlash('error', $e->getMessage()); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/add'])); } } } /** * update a record. * * @return */ public function actionUpdate() { $post = Yii::$app->request->post(); if(!empty($post)){ try{ $model = Api::findOne(['id' =>$post['Api']['id']]); if (null == $model){ throw new Exception ("操作失败,记录不存在"); } if($model->load($post)){ $model->content_text = CTools::translateRichToText(strip_tags($model->content)); $model->url = \Yii::$app->request->hostInfo.'/'.$model->getFilePathHead().$model->file_name; if($model->save()){ Yii::$app->getSession()->setFlash('success', '操作成功'); // 写入文件 $filepath = $model->getFilePathHead().$model->file_name; CTools::createDir(dirname($filepath)); $file = fopen($filepath, "w"); fwrite($file, $model->content_text); fclose($file); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/list'])); } #抛出异常 throw new Exception (CTools::recursiveMultiArray($model->errors)); }else{ #抛出异常 throw new Exception (CTools::recursiveMultiArray($model->errors)); } }catch (Exception $e){ #捕获抛出的异常 Yii::$app->getSession()->setFlash('error', $e->getMessage()); return $this->redictPage(Yii::$app->urlManager->createUrl(['api/edit','id' => $model->id])); } } } /** * 测试代码 * * @return string */ public function actionTestApi(){ $model = Yii::$app->request->get('model'); $data = Yii::$app->request->get('data'); return $this->render('//common/openUrl', [ 'url' => $model->getFilePathHead().$data['file_name'], ]); } }
dora-BYR/adminTest
app/controllers/ApiController.php
PHP
mit
9,118
<div id='printoutPanel'></div> <div id='map'></div> <div id="toolbarContainer" class="hidden">Zone Toolbar<hr /> <span class="close-button">X</span> </div> <div class='map-toolbar'> <div class="row text-primary"> <div class="col-xs-4 center"> <i class="fa fa-3x fa-plus-circle circle zoom-in" aria-hidden="true"></i> </div> </div> <div class="row text-primary pad-top pad-1x"> <div class="col-xs-4 center"> <i class="fa fa-3x fa-minus-circle circle zoom-out " aria-hidden="true"></i> </div> </div> </div> <div class="ipanel ipanel-left hidden" id="assets-panel"> <span class="ipanel-close-button"><i class="fa fa-times" aria-hidden="true"></i></span> <div class="unit-searh-section form-group gap-top"> <input id="untiSearch" type="search" class="form-control searchinput" placeholder="Search here..." value=""> <span id="searchclear" class="searchclear glyphicon glyphicon-remove-circle"></span> </div> <div id="scrollArea" class="clusterize-scroll"> <div id="contentArea" class="clusterize-content"> <div class="clusterize-no-data ">Loading data…</div> </div> </div> </div>
khaladj/newapp
application/views/map.php
PHP
mit
1,162
#region << 版 本 注 释 >> /**************************************************** * 文 件 名: * Copyright(c) ITdos * CLR 版本: 4.0.30319.18408 * 创 建 人:steven hu * 电子邮箱: * 官方网站:www.ITdos.com * 创建日期:2010/4/8 19:55:23 * 文件描述: ****************************************************** * 修 改 人:ITdos * 修改日期: * 备注描述: *******************************************************/ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using Dos.ORM; using Dos.ORM.Common; using Dos.ORM.Common; using System.Data; namespace Dos.ORM { public enum WhereType { /// <summary> /// join where /// </summary> JoinWhere, /// <summary> /// 常规Where /// </summary> Where } /// <summary> /// 比较类型 /// </summary> public enum QueryOperator : byte { /// <summary> /// == /// </summary> Equal, /// <summary> /// &lt;&gt; 、 !=、不等于 /// </summary> NotEqual, /// <summary> /// > /// </summary> Greater, /// <summary> /// &lt; 小于 /// </summary> Less, /// <summary> /// >= /// </summary> GreaterOrEqual, /// <summary> /// &lt;= 小于等于 /// </summary> LessOrEqual, /// <summary> /// LIKE /// </summary> Like, /// <summary> /// & /// </summary> BitwiseAND, /// <summary> /// | /// </summary> BitwiseOR, /// <summary> /// ^ /// </summary> BitwiseXOR, /// <summary> /// ~ /// </summary> BitwiseNOT, /// <summary> /// IS NULL /// </summary> IsNULL, /// <summary> /// IS NOT NULL /// </summary> IsNotNULL, /// <summary> /// + /// </summary> Add, /// <summary> /// - /// </summary> Subtract, /// <summary> /// * /// </summary> Multiply, /// <summary> /// / /// </summary> Divide, /// <summary> /// % /// </summary> Modulo, } /// <summary> /// 参数 /// </summary> [Serializable] public class Parameter { private string parameterName; private object parameterValue; private DbType? parameterDbType; private int? parameterSize; /// <summary> /// /// </summary> /// <param name="parameterName"></param> /// <param name="parameterValue"></param> public Parameter(string parameterName, object parameterValue) : this(parameterName, parameterValue, null, null) { } /// <summary> /// /// </summary> /// <param name="parameterName"></param> /// <param name="parameterValue"></param> /// <param name="parameterDbType"></param> /// <param name="parameterSize"></param> public Parameter(string parameterName, object parameterValue, DbType? parameterDbType, int? parameterSize) { this.parameterName = parameterName; this.parameterValue = parameterValue; this.parameterDbType = parameterDbType; this.parameterSize = parameterSize; } /// <summary> /// 参数名称 /// </summary> public string ParameterName { get { return parameterName; } set { parameterName = value; } } /// <summary> /// 参数值 /// </summary> public object ParameterValue { get { return parameterValue; } set { parameterValue = value; } } /// <summary> /// 类型 /// </summary> public DbType? ParameterDbType { get { return parameterDbType; } set { parameterDbType = value; } } /// <summary> /// 长度 /// </summary> public int? ParameterSize { get { return parameterSize; } set { parameterSize = value; } } } /// <summary> /// 表达式 /// </summary> [Serializable] public class Expression { /// <summary> /// /// </summary> protected string expressionString = string.Empty; /// <summary> /// 参数 /// </summary> protected List<Parameter> parameters = new List<Parameter>(); /// <summary> /// 构造函数 /// </summary> public Expression() { } /// <summary> /// 构造函数 /// </summary> /// <param name="expressionString"></param> public Expression(string expressionString) { this.expressionString = expressionString; } /// <summary> /// 构造函数 /// </summary> /// <param name="expressionString"></param> /// <param name="parameters"></param> public Expression(string expressionString, params Parameter[] parameters) { if (!string.IsNullOrEmpty(expressionString)) { this.expressionString = expressionString; if (null != parameters && parameters.Length > 0) this.parameters.AddRange(parameters); } } /// <summary> /// 构造函数 /// </summary> /// <param name="field"></param> /// <param name="value"></param> /// <param name="oper"></param> public Expression(Field field, object value, QueryOperator oper) : this(field, value, oper, true) { } /// <summary> /// 构造函数 /// </summary> /// <param name="field"></param> /// <param name="value"></param> /// <param name="oper"></param> /// <param name="isFieldBefore"></param> public Expression(Field field, object value, QueryOperator oper, bool isFieldBefore) { if (!Field.IsNullOrEmpty(field)) { string valuestring = null; if (value is Expression) { Expression expression = (Expression)value; valuestring = expression.ToString(); parameters.AddRange(expression.Parameters); } else if (value is Field) { Field fieldValue = (Field)value; valuestring = fieldValue.TableFieldName; } else { valuestring = DataUtils.MakeUniqueKey(field); //valuestring = field.tableName + field.Name; var p = new Parameter(valuestring, value, field.ParameterDbType, field.ParameterSize); parameters.Add(p); } if (isFieldBefore) { this.expressionString = string.Concat(field.TableFieldName, DataUtils.ToString(oper), valuestring); } else { this.expressionString = string.Concat(valuestring, DataUtils.ToString(oper), field.TableFieldName); } } } /// <summary> /// 返回参数 /// </summary> internal List<Parameter> Parameters { get { return parameters; } } /// <summary> /// 返回组合字符串 /// </summary> /// <returns></returns> public override string ToString() { return expressionString; } } }
windygu/Dos.ORM
Expression/Expression.cs
C#
mit
8,076
var mongoose = require('mongoose') , Schema = mongoose.Schema , ObjectId = Schema.ObjectId , relationships = require('../../index'); // require('mongoose-relationships'); /** * Blog Post Schema * "belongs to one author" */ var PostSchema = new Schema({ title : String , body : String , author : {type: ObjectId, ref: 'User'} }); /** * User Schema * "has many posts" */ var UserSchema = new Schema({ name : String , posts : [{type: ObjectId, ref: 'Post'}] }); /** * Attach the plugin to the schemas */ PostSchema.plugin(relationships, { belongsTo : "User" , through : "author" }); UserSchema.plugin(relationships, { hasMany : "Post" , through : "posts" }); /** * Register the models with Mongoose */ var Post = mongoose.model('Post', PostSchema) , User = mongoose.model('User', UserSchema); // Have fun here: var user = new User(); user.posts.create({ title: "Mongoose, now with added love through relationships!" }, function(err, user, post){ // user.posts.length === 1 // post.title === "Mongoose, now with added love through relationships!" }); // Using an `Array` user.posts.create([ { title: "Not too imaginative post title" } , { title: "... a tad more imaginative post title" } ], function(err, user, posts){ // user.posts.length === 3 // posts.length == 2 // posts[0] instanceof Post });
shagupta10/MEANJS
node_modules/mongo-relation/examples/blog/models.js
JavaScript
mit
1,386
import {createSelector} from 'reselect' import usersSelector from 'usersSelector' const selectedUserIdSelector = (state) => state.selectedUserId export default createSelector( [usersSelector, selectedUserIdSelector], (users, selectedUserId) => users.get(selectedUserId) )
unindented/react-redux-winjs-example
selectors/selectedUserSelector/src/selectedUserSelector.js
JavaScript
mit
279
// (c) ammap.com | SVG (in JSON format) map of Libya - Low // areas: {id:"LY-WD"},{id:"LY-BU"},{id:"LY-DR"},{id:"LY-SR"},{id:"LY-BA"},{id:"LY-WA"},{id:"LY-JA"},{id:"LY-HZ"},{id:"LY-TB"},{id:"LY-MZ"},{id:"LY-ZA"},{id:"LY-NQ"},{id:"LY-JI"},{id:"LY-SB"},{id:"LY-MI"},{id:"LY-MQ"},{id:"LY-GT"},{id:"LY-WS"},{id:"LY-MB"},{id:"LY-KF"},{id:"LY-JU"},{id:"LY-NL"} AmCharts.maps.libyaLow={ "svg": { "defs": { "amcharts:ammap": { "projection":"mercator", "leftLongitude":"9.391466", "topLatitude":"33.1679793", "rightLongitude":"25.146954", "bottomLatitude":"19.5008125" } }, "g":{ "path":[ { "id":"LY-WD", "title":"Wadi al Hayaa", "d":"M236.97,352.67L188.1,345.8L105.65,404.02L106.9,441.29L145.18,439.93L234.51,402.37L245.18,378.51L236.97,352.67z" }, { "id":"LY-BU", "title":"Al Butnan", "d":"M790.67,297.68L790.32,232.14L775.94,177.43L791.36,142.24L784.01,109.12L799.48,90.55L790.69,72.49L703.58,57.71L689.36,141.4L694.05,295.25L790.67,297.68z" }, { "id":"LY-DR", "title":"Darnah", "d":"M703.58,57.71L696.27,32.47L639.88,16.11L636.44,113.04L646.24,122.59L689.36,141.4L703.58,57.71z" }, { "id":"LY-SR", "title":"Surt", "d":"M478.97,166.48L407.27,124.54L345.42,114.27L365.25,209.36L359.58,222.33L405.66,229.62L418.06,223.15L438.3,261.26L464.33,274.5L478.97,166.48z" }, { "id":"LY-BA", "title":"Benghazi", "d":"M606.3,127.57L601.08,97.76L567.51,95.48L557.53,74.82L568.89,37.08L536.87,73.09L547.02,116.47L569.78,129.22L606.3,127.57z" }, { "id":"LY-WA", "title":"Al Wahat", "d":"M606.3,127.57L569.78,129.22L547.02,116.47L541.73,140.25L520.58,163.52L496.89,172.65L478.97,166.48L464.33,274.5L498.21,283.36L498.09,359.23L790.67,357.18L790.67,297.68L694.05,295.25L689.36,141.4L646.24,122.59L626.34,125.78L606.3,127.57z" }, { "id":"LY-JA", "title":"Al Jabal al Akhdar", "d":"M639.88,16.11L608.21,24.06L626.34,125.78L646.24,122.59L636.44,113.04L639.88,16.11z" }, { "id":"LY-MJ", "title":"Al Marj", "d":"M608.21,24.06L568.89,37.08L557.53,74.82L567.51,95.48L601.08,97.76L606.3,127.57L626.34,125.78L608.21,24.06z" }, { "id":"LY-TB", "title":"Tripoli", "d":"M235.52,25.39L192.67,18.24L191.32,27.6L199.38,50.74L235.52,25.39z" }, { "id":"LY-JG", "title":"Al Jabal al Gharbi", "d":"M207.49,67.57L200.1,51.71L178.39,55.12L130.21,52.3L135.27,124.88L116.48,156.44L123.5,240.9L134.7,269.17L171.79,278.61L233.31,213.15L258.95,233.86L275.7,222.53L280.82,196.08L285.65,164.23L248.47,145.99L207.49,67.57z" }, { "id":"LY-ZA", "title":"Az Zawiyah", "d":"M191.32,27.6L192.67,18.24L165.98,22.13L130.21,52.3L178.39,55.12L191.32,27.6z" }, { "id":"LY-NQ", "title":"An Nuqat al Khams", "d":"M112.21,0L113.27,45.72L130.21,52.3L165.98,22.13L112.21,0z" }, { "id":"LY-JI", "title":"Al Jifarah", "d":"M199.38,50.74L191.32,27.6L178.39,55.12L200.1,51.71L199.38,50.74z" }, { "id":"LY-SB", "title":"Sabha", "d":"M328.23,319.08L291.61,324.15L259.02,350.19L236.97,352.67L245.18,378.51L234.51,402.37L259.18,395.1L279.48,373.62L352.59,355.71L328.23,319.08z" }, { "id":"LY-MI", "title":"Misratah", "d":"M345.42,114.27L314.06,92.6L301.74,51.03L275.87,43.83L271.38,72.5L243.96,62.12L207.49,67.57L248.47,145.99L285.65,164.23L280.82,196.08L325.45,223.19L359.58,222.33L365.25,209.36L345.42,114.27z" }, { "id":"LY-MQ", "title":"Murzuq", "d":"M498,416L449.47,395.09L409.49,413.29L385.86,407.05L352.53,368.64L352.59,355.71L279.48,373.62L259.18,395.1L234.51,402.37L145.18,439.93L106.9,441.29L110.31,509.32L135.56,553.87L211.75,572.39L248.7,603.18L337.76,557.86L498.9,644.09L498,416z" }, { "id":"LY-GT", "title":"Ghat", "d":"M105.65,404.02L92.16,335.26L32.98,313.53L22.41,343.44L31.22,379.55L6.29,409.86L36.84,453.56L38.05,479.97L49.54,495.47L110.31,509.32L106.9,441.29L105.65,404.02z" }, { "id":"LY-WS", "title":"Wadi ash Shati'", "d":"M258.95,233.86L233.31,213.15L171.79,278.61L134.7,269.17L103.09,272.05L82.24,254.85L58.63,267.48L27.74,267.82L32.98,313.53L92.16,335.26L105.65,404.02L188.1,345.8L236.97,352.67L259.02,350.19L291.61,324.15L328.23,319.08L332.41,298.68L317.85,290.94L289.05,294.93L286.08,279.91L259.09,252.9L258.95,233.86z" }, { "id":"LY-MB", "title":"Al Marqab", "d":"M275.87,43.83L235.52,25.39L199.38,50.74L200.1,51.71L207.49,67.57L243.96,62.12L271.38,72.5L275.87,43.83z" }, { "id":"LY-KF", "title":"Al Kufrah", "d":"M740.33,771.53L740.33,744.82L790.45,744.79L790.67,357.18L498.09,359.23L498,416L498.9,644.09L740.33,771.53z" }, { "id":"LY-JU", "title":"Al Jufrah", "d":"M359.58,222.33L325.45,223.19L280.82,196.08L275.7,222.53L258.95,233.86L259.09,252.9L286.08,279.91L289.05,294.93L317.85,290.94L332.41,298.68L328.23,319.08L352.59,355.71L352.53,368.64L385.86,407.05L409.49,413.29L449.47,395.09L498,416L498.09,359.23L498.21,283.36L464.33,274.5L438.3,261.26L418.06,223.15L405.66,229.62L359.58,222.33z" }, { "id":"LY-NL", "title":"Nalut", "d":"M130.21,52.3L113.27,45.72L49.73,89.52L41.79,104.37L46.11,145.4L29.96,167.38L0.52,181.25L19.71,210.79L27.74,267.82L58.63,267.48L82.24,254.85L103.09,272.05L134.7,269.17L123.5,240.9L116.48,156.44L135.27,124.88L130.21,52.3z" } ] } } };
cdnjs/cdnjs
ajax/libs/ammaps/3.21.15/maps/js/libyaLow.js
JavaScript
mit
5,470
namespace Fluid.Parser { public static class ErrorMessages { public const string EqualAfterAssignIdentifier = "'=' was expected after the identifier of 'assign'"; public const string IdentifierAfterAssign = "An identifier was expected after the 'assign' tag"; public const string IdentifierAfterTagStart = "An identifier was expected after '{%'"; public const string LogicalExpressionStartsFilter = "A value was expected"; public const string IdentifierAfterPipe = "An identifier was expected after the '|' sign"; public const string ExpectedTagEnd = "End of tag '%}' was expected"; public const string ExpectedOutputEnd = "End of tag '}}' was expected"; public const string ExpectedStringRender = "A quoted string value is required for the render tag"; public const string FunctionsNotAllowed = "Functions are not allowed"; public const string IdentifierAfterMacro = "An identifier was expected after the 'macro' tag"; public const string ParentesesAfterFunctionName = "Start of arguments '(' is expected after a function name"; } }
sebastienros/fluid
Fluid/Parser/ErrorMessages.cs
C#
mit
1,137
require "recall_pi/version" require "recall_pi/pi" require "recall_pi/pi_config" require "recall_pi/pi_generator" require "recall_pi/application"
rsb/recall_pi
lib/recall_pi.rb
Ruby
mit
146
namespace SqlModeller.Model { public class CommonTableExpression { public string Alias { get; set; } public SelectQuery Query { get; set; } } }
jmenziessmith/SqlModeller
src/SqlModeller/Model/CommonTableExpression.cs
C#
mit
181
<?php namespace Prooms\SecurityBundle\Entity; use Doctrine\ORM\Mapping as ORM; use Doctrine\Common\Collections\ArrayCollection; use Prooms\RoomsBundle\Entity\Room; use Prooms\RoomsBundle\Entity\UserRoom; use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity; use Symfony\Component\Validator\Mapping\ClassMetadata; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity * @ORM\Table(name="student_groups") * @ORM\Entity(repositoryClass="Prooms\SecurityBundle\Entity\StudentGroupRepository") * @UniqueEntity( * fields={"year", "degree", "major", "instrument", "gpaFloor"}, * message="Duplicate student group exist in your uploaded csv file." * ) */ class StudentGroup { /** * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @ORM\Column(type="integer") */ private $year; /** * @ORM\Column(type="string", length=30) */ private $degree; /** * @ORM\Column(type="string", length=30) */ private $major; /** * @ORM\Column(type="string", length=30) */ private $instrument; /** * @ORM\Column(name="gpa_floor", type="integer") */ private $gpaFloor; /** * @ORM\Column(name="max_hours", type="integer") */ private $maxHours; /** * @ORM\Column(name="opening_datetime", type="datetime") */ private $openingDatetime; public static function getAllDegrees() { return array( 'bmvs' => 'BMVS', 'mmus' => 'MMUS', 'dma' => 'DMA', 'dpst' => 'DPST', 'dmps' => 'DMPS' ); } public static function getAllMajors() { return array( 'gmus'=>'GMUS', 'gsem'=>'GSEM', 'gssm'=>'GSSM', 'voic'=>'VOIC', 'muss'=>'MUSS', 'guit'=>'GUIT', 'comp'=>'COMP', 'orin'=>'ORIN', 'pian'=>'PIAN', 'oper'=>'OPER', 'harp'=>'HARP', 'opgn'=>'OPGN', 'chor'=>'CHOR', 'oper'=>'OPER', ) ; } public function getId() { return $this->id; } public function getDegree() { return $this->degree; } public function setDegree($degree) { $this->degree = $degree; } public function getMajor() { return $this->major; } public function setMajor($major = NULL) { $this->major = $major; } public function getYear() { return $this->year; } public function setYear($year = NULL) { $this->year = $year; } public function setInstrument($instrument) { $this->instrument = $instrument; } public function getInstrument() { return $this->instrument; } public function getGpaFloor() { return $this->gpaFloor; } public function setGpaFloor($gpa) { $this->gpaFloor = $gpa; } public function getMaxHours() { return $this->maxHours; } public function setMaxHours($maxHours) { $this->maxHours = $maxHours; } public function getOpeningDatetime() { return $this->openingDatetime; } public function setOpeningDatetime($dateTime) { $this->openingDatetime = $dateTime; } public function isDefault() { return ! ($this->degree || $this->major || $this->year || $this->instrument || $this->gpaFloor); } public static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata->addPropertyConstraint('gpaFloor', new Assert\Max(array( 'limit' => '100', 'message' => 'GPA floor must be 100(%) or smaller.', ))); $metadata->addPropertyConstraint('gpaFloor', new Assert\Min(array( 'limit' => '0', 'message' => 'GPA floor must be 0(%) or higher.', ))); $metadata->addPropertyConstraint('maxHours', new Assert\Min(array( 'limit' => '0', 'message' => 'GPA floor must be 0 or higher.', ))); } }
y252zhan/Music-Rooms-Manager
src/Prooms/SecurityBundle/Entity/StudentGroup.php
PHP
mit
4,261
/** * @license Highcharts JS v9.1.0 (2021-05-04) * @module highcharts/themes/high-contrast-light * @requires highcharts * * (c) 2009-2021 Highsoft AS * * License: www.highcharts.com/license */ 'use strict'; import '../../Extensions/Themes/HighContrastLight.js';
cdnjs/cdnjs
ajax/libs/highcharts/9.1.0/es-modules/masters/themes/high-contrast-light.src.js
JavaScript
mit
270
<?php namespace MoreSparetime\WordPress\PluginBuilder\Cron; use AndreasGlaser\Helpers\Validate\Expect; use MoreSparetime\WordPress\PluginBuilder\AttachableInterface; use MoreSparetime\WordPress\PluginBuilder\Plugin; use MoreSparetime\WordPress\PluginBuilder\PluginAwareTrait; /** * Class Cron * * @package MoreSparetime\WordPress\PluginBuilder\Cron * @author Andreas Glaser */ class Cron implements AttachableInterface { use PluginAwareTrait; /** * @var string */ protected $slug; /** * @var callable */ protected $controller; /** * @var string */ protected $recurrence; /** * Cron constructor. * * @param \MoreSparetime\WordPress\PluginBuilder\Plugin $plugin * @param string $slug * @param callable $controller * @param string $recurrence * * @author Andreas Glaser */ public function __construct(Plugin $plugin, $slug, $controller, $recurrence = 'hourly') { $this->setPlugin($plugin); $this->setSlug($slug); $this->setController($controller); $this->setRecurrence($recurrence); } /** * @return string * @author Andreas Glaser */ public function getSlug() { return $this->slug; } /** * @param string $slug * * @return Cron * @author Andreas Glaser */ public function setSlug($slug) { Expect::str($slug); $this->slug = $this->plugin->makeSlug('cron', $slug); return $this; } /** * @return callable * @author Andreas Glaser */ public function getController() { return $this->controller; } /** * @param callable $controller * * @return Cron * @author Andreas Glaser */ public function setController($controller) { Expect::isCallable($controller); $this->controller = $controller; return $this; } /** * @return string * @author Andreas Glaser */ public function getRecurrence() { return $this->recurrence; } /** * @param string $recurrence * * @return Cron * @author Andreas Glaser */ public function setRecurrence($recurrence) { Expect::str($recurrence); $this->recurrence = $recurrence; return $this; } /** * @return void * @author Andreas Glaser */ public function attachHooks() { // todo: this can probably be wrapped into activation hook if (!wp_next_scheduled($this->slug)) { wp_schedule_event(time(), $this->recurrence, $this->slug); } add_action($this->slug, $this->controller); // remove cron on deactivation register_deactivation_hook($this->plugin->getPluginFilePath(), function () { wp_clear_scheduled_hook($this->slug); }); } }
more-sparetime/wp-plugin-builder
src/Cron/Cron.php
PHP
mit
3,052
#module Lettr #class Railtie < Rails::Railtie #initializer 'lettr.init' do #ActiveSupport.on_load(:action_mailer) do #ActionMailer::Base.add_delivery_method :lettr, Lettr::MailExtensions::Lettr #end #end #end #end
digineo/lettr
lib/lettr/railtie.rb
Ruby
mit
248
import Hammer from '@egjs/hammerjs'; import { DEG_RAD } from './constants'; import { HammerInputExt } from './GestureHandler'; import IndiscreteGestureHandler from './IndiscreteGestureHandler'; class RotationGestureHandler extends IndiscreteGestureHandler { get name() { return 'rotate'; } get NativeGestureClass() { return Hammer.Rotate; } transformNativeEvent({ rotation, velocity, center }: HammerInputExt) { return { rotation: (rotation - (this.initialRotation ?? 0)) * DEG_RAD, anchorX: center.x, anchorY: center.y, velocity, }; } } export default RotationGestureHandler;
kmagiera/react-native-gesture-handler
src/web/RotationGestureHandler.ts
TypeScript
mit
633
# frozen_string_literal: true module Cucumber module Core module Ast class EmptyBackground def describe_to(*) self end def inspect "#<#{self.class.name}>" end end end end end
kamenlitchev/cucumber-ruby-core
lib/cucumber/core/ast/empty_background.rb
Ruby
mit
253
<?php return array( /* |-------------------------------------------------------------------------- | Application Debug Mode |-------------------------------------------------------------------------- | | When your application is in debug mode, detailed error messages with | stack traces will be shown on every error that occurs within your | application. If disabled, a simple generic error page is shown. | */ 'debug' => true, /* |-------------------------------------------------------------------------- | Application URL |-------------------------------------------------------------------------- | | This URL is used by the console to properly generate URLs when using | the Artisan command line tool. You should set this to the root of | your application so that it is used when running Artisan tasks. | */ 'url' => 'http://localhost', /* |-------------------------------------------------------------------------- | Application Timezone |-------------------------------------------------------------------------- | | Here you may specify the default timezone for your application, which | will be used by the PHP date and date-time functions. We have gone | ahead and set this to a sensible default for you out of the box. | */ 'timezone' => 'UTC', /* |-------------------------------------------------------------------------- | Application Locale Configuration |-------------------------------------------------------------------------- | | The application locale determines the default locale that will be used | by the translation service provider. You are free to set this value | to any of the locales which will be supported by the application. | */ 'locale' => 'en', /* |-------------------------------------------------------------------------- | Application Fallback Locale |-------------------------------------------------------------------------- | | The fallback locale determines the locale to use when the current one | is not available. You may change the value to correspond to any of | the language folders that are provided through your application. | */ 'fallback_locale' => 'en', /* |-------------------------------------------------------------------------- | Encryption Key |-------------------------------------------------------------------------- | | This key is used by the Illuminate encrypter service and should be set | to a random, 32 character string, otherwise these encrypted strings | will not be safe. Please do this before deploying an application! | */ 'key' => 'dNsAlWrFxjY7ISQEr6i4DzoIkQHpmdFn', 'cipher' => MCRYPT_RIJNDAEL_128, /* |-------------------------------------------------------------------------- | Autoloaded Service Providers |-------------------------------------------------------------------------- | | The service providers listed here will be automatically loaded on the | request to your application. Feel free to add your own services to | this array to grant expanded functionality to your applications. | */ 'providers' => array( 'Illuminate\Foundation\Providers\ArtisanServiceProvider', 'Illuminate\Auth\AuthServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Session\CommandsServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Routing\ControllerServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Html\HtmlServiceProvider', 'Illuminate\Log\LogServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Database\MigrationServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Remote\RemoteServiceProvider', 'Illuminate\Auth\Reminders\ReminderServiceProvider', 'Illuminate\Database\SeedServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'Illuminate\Workbench\WorkbenchServiceProvider', 'Skovachev\Notifier\ServiceProvider', ), /* |-------------------------------------------------------------------------- | Service Provider Manifest |-------------------------------------------------------------------------- | | The service provider manifest is used by Laravel to lazy load service | providers which are not needed for each request, as well to keep a | list of all of the services. Here, you may set its storage spot. | */ 'manifest' => storage_path().'/meta', /* |-------------------------------------------------------------------------- | Class Aliases |-------------------------------------------------------------------------- | | This array of class aliases will be registered when this application | is started. However, feel free to register as many as you wish as | the aliases are "lazy" loaded so they don't hinder performance. | */ 'aliases' => array( 'App' => 'Illuminate\Support\Facades\App', 'Artisan' => 'Illuminate\Support\Facades\Artisan', 'Auth' => 'Illuminate\Support\Facades\Auth', 'Blade' => 'Illuminate\Support\Facades\Blade', 'Cache' => 'Illuminate\Support\Facades\Cache', 'ClassLoader' => 'Illuminate\Support\ClassLoader', 'Config' => 'Illuminate\Support\Facades\Config', 'Controller' => 'Illuminate\Routing\Controller', 'Cookie' => 'Illuminate\Support\Facades\Cookie', 'Crypt' => 'Illuminate\Support\Facades\Crypt', 'DB' => 'Illuminate\Support\Facades\DB', 'Eloquent' => 'Illuminate\Database\Eloquent\Model', 'Event' => 'Illuminate\Support\Facades\Event', 'File' => 'Illuminate\Support\Facades\File', 'Form' => 'Illuminate\Support\Facades\Form', 'Hash' => 'Illuminate\Support\Facades\Hash', 'HTML' => 'Illuminate\Support\Facades\HTML', 'Input' => 'Illuminate\Support\Facades\Input', 'Lang' => 'Illuminate\Support\Facades\Lang', 'Log' => 'Illuminate\Support\Facades\Log', 'Mail' => 'Illuminate\Support\Facades\Mail', 'Notifier' => 'Skovachev\Notifier\Facade', 'Paginator' => 'Illuminate\Support\Facades\Paginator', 'Password' => 'Illuminate\Support\Facades\Password', 'Queue' => 'Illuminate\Support\Facades\Queue', 'Redirect' => 'Illuminate\Support\Facades\Redirect', 'Redis' => 'Illuminate\Support\Facades\Redis', 'Request' => 'Illuminate\Support\Facades\Request', 'Response' => 'Illuminate\Support\Facades\Response', 'Route' => 'Illuminate\Support\Facades\Route', 'Schema' => 'Illuminate\Support\Facades\Schema', 'Seeder' => 'Illuminate\Database\Seeder', 'Session' => 'Illuminate\Support\Facades\Session', 'SoftDeletingTrait' => 'Illuminate\Database\Eloquent\SoftDeletingTrait', 'SSH' => 'Illuminate\Support\Facades\SSH', 'Str' => 'Illuminate\Support\Str', 'URL' => 'Illuminate\Support\Facades\URL', 'Validator' => 'Illuminate\Support\Facades\Validator', 'View' => 'Illuminate\Support\Facades\View', ), );
georgizhivankin/SmartDir
app/config/app.php
PHP
mit
7,563
<?php /** * @link http://www.yiiframework.com/ * @copyright Copyright (c) 2008 Yii Software LLC * @license http://www.yiiframework.com/license/ */ namespace yii\jui; use yii\base\InvalidConfigException; use yii\helpers\ArrayHelper; use yii\helpers\Url; use yii\helpers\Html; /** * Tabs renders a tabs jQuery UI widget. * * For example: * * ```php * echo Tabs::widget([ * 'items' => [ * [ * 'label' => 'Tab one', * 'content' => 'Mauris mauris ante, blandit et, ultrices a, suscipit eget...', * ], * [ * 'label' => 'Tab two', * 'content' => 'Sed non urna. Phasellus eu ligula. Vestibulum sit amet purus...', * 'options' => ['tag' => 'div'], * 'headerOptions' => ['class' => 'my-class'], * ], * [ * 'label' => 'Tab with custom id', * 'content' => 'Morbi tincidunt, dui sit amet facilisis feugiat...', * 'options' => ['id' => 'my-tab'], * ], * [ * 'label' => 'Ajax tab', * 'url' => ['ajax/content'], * ], * ], * 'options' => ['tag' => 'div'], * 'itemOptions' => ['tag' => 'div'], * 'headerOptions' => ['class' => 'my-class'], * 'clientOptions' => ['collapsible' => false], * ]); * ``` * * @see http://api.jqueryui.com/tabs/ * @author Alexander Kochetov <creocoder@gmail.com> * @since 2.0 */ class Tabs extends Widget { /** * @var array the HTML attributes for the widget container tag. The following special options are recognized: * * - tag: string, defaults to "div", the tag name of the container tag of this widget. * * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $options = []; /** * @var array list of tab items. Each item can be an array of the following structure: * * - label: string, required, specifies the header link label. When [[encodeLabels]] is true, the label * will be HTML-encoded. * - content: string, the content to show when corresponding tab is clicked. Can be omitted if url is specified. * - url: mixed, mixed, optional, the url to load tab contents via AJAX. It is required if no content is specified. * - template: string, optional, the header link template to render the header link. If none specified * [[linkTemplate]] will be used instead. * - options: array, optional, the HTML attributes of the header. * - headerOptions: array, optional, the HTML attributes for the header container tag. */ public $items = []; /** * @var array list of HTML attributes for the item container tags. This will be overwritten * by the "options" set in individual [[items]]. The following special options are recognized: * * - tag: string, defaults to "div", the tag name of the item container tags. * * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $itemOptions = []; /** * @var array list of HTML attributes for the header container tags. This will be overwritten * by the "headerOptions" set in individual [[items]]. * @see \yii\helpers\Html::renderTagAttributes() for details on how attributes are being rendered. */ public $headerOptions = []; /** * @var string the default header template to render the link. */ public $linkTemplate = '<a href="{url}">{label}</a>'; /** * @var boolean whether the labels for header items should be HTML-encoded. */ public $encodeLabels = true; /** * Renders the widget. */ public function run() { $options = $this->options; $tag = ArrayHelper::remove($options, 'tag', 'div'); echo Html::beginTag($tag, $options) . "\n"; echo $this->renderItems() . "\n"; echo Html::endTag($tag) . "\n"; $this->registerWidget('tabs'); } /** * Renders tab items as specified on [[items]]. * @return string the rendering result. * @throws InvalidConfigException. */ protected function renderItems() { $headers = []; $items = []; foreach ($this->items as $n => $item) { if (!isset($item['label'])) { throw new InvalidConfigException("The 'label' option is required."); } if (isset($item['url'])) { $url = Url::to($item['url']); } else { if (!isset($item['content'])) { throw new InvalidConfigException("The 'content' or 'url' option is required."); } $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', [])); $tag = ArrayHelper::remove($options, 'tag', 'div'); if (!isset($options['id'])) { $options['id'] = $this->options['id'] . '-tab' . $n; } $url = '#' . $options['id']; $items[] = Html::tag($tag, $item['content'], $options); } $headerOptions = array_merge($this->headerOptions, ArrayHelper::getValue($item, 'headerOptions', [])); $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate); $headers[] = Html::tag( 'li', strtr( $template, [ '{label}' => $this->encodeLabels ? Html::encode($item['label']) : $item['label'], '{url}' => $url, ] ), $headerOptions ); } return Html::tag('ul', implode("\n", $headers)) . "\n" . implode("\n", $items); } }
heartshare/cmf-1
based/vendor/yiisoft/yii2-jui/Tabs.php
PHP
mit
5,861
'use strict'; var yeoman = require('yeoman-generator'); var chalk = require('chalk'); var yosay = require('yosay'); module.exports = yeoman.Base.extend({ prompting: function () { // Have Yeoman greet the user. this.log(yosay( 'Welcome to the stylish ' + chalk.red('generator-dev-cli') + ' generator!' )); var prompts = [{ type: 'list', name: 'environment', message: 'Please choose dev environment(jsPlugin):', choices: ['jsPlugin', 'react'], default: 'jsPlugin' }, { type: 'input', name: 'name', message: 'Your project name', default: this.appname // Default to current folder name }, { type: 'confirm', name: 'besure', message: 'Would you like to enable this option?', default: true }]; return this.prompt(prompts).then(function (props) { // To access props later use this.props.someAnswer; this.props = props; }.bind(this)); }, writing: function () { this.fs.copy( this.templatePath(this.props.environment), this.destinationPath(this.props.name), true ); this.fs.copy( this.templatePath(this.props.environment + '/.*'), this.destinationPath(this.props.name + '/'), true ); }, install: function () { } });
lsa2127291/generator-dev-cli
generators/app/index.js
JavaScript
mit
1,503
const { stripIndent } = require('common-tags') module.exports = function (widgetName) { return stripIndent` import { ${widgetName} } from 'react-widgets'; let people = listOfPeople(); <> <${widgetName} data={people} textField='fullName' groupBy='lastName' /> <${widgetName} data={people} textField='fullName' groupBy={person => person.fullName.length} /> </> ` }
jquense/react-widgets
www/plugins/examples/groupBy.js
JavaScript
mit
458
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_21.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__new_free.label.xml Template File: sources-sinks-21.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: Allocate data using new * GoodSource: Allocate data using malloc() * Sinks: * GoodSink: Deallocate data using delete * BadSink : Deallocate data using free() * Flow Variant: 21 Control flow: Flow controlled by value of a static global variable. All functions contained in one file. * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_21 { #ifndef OMITBAD /* The static variable below is used to drive control flow in the sink function */ static int badStatic = 0; static void badSink(int64_t * data) { if(badStatic) { /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete to deallocate the memory */ free(data); } } void bad() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new int64_t; badStatic = 1; /* true */ badSink(data); } #endif /* OMITBAD */ #ifndef OMITGOOD /* The static variables below are used to drive control flow in the sink functions. */ static int goodB2G1Static = 0; static int goodB2G2Static = 0; static int goodG2bStatic = 0; /* goodB2G1() - use badsource and goodsink by setting the static variable to false instead of true */ static void goodB2G1Sink(int64_t * data) { if(goodB2G1Static) { /* INCIDENTAL: CWE 561 Dead Code, the code below will never run */ printLine("Benign, fixed string"); } else { /* FIX: Deallocate the memory using delete */ delete data; } } static void goodB2G1() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new int64_t; goodB2G1Static = 0; /* false */ goodB2G1Sink(data); } /* goodB2G2() - use badsource and goodsink by reversing the blocks in the if in the sink function */ static void goodB2G2Sink(int64_t * data) { if(goodB2G2Static) { /* FIX: Deallocate the memory using delete */ delete data; } } static void goodB2G2() { int64_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires delete to free the memory */ data = new int64_t; goodB2G2Static = 1; /* true */ goodB2G2Sink(data); } /* goodG2B() - use goodsource and badsink */ static void goodG2BSink(int64_t * data) { if(goodG2bStatic) { /* POTENTIAL FLAW: Deallocate memory using free() - the source memory allocation function may * require a call to delete to deallocate the memory */ free(data); } } static void goodG2B() { int64_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory from the heap using malloc() */ data = (int64_t *)malloc(100*sizeof(int64_t)); goodG2bStatic = 1; /* true */ goodG2BSink(data); } void good() { goodB2G1(); goodB2G2(); goodG2B(); } #endif /* OMITGOOD */ } /* close namespace */ /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_21; /* so that we can use good and bad easily */ int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
maurer/tiamat
samples/Juliet/testcases/CWE762_Mismatched_Memory_Management_Routines/s06/CWE762_Mismatched_Memory_Management_Routines__new_free_int64_t_21.cpp
C++
mit
4,431
package io.hosuaby.restful.services; import io.hosuaby.restful.controllers.TeapotCommandController; import io.hosuaby.restful.services.exceptions.teapots.TeapotNotConnectedException; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import org.springframework.web.context.request.async.DeferredResult; import org.springframework.web.socket.WebSocketSession; /** * Service that provides registration of teapots and communication with them via * web socket sessions. */ public interface TeapotCommandService { /** * Registers a newly connected teapot with associated websocket connection. * * @param teapotId teapot id * @param session teapot websocket session */ void register(String teapotId, WebSocketSession session); /** * Unregisters disconnected teapot. This method don't close teapot session. * Teapot session must be closed prior to call of this method. Teapot must * be registered prior to call of this method. * * @param teapotSession teapot websocket session */ void unregister(WebSocketSession teapotSession); /** * Shutdown the connected teapot. This method is called by * {@link TeapotCommandController}. * * @param teapotId teapot id. * * @throws IOException * failed to close teapot session * @throws TeapotNotConnectedException * teapot with defined id is not connected */ void shutdown(String teapotId) throws IOException, TeapotNotConnectedException; /** * @return ids of registered teapots. */ String[] getRegisteredTeapotsIds(); /** * Returns true if teapot with defined id is connected, and false if teapot * is not connected. * * @param teapotId teapot id * * @return true if teapot is connected, false if not */ boolean isTeapotConnected(String teapotId); /** * Sends the message to the teapot from Ajax client. This method returns * {@link DeferredResult} that will be fulfilled once teapot returns the * answer. If any error occurs during processing deferred object is * rejected with appropriate error code and message. * For chaque Ajax request method generates unique clientId that will be * transmitted to teapot. * * @param req ajax http request * @param teapotId teapot id * @param msg message to send * * @return deferred result */ DeferredResult<String> sendMessage(HttpServletRequest req, String teapotId, String msg); /** * Submits response from the teapot to the client. Attribute * <code>clientId</code> can reference unique request in case of Ajax * request or websocket session if client is connected via websocket. * If command was made by Ajax request, associated DeferredResult * is fulfilled. * * @param clientId request or websocket session id * @param msg message to send */ void submitResponse(String clientId, String msg); /** * Submits response from the teapot to the client. Attribute * <code>clientId</code> can reference unique request in case of Ajax * request or websocket session if client is connected via websocket. * In the case of Ajax request, if <code>isLast</code> is set to * <code>true</code> the message is appended to the buffer instead of * immediate fulfill of the <code>DeferredResult</code> object. * * @param clientId request or websocket session id * @param msg message to send * @param isLast flag of the last message of the response */ void submitResponse(String clientId, String msg, boolean isLast); /** * Sends error message back to client. * * @param clientId request or websocket session id * @param error error message */ void submitError(String clientId, String error); }
hosuaby/example-restful-project
src/main/java/io/hosuaby/restful/services/TeapotCommandService.java
Java
mit
4,011
using UnityEngine; using System.Collections; namespace UnityChan { // // ↑↓キーでループアニメーションを切り替えるスクリプト(ランダム切り替え付き)Ver.3 // 2014/04/03 N.Kobayashi // // Require these components when using this script [RequireComponent(typeof(Animator))] public class IdleChanger : MonoBehaviour { private Animator anim; // Animatorへの参照 private AnimatorStateInfo currentState; // 現在のステート状態を保存する参照 private AnimatorStateInfo previousState; // ひとつ前のステート状態を保存する参照 public bool _random = false; // ランダム判定スタートスイッチ public float _threshold = 0.5f; // ランダム判定の閾値 public float _interval = 10f; // ランダム判定のインターバル //private float _seed = 0.0f; // ランダム判定用シード // Use this for initialization void Start () { // 各参照の初期化 anim = GetComponent<Animator> (); currentState = anim.GetCurrentAnimatorStateInfo (0); previousState = currentState; // ランダム判定用関数をスタートする StartCoroutine ("RandomChange"); } // Update is called once per frame void Update () { // ↑キー/スペースが押されたら、ステートを次に送る処理 if (Input.GetKeyDown ("up") || Input.GetButton ("Jump")) { // ブーリアンNextをtrueにする anim.SetBool ("Next", true); } // ↓キーが押されたら、ステートを前に戻す処理 if (Input.GetKeyDown ("down")) { // ブーリアンBackをtrueにする anim.SetBool ("Back", true); } // "Next"フラグがtrueの時の処理 if (anim.GetBool ("Next")) { // 現在のステートをチェックし、ステート名が違っていたらブーリアンをfalseに戻す currentState = anim.GetCurrentAnimatorStateInfo (0); if (previousState.fullPathHash != currentState.fullPathHash) { anim.SetBool ("Next", false); previousState = currentState; } } // "Back"フラグがtrueの時の処理 if (anim.GetBool ("Back")) { // 現在のステートをチェックし、ステート名が違っていたらブーリアンをfalseに戻す currentState = anim.GetCurrentAnimatorStateInfo (0); if (previousState.fullPathHash != currentState.fullPathHash) { anim.SetBool ("Back", false); previousState = currentState; } } } void OnGUI () { GUI.Box (new Rect (Screen.width - 110, 10, 100, 90), "Change Motion"); if (GUI.Button (new Rect (Screen.width - 100, 40, 80, 20), "Next")) anim.SetBool ("Next", true); if (GUI.Button (new Rect (Screen.width - 100, 70, 80, 20), "Back")) anim.SetBool ("Back", true); } // ランダム判定用関数 IEnumerator RandomChange () { // 無限ループ開始 while (true) { //ランダム判定スイッチオンの場合 if (_random) { // ランダムシードを取り出し、その大きさによってフラグ設定をする float _seed = Random.Range (0.0f, 1.0f); if (_seed < _threshold) { anim.SetBool ("Back", true); } else if (_seed >= _threshold) { anim.SetBool ("Next", true); } } // 次の判定までインターバルを置く yield return new WaitForSeconds (_interval); } } } }
BeatItOtaku/Eclair2
Eclair2/Assets/UnityChanToonShader_v1.0.1 2/Assets/UnityChan/Scripts/IdleChanger.cs
C#
mit
3,416
package maidenhead import ( "math" "strings" "testing" ) // parsed locator must be translated to the same locator // using GridSquare() func TestParseLocator(t *testing.T) { var locTests = map[string]Point{ "JN88RT": Point{48.791667, 17.416667}, "JN89HF": Point{49.208333, 16.583333}, "JN58TD": Point{48.125000, 11.583333}, "GF15VC": Point{-34.916667, -56.250000}, "FM18LW": Point{38.916667, -77.083333}, "RE78IR": Point{-41.291667, 174.666667}, "PM45lm": Point{35.5, 128.916667}, } for loc, p := range locTests { point, err := ParseLocator(loc) if err != nil { t.Errorf("%s parsing error: %s", loc, err) continue } l, err := point.GridSquare() if err != nil { t.Errorf("%s: %v to GridSquare(): %s", loc, point, err) continue } if !strings.EqualFold(l, loc) { t.Errorf("%s: parsed to %v produces %s\n", loc, point, l) } if !(almostEqual(p.Latitude, point.Latitude) && almostEqual(p.Longitude, point.Longitude)) { t.Errorf("%s: at %s, expeted %s", loc, point, p) } } } func almostEqual(a, b float64) bool { return math.Abs(a-b) < 1e-06 }
pd0mz/go-maidenhead
parselocator_test.go
GO
mit
1,104
#include <pybind11/embed.h> #include <iostream> #include <string> namespace py = pybind11; #include "load_module.h" py::object LoadPyModuleFromFile(const char * file_path) { py::dict locals; locals["path"] = py::cast(file_path); py::eval<py::eval_statements>( // tell eval we're passing multiple statements "import importlib.util\n" "import os\n" "import sys\n" "module_name = os.path.basename(path)[:-3]\n" "try:\n" " new_module = sys.modules[module_name]\n" "except KeyError:\n" " spec = importlib.util.spec_from_file_location(module_name, path)\n" " new_module = importlib.util.module_from_spec(spec)\n" " spec.loader.exec_module(new_module)\n", py::globals(), locals); auto py_module = locals["new_module"]; return py_module; } py::object LoadPyModuleFromString(const char * content, const char * module_name, const char * module_file) { py::dict locals; locals["module_content"] = py::cast(content); locals["module_name"] = py::cast(module_name); locals["module_file"] = py::cast(module_file); py::object result = py::eval<py::eval_statements>( "import importlib.util\n" "import os\n" "import io\n" "import sys\n" "import tempfile\n" "try:\n" " new_module = sys.modules[module_name]\n" "except KeyError:\n" " t_fd, t_path = tempfile.mkstemp(suffix='.py', text=True)\n" " t_f = os.fdopen(t_fd, 'w')\n" " t_f.write(module_content)\n" " t_f.close()\n" " spec = importlib.util.spec_from_file_location(module_name, t_path)\n" " new_module = importlib.util.module_from_spec(spec)\n" " spec.loader.exec_module(new_module)\n" " os.remove(t_path)\n", py::globals(), locals); return locals["new_module"]; }
stonewell/wxglterm
src/utils/load_module.cpp
C++
mit
1,921
#include "Body.h" vec_f CalculateCenterOfMass(nz::BodyPart* polygon) { switch (polygon->Type) { case nz::ShapeType::Polygon: { vec_f com; auto poly = polygon->Polygon; int count = poly->Count(); for (int i = 0; i < count; ++i) { vec_f vertex = poly->At(i); com.X += vertex.X; com.Y += vertex.Y; } return com / count; } case nz::ShapeType::Rectangle: { return vec_f(polygon->Rectangle.X / 2, polygon->Rectangle.Y); } default: break; } return vec_f::Zero(); } nz::Body::Body() : Rotation(0), Velocity(vec_f::Zero()), CollisionHandler(nullptr), _position(vec_f::Zero()) {} nz::Body::Body(vec_f position, number_f rotation) : Rotation(rotation), Velocity(vec_f::Zero()), CollisionHandler(nullptr), _position(position) {} nz::Body::Body(vec_f position, number_f rotation, Thunk1<Body*>* const collisionHandler) : Rotation(rotation), Velocity(vec_f::Zero()), CollisionHandler(collisionHandler), _position(position) {} nz::Aabb nz::Body::GetBoundingBox() const { return _boundingBox; } nz::Aabb nz::Body::CalculateBoundingBox() const { auto returnable = _boundingBox; returnable.Min += CalculateWorldTranslation(); returnable.Max += CalculateWorldTranslation(); return returnable; } vec_f nz::Body::GetCenterOfMass() const { return _centerOfMass; } vec_f nz::Body::CalculateWorldTranslation() const { return _position + _centerOfMass; } void nz::Body::SetWorldTranslation(vec_f translation) { _position = translation - _centerOfMass; } void nz::Body::AttachBodyPart(std::shared_ptr<BodyPart> part) { Part = part; _centerOfMass = CalculateCenterOfMass(part.get()); // Realign the position. _position -= _centerOfMass; Aabb aabb; switch (Part->Type) { case ShapeType::Polygon: { auto poly = Part->Polygon; int count = poly->Count(); for (int i = 0; i < count; ++i) { auto calcPos = poly->At(i) + _centerOfMass; if (calcPos.X < aabb.Min.X) { aabb.Min.X = calcPos.X; } if (calcPos.Y < aabb.Min.Y) { aabb.Min.Y = calcPos.Y; } if (calcPos.X > aabb.Max.X) { aabb.Max.X = calcPos.X; } if (calcPos.Y > aabb.Max.Y) { aabb.Max.Y = calcPos.Y; } } break; } case ShapeType::Rectangle: { auto rect = Part->Rectangle; aabb.Min = _centerOfMass; aabb.Max = rect + _centerOfMass; break; } default: break; } _boundingBox = aabb; }
codeflowerblue/demo
GamePhysics/Body.cpp
C++
mit
2,371
module.exports = function(grunt) { grunt.initConfig({ sass: { // Task dist: { // Target files: { // Dictionary of files 'assets/stylesheets/styles.css': 'assets/stylesheets/src/styles.scss' , 'assets/stylesheets/smartphone.css': 'assets/stylesheets/src/smartphone.scss' } } }, watch: { css: { files: ['assets/stylesheets/src/*.scss'], tasks: ['sass', 'cssmin'] } }, cssmin: { target: { files: { 'assets/stylesheets/app.min.css': ['assets/stylesheets/styles.css', 'assets/stylesheets/smartphone.css'] } } } }); grunt.loadNpmTasks('grunt-contrib-sass'); grunt.loadNpmTasks('grunt-contrib-watch'); grunt.loadNpmTasks('grunt-contrib-cssmin'); grunt.registerTask('default', ['sass', 'cssmin', 'watch']); };
TejaswiR/mypsd2html
Gruntfile.js
JavaScript
mit
957
const test = require('tape'); const Mark = require('./../mark.js'); function stringArrayBuffer(str) { var buffer = new ArrayBuffer(str.length); var bytes = new Uint8Array(buffer); str.split('').forEach(function(str, i) { bytes[i] = str.charCodeAt(0); }); return buffer; } test('Stringify JSON object', function(assert) { assert.equal(Mark.stringify(Mark.parse(`{a:12.4, b:true, c:false, d:'str', e:null, g:1, h:[1,2,3], i:-12, j:[], k:{}, l:'', m:"", n:0, p:1e-2}`)), `{a:12.4 b:true c:false d:"str" e:null g:1 h:[1 2 3] i:-12 j:[] k:{} l:"" m:"" n:0 p:0.01}`, "Stringify JSON object"); assert.end() ; }); test('Stringify Mark object', function(assert) { assert.equal(Mark.stringify(Mark.parse('{obj}')), '{obj}', "Stringify {obj}"); assert.equal(Mark.stringify(Mark.parse('{div width:10}')), '{div width:10}', "Stringify {div width:10}"); assert.equal(Mark.stringify(Mark.parse('{div "text"}')), '{div "text"}', 'Stringify {div "text"}'); assert.equal(Mark.stringify(Mark.parse("{div 'text'}")), '{div "text"}', "Stringify {div 'text'}"); assert.equal(Mark.stringify(Mark.parse('{div {br}}')), '{div {br}}', "Stringify {div {br}}"); assert.equal(Mark.stringify(Mark.parse('{div width:null}')), '{div width:null}', "Stringify property with null value}"); // undefined value handling var t = {obj:undefined}; assert.equal(Mark.stringify(t), '{}', "Stringify undefined property"); assert.equal(Mark.stringify([1, null, undefined]), '[1 null null]', "Stringify undefined value in array"); // JSON inside Mark assert.equal(Mark.stringify(Mark.parse('{div {width:10}}')), '{div {width:10}}', "Stringify {div {width:10}}"); // stringify with identation assert.equal(Mark.stringify(Mark.parse('{div width:10 (!--comment--) "test" {br}}'), {space:' '}), '{div width:10 \n (!--comment--) \n "test" \n {br}\n}', "Stringify with identation"); // stringify omitting comma assert.equal(Mark.stringify(Mark.parse('{div width:10, height:"15px", margin:[5 10 10 5]}')), '{div width:10 height:"15px" margin:[5 10 10 5]}', "Stringify without comma"); // stringify base64 data assert.equal(Mark.stringify(stringArrayBuffer('Hello')), '[#SGVsbG8=]', "Stringify binary data 'hello'"); assert.equal(Mark.stringify(stringArrayBuffer('Hello worlds!')), '[#SGVsbG8gd29ybGRzIQ==]', "Stringify binary data 'Hello worlds!'"); var doc = Mark('doc', {mime:'text/html', data:stringArrayBuffer("<h1>Mark binary!</h1>")}); assert.equal(Mark.stringify(doc), '{doc mime:"text/html" data:[#PGgxPk1hcmsgYmluYXJ5ITwvaDE+]}', "Stringify nested binary data"); // stringify base85 data var bin = stringArrayBuffer('hello'); bin.encoding = 'a85'; assert.equal(Mark.stringify(bin), "[#~BOu!rDZ~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~\n@p\ns7\ntD.3~]")), "[#~@ps7tD.3~]", "Stringify base85"); assert.equal(Mark.stringify(Mark("[#~ @<5pm \rBfIs ~]")), "[#~@<5pmBfIs~]", "Parse base85 of 'ascii85'"); assert.end(); });
henry-luo/mark
test/stringify-mark.js
JavaScript
mit
3,018
const path = require(`path`) const chunk = require(`lodash/chunk`) // This is a simple debugging tool // dd() will prettily dump to the terminal and kill the process // const { dd } = require(`dumper.js`) /** * exports.createPages is a built-in Gatsby Node API. * It's purpose is to allow you to create pages for your site! 💡 * * See https://www.gatsbyjs.com/docs/node-apis/#createPages for more info. */ exports.createPages = async gatsbyUtilities => { // Query our posts from the GraphQL server const posts = await getNodes(gatsbyUtilities) // If there are no posts in WordPress, don't do anything if (!posts.length) { return } // If there are posts and pages, create Gatsby pages for them await createSinglePages({ posts, gatsbyUtilities }) // And a paginated archive await createBlogPostArchive({ posts, gatsbyUtilities }) } /** * This function creates all the individual blog pages in this site */ const createSinglePages = async ({ posts, gatsbyUtilities }) => Promise.all( posts.map(({ previous, post, next }) => // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info gatsbyUtilities.actions.createPage({ // Use the WordPress uri as the Gatsby page path // This is a good idea so that internal links and menus work 👍 path: post.uri, // use the blog post template as the page component component: path.resolve( `./src/templates/${post.__typename.replace(`Wp`, ``)}.js` ), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // we need to add the post id here // so our blog post template knows which blog post // the current page is (when you open it in a browser) id: post.id, // We also use the next and previous id's to query them and add links! previousPostId: previous ? previous.id : null, nextPostId: next ? next.id : null, }, }) ) ) /** * This function creates all the individual blog pages in this site */ async function createBlogPostArchive({ posts, gatsbyUtilities }) { const graphqlResult = await gatsbyUtilities.graphql(/* GraphQL */ ` { wp { readingSettings { postsPerPage } } } `) const { postsPerPage } = graphqlResult.data.wp.readingSettings const postsChunkedIntoArchivePages = chunk(posts, postsPerPage) const totalPages = postsChunkedIntoArchivePages.length return Promise.all( postsChunkedIntoArchivePages.map(async (_posts, index) => { const pageNumber = index + 1 const getPagePath = page => { if (page > 0 && page <= totalPages) { // Since our homepage is our blog page // we want the first page to be "/" and any additional pages // to be numbered. // "/blog/2" for example return page === 1 ? `/` : `/blog/${page}` } return null } // createPage is an action passed to createPages // See https://www.gatsbyjs.com/docs/actions#createPage for more info await gatsbyUtilities.actions.createPage({ path: getPagePath(pageNumber), // use the blog post archive template as the page component component: path.resolve(`./src/templates/blog-post-archive.js`), // `context` is available in the template as a prop and // as a variable in GraphQL. context: { // the index of our loop is the offset of which posts we want to display // so for page 1, 0 * 10 = 0 offset, for page 2, 1 * 10 = 10 posts offset, // etc offset: index * postsPerPage, // We need to tell the template how many posts to display too postsPerPage, nextPagePath: getPagePath(pageNumber + 1), previousPagePath: getPagePath(pageNumber - 1), }, }) }) ) } /** * This function queries Gatsby's GraphQL server and asks for * All WordPress blog posts. If there are any GraphQL error it throws an error * Otherwise it will return the posts 🙌 * * We're passing in the utilities we got from createPages. * So see https://www.gatsbyjs.com/docs/node-apis/#createPages for more info! */ async function getNodes({ graphql, reporter }) { const graphqlResult = await graphql(/* GraphQL */ ` query WpPosts { # Query all WordPress blog posts sorted by date allWpPost(sort: { fields: [date], order: DESC }) { edges { previous { id } # note: this is a GraphQL alias. It renames "node" to "post" for this query # We're doing this because this "node" is a post! It makes our code more readable further down the line. post: node { __typename id uri } next { id } } } allWpPage(sort: { fields: [date], order: DESC }) { edges { previous { id } # note: this is a GraphQL alias. It renames "node" to "post" for this query # We're doing this because this "node" is a post! It makes our code more readable further down the line. post: node { __typename id uri } next { id } } } } `) if (graphqlResult.errors) { reporter.panicOnBuild( `There was an error loading your blog posts`, graphqlResult.errors ) return } return [ ...graphqlResult.data.allWpPost.edges, ...graphqlResult.data.allWpPage.edges, ] }
gatsbyjs/gatsby
starters/gatsby-starter-wordpress-blog/gatsby-node.js
JavaScript
mit
5,757
'use strict'; // Call this function when the page loads (the "ready" event) $(document).ready(function() { initializePage(); }) /* * Function that is called when the document is ready. */ function initializePage() { $('.project a').click(addProjectDetails); $('#colorBtn').click(randomizeColors); $('#apibutton').click(getExternalApi); } /* * Make an AJAX call to retrieve project details and add it in */ function addProjectDetails(e) { // Prevent following the link e.preventDefault(); // Get the div ID, e.g., "project3" var projectID = $(this).closest('.project').attr('id'); // get rid of 'project' from the front of the id 'project3' var idNumber = projectID.substr('project'.length); console.log("User clicked on project " + idNumber); $.get('/project/' + idNumber, addProject); console.log('/project/' + idNumber); } function addProject(result) { console.log(result); var projectHTML = '<a href="#" class="thumbnail">' + '<img src="' + result['image'] + '" class="detalsImage">' + '<p>' + result['title'] + '</p>' + '<p> <small>' + result['date'] + '</small></p>' + '<p>' + result['summary'] + '</p> </a>'; $("#project" + result['id'] + " .details").html(projectHTML);
 } /* * Make an AJAX call to retrieve a color palette for the site * and apply it */ function randomizeColors(e) { e.preventDefault(); $.get('/palette', addColor); } function addColor(result) { console.log(result); var colors = result['colors']['hex']; $('body').css('background-color', colors[0]); $('.thumbnail').css('background-color', colors[1]); $('h1, h2, h3, h4, h5, h5').css('color', colors[2]); $('p').css('color', colors[3]); $('.project img').css('opacity', .75); } function getExternalApi(e) { e.preventDefault(); $.get('https://api.spotify.com/v1/artists/4dpARuHxo51G3z768sgnrY', getAPI); } function getAPI(result) { console.log(result); var images = result['images']; console.log(images); var adeleHTML = '<h1>' + result['name'] + '</h1>' + '<p> popularity: ' + result['popularity'] + '</p>' + '<p> genre: ' + result['genres'][0] + '</p>' + '<img src="' + images[2]['url'] + '"> <br />' ; $("#output").html(adeleHTML);
 }
daisy-aurora/lab6
public/js/introHCI.js
JavaScript
mit
2,197
using System.Collections.Generic; using Newtonsoft.Json; namespace Parse.Api.Models { // TODO GeoQueries /// <summary> /// Constraints are used for constructing precise queries. For usage, see the README. /// </summary> /// <seealso cref="http://parse.com/docs/rest#queries-constraints"/> public class Constraint { /// <summary> /// Used to find Parse objects that are less than the provided argument. /// </summary> [JsonProperty("$lt", NullValueHandling = NullValueHandling.Ignore)] public object LessThan { get; set; } /// <summary> /// Used to find Parse objects that are less than or equal to the provided argument. /// </summary> [JsonProperty("$lte", NullValueHandling = NullValueHandling.Ignore)] public object LessThanOrEqualTo { get; set; } /// <summary> /// Used to find Parse objects that are greater than the provided argument. /// </summary> [JsonProperty("$gt", NullValueHandling = NullValueHandling.Ignore)] public object GreaterThan { get; set; } /// <summary> /// Used to find Parse objects that are greater than or equal to the provided argument. /// </summary> [JsonProperty("$gte", NullValueHandling = NullValueHandling.Ignore)] public object GreaterThanOrEqualTo { get; set; } /// <summary> /// Used to find Parse objects that are not equal to the provided argument. /// </summary> [JsonProperty("$ne", NullValueHandling = NullValueHandling.Ignore)] public object NotEqualTo { get; set; } /// <summary> /// Used to find Parse objects that contain a value in the provided list of arguments. /// </summary> [JsonProperty("$in", NullValueHandling = NullValueHandling.Ignore)] public List<object> In { get; set; } /// <summary> /// Used to find Parse objects that do not contains values in the provided list of arguments. /// </summary> [JsonProperty("$nin", NullValueHandling = NullValueHandling.Ignore)] public List<object> NotIn { get; set; } /// <summary> /// Used to find Parse objects with an array field containing each of the values in the provided list of arguments. /// </summary> [JsonProperty("$all", NullValueHandling = NullValueHandling.Ignore)] public List<object> All { get; set; } /// <summary> /// Used to find Parse objects that have or do not have values for the specified property. /// </summary> [JsonProperty("$exists", NullValueHandling = NullValueHandling.Ignore)] public bool? Exists { get; set; } /// <summary> /// Used to find Parse objects that are related to other objects. /// </summary> [JsonProperty("$select", NullValueHandling = NullValueHandling.Ignore)] public object Select { get; set; } /// <summary> /// Used to find Parse objects that are related to other objects. /// </summary> [JsonProperty("$dontSelect", NullValueHandling = NullValueHandling.Ignore)] public object DontSelect { get; set; } /// <summary> /// Used to find Parse objects whose string value matches the provided Perl-based regex string. /// </summary> [JsonProperty("$regex", NullValueHandling = NullValueHandling.Ignore)] public string Regex { get; set; } /// <summary> /// Options used to control how the regex property matches values. /// Possible values for this include 'i' for a case-insensitive /// search and 'm' to search through multiple lines of text. To /// use both options, simply concatenate them as 'im'. /// </summary> [JsonProperty("$options", NullValueHandling = NullValueHandling.Ignore)] public string RegexOptions { get; set; } } }
aldenquimby/parse-csharp
Parse.Api/Models/Constraint.cs
C#
mit
4,098
using System; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; using Disty.Common.Contract.Distributions; using Disty.Common.Net.Http; using Disty.Service.Interfaces; using log4net; namespace Disty.Service.Endpoint.Http { public interface IDistributionListController : IController<DistributionList> { Task<IHttpActionResult> Delete(int id); Task<IHttpActionResult> Get(); Task<IHttpActionResult> Get(int id); Task<IHttpActionResult> Post(DistributionList item); } [AllowAnonymous] [RoutePrefix("api/distributionList")] public class DistributionListController : ApiController, IDistributionListController { private readonly IDistributionListService _service; private readonly ILog _log; public DistributionListController(ILog log, IDistributionListService service) { _log = log; _service = service; } [Route("")] public async Task<IHttpActionResult> Delete(int id) { try { await Task.Run(() => _service.DeleteAsync(id)); return Ok(); } catch (Exception ex) { _log.Error("Error creating email.", ex); return InternalServerError(new Exception("Unable to create email.")); } } [Route("")] [ResponseType(typeof (IEnumerable<DistributionList>))] public async Task<IHttpActionResult> Get() { try { var list = await Task.Run(() => _service.GetAsync()); if (list == null) { return NotFound(); } return Ok(list); } catch (Exception ex) { _log.Error("Error finding distribution list.", ex); return ResponseMessage(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } [Route("{id:int}", Name = "GetDistributionList")] [ResponseType(typeof (DistributionList))] public async Task<IHttpActionResult> Get(int id) { try { var list = await Task.Run(() => _service.GetAsync(id)); if (list == null) { return NotFound(); } return Ok(list); } catch (Exception ex) { _log.Error("Error finding distribution list.", ex); return ResponseMessage(new HttpResponseMessage(HttpStatusCode.InternalServerError)); } } [Route("")] public async Task<IHttpActionResult> Post(DistributionList item) { try { var id = await Task.Run(() => _service.SaveAsync(item)); if (id == 0) { return InternalServerError(new Exception("Unable to create distribution list.")); } return CreatedAtRoute<DistributionList>("GetDistributionList", new {id}, null); } catch (Exception ex) { _log.Error("Error creating distribution list.", ex); return InternalServerError(new Exception("Unable to create distribution list.")); } } } }
BryceAshey/Disty
Disty.Service.Endpoint.Http/DistributionListController.cs
C#
mit
3,534
package uk.ac.imperial.doc.pctmc.postprocessors.numerical; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import org.jfree.data.xy.XYDataset; import uk.ac.imperial.doc.jexpressions.constants.Constants; import uk.ac.imperial.doc.jexpressions.expressions.AbstractExpression; import uk.ac.imperial.doc.jexpressions.javaoutput.statements.AbstractExpressionEvaluator; import uk.ac.imperial.doc.pctmc.analysis.AbstractPCTMCAnalysis; import uk.ac.imperial.doc.pctmc.analysis.AnalysisUtils; import uk.ac.imperial.doc.pctmc.analysis.plotexpressions.PlotDescription; import uk.ac.imperial.doc.pctmc.charts.PCTMCChartUtilities; import uk.ac.imperial.doc.pctmc.utils.FileUtils; public abstract class NumericalPostprocessorCI extends NumericalPostprocessor { public NumericalPostprocessorCI(double stopTime, double stepSize) { super(stopTime, stepSize); } protected double[][][] absHalfCIWidth; protected List<PlotDescription> plotDescriptions; public void setPlotDescriptions(List<PlotDescription> plotDescriptions) { this.plotDescriptions = plotDescriptions; } @Override public final void postprocessAnalysis(Constants constants, AbstractPCTMCAnalysis analysis, List<PlotDescription> _plotDescriptions){ plotDescriptions = _plotDescriptions; prepare(analysis, constants); calculateDataPoints(constants); if (dataPoints!=null) { results = new LinkedHashMap<PlotDescription, double[][]>(); resultsCI = new LinkedHashMap<PlotDescription, double[][]>(); int index=0; for (PlotDescription pd:plotDescriptions) { double[][] ci = null; if (absHalfCIWidth!=null) { ci = absHalfCIWidth[index++]; resultsCI.put(pd, ci); } double[][] data = plotData(analysis.toString(), constants, ci, pd.getExpressions(), pd.getFilename()); results.put(pd, data); } } setResults(constants, _plotDescriptions); } public void setResults(Constants constants, List<PlotDescription> _plotDescriptions) { if (dataPoints!=null) { results = new LinkedHashMap<PlotDescription, double[][]>(); resultsCI = new LinkedHashMap<PlotDescription, double[][]>(); int index=0; for (PlotDescription pd:plotDescriptions) { double[][] ci = null; if (absHalfCIWidth!=null) { ci = absHalfCIWidth[index++]; resultsCI.put(pd, ci); } results.put(pd, evaluateExpressions(pd.getExpressions(), constants)); } } } protected Map<PlotDescription, double[][]> resultsCI; public Map<PlotDescription, double[][]> getResultsCI() { return resultsCI; } public double[][] plotData(String analysisTitle, Constants constants, double[][] dataCI, List<AbstractExpression> expressions, String filename) { if (dataCI == null) { return super.plotData(analysisTitle, constants, expressions, filename); } else { String[] names = new String[expressions.size()]; for (int i = 0; i < expressions.size(); i++) { names[i] = expressions.get(i).toString(); } double[][] data = evaluateExpressions(expressions, constants); XYDataset dataset = AnalysisUtils.getDatasetFromArray(data, dataCI, stepSize, names); PCTMCChartUtilities.drawDeviationChart(dataset, "time", "count", "", analysisTitle+this.toString()); if (filename != null && !filename.equals("")) { List<String> labels = new LinkedList<String>(); for (AbstractExpression e : expressions) { labels.add(e.toString()); } FileUtils.writeGnuplotFile(filename, "", labels, "time", "count"); FileUtils.writeCSVfile(filename, dataset); } return data; } } public double[] evaluateExpressions(AbstractExpressionEvaluator evaluator,final double[] data, int t, Constants constants){ //evaluator.setRates(constants.getFlatConstants()); double[] selectedData = new double[evaluator.getNumberOfExpressions()]; selectedData = evaluator.update(constants.getFlatConstants(),data, t * stepSize); return selectedData; } }
anton23/gpanalyser
src-pctmc/uk/ac/imperial/doc/pctmc/postprocessors/numerical/NumericalPostprocessorCI.java
Java
mit
3,999
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("09. TraverseDirectoryToXml")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09. TraverseDirectoryToXml")] [assembly: AssemblyCopyright("Copyright © 2015")] [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("dbbbd092-85b3-47b5-bdea-a869861dfd3b")] // 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")]
juvemar/Databases
02. XMLProcessingIn.NET/XML Processing in .NET/09. TraverseDirectoryToXml/Properties/AssemblyInfo.cs
C#
mit
1,428
 module app.shared { export interface IEntityService<T extends IEntity> { post : (entity : T) => ng.IPromise<T>; } }
olofd/bokaettband
FrontEnd/app/shared/services/IEntityService.ts
TypeScript
mit
139
'use strict'; const path = require('path'); const srcDir = path.join(__dirname, 'src/front'), distDir = path.join(__dirname, 'front/dist'); module.exports = { envFilePath: path.join(__dirname, '.env'), src: { front: { jsEntry: path.join(srcDir, 'js/index.js'), htmlEntry: path.join(srcDir, 'index.html'), stylesEntry: path.join(srcDir, 'scss/style.scss') } }, dist: { buildDir: path.join(distDir, 'build'), releaseDir: path.join(distDir, 'release') } };
raccoon-app/ui-kit
layout.js
JavaScript
mit
553
import test from 'ava'; import React from 'react'; import { shallow } from 'enzyme'; import Text from '../../../src/components/form-inputs/text'; test('Text | default props', (t) => { const textWrapper = shallow(<Text />); t.deepEqual(textWrapper.props(), { type: 'text', 'data-form-id': '', className: '', id: '', placeholder: '', required: false, value: '', min: -1, max: -1, }); }); test('Text | all props filled', (t) => { const textWrapper = shallow( <Text className="test-class" data-form-id="test-form-id" id="test-id" placeholder="test-placeholder" required value="test-value" min={8} max={30} />, ); t.deepEqual(textWrapper.props(), { type: 'text', 'data-form-id': 'test-form-id', className: 'test-class', id: 'test-id', placeholder: 'test-placeholder', required: true, value: 'test-value', min: 8, max: 30, }); });
aichbauer/redux-valid-form
test/components_test/form-inputs/text.js
JavaScript
mit
972
/** * mobservable * (c) 2015 - Michel Weststrate * https://github.com/mweststrate/mobservable */ namespace mobservable { export namespace _ { export function throwingViewSetter() { throw new Error(`[mobservable.view '${this.context.name}'] View functions do not accept new values`); } export class ObservableView<T> extends ViewNode { private isComputing = false; private hasError = false; protected _value: T; protected changeEvent = new SimpleEventEmitter(); constructor(protected func:()=>T, private scope: Object, context:Mobservable.IContextInfoStruct, private compareStructural) { super(context); } get():T { if (this.isComputing) throw new Error(`[mobservable.view '${this.context.name}'] Cycle detected`); if (this.isSleeping) { if (_.isComputingView()) { // somebody depends on the outcome of this computation this.wakeUp(); // note: wakeup triggers a compute this.notifyObserved(); } else { // nobody depends on this computable; // so just compute fresh value and continue to sleep this.wakeUp(); this.tryToSleep(); } } else { // we are already up to date, somebody is just inspecting our current value this.notifyObserved(); } if (this.hasCycle) throw new Error(`[mobservable.view '${this.context.name}'] Cycle detected`); if (this.hasError) { if (logLevel > 0) console.error(`[mobservable.view '${this.context.name}'] Rethrowing caught exception to observer: ${this._value}${(<any>this._value).cause||''}`); throw this._value; } return this._value; } set() { throwingViewSetter.call(this); } compute() { var newValue:T; try { // this cycle detection mechanism is primarily for lazy computed values; other cycles are already detected in the dependency tree if (this.isComputing) throw new Error(`[mobservable.view '${this.context.name}'] Cycle detected`); this.isComputing = true; newValue = this.func.call(this.scope); this.hasError = false; } catch (e) { this.hasError = true; console.error(`[mobservable.view '${this.context.name}'] Caught error during computation: `, e, "View function:", this.func.toString()); console.trace(); if (e instanceof Error) newValue = e; else { newValue = <T><any> new Error(`[mobservable.view '${this.context.name}'] Error during computation (see error.cause) in ` + this.func.toString()); (<any>newValue).cause = e; } } this.isComputing = false; const changed = this.compareStructural ? !deepEquals(newValue, this._value) : newValue !== this._value; if (changed) { var oldValue = this._value; this._value = newValue; this.changeEvent.emit(newValue, oldValue); return true; } return false; } observe(listener:(newValue:T, oldValue:T)=>void, fireImmediately=false):Lambda { this.setRefCount(+1); // awake if (fireImmediately) listener(this.get(), undefined); var disposer = this.changeEvent.on(listener); return once(() => { this.setRefCount(-1); disposer(); }); } asPropertyDescriptor(): PropertyDescriptor { return { configurable: false, enumerable: false, get: () => this.get(), set: throwingViewSetter } } toString() { return `ComputedObservable[${this.context.name}:${this._value}] ${this.func.toString()}`; } } } }
sandals/mobservable
lib/observableview.ts
TypeScript
mit
4,707
/* * This file is part of Mixin, licensed under the MIT License (MIT). * * Copyright (c) SpongePowered <https://www.spongepowered.org> * Copyright (c) contributors * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package org.spongepowered.tools.obfuscation.struct; import javax.annotation.processing.Messager; import javax.lang.model.element.AnnotationMirror; import javax.lang.model.element.AnnotationValue; import javax.lang.model.element.Element; import javax.tools.Diagnostic; /** * Wrapper for Annotation Processor messages, used to enable messages to be * easily queued and manipulated */ public class Message { private Diagnostic.Kind kind; private CharSequence msg; private final Element element; private final AnnotationMirror annotation; private final AnnotationValue value; public Message(Diagnostic.Kind kind, CharSequence msg) { this(kind, msg, null, null, null); } public Message(Diagnostic.Kind kind, CharSequence msg, Element element) { this(kind, msg, element, null, null); } public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation) { this(kind, msg, element, annotation, null); } public Message(Diagnostic.Kind kind, CharSequence msg, Element element, AnnotationMirror annotation, AnnotationValue value) { this.kind = kind; this.msg = msg; this.element = element; this.annotation = annotation; this.value = value; } public Message sendTo(Messager messager) { if (this.value != null) { messager.printMessage(this.kind, this.msg, this.element, this.annotation, this.value); } else if (this.annotation != null) { messager.printMessage(this.kind, this.msg, this.element, this.annotation); } else if (this.element != null) { messager.printMessage(this.kind, this.msg, this.element); } else { messager.printMessage(this.kind, this.msg); } return this; } public Diagnostic.Kind getKind() { return this.kind; } public Message setKind(Diagnostic.Kind kind) { this.kind = kind; return this; } public CharSequence getMsg() { return this.msg; } public Message setMsg(CharSequence msg) { this.msg = msg; return this; } public Element getElement() { return this.element; } public AnnotationMirror getAnnotation() { return this.annotation; } public AnnotationValue getValue() { return this.value; } }
simon816/Mixin
src/ap/java/org/spongepowered/tools/obfuscation/struct/Message.java
Java
mit
3,695
<?php if (! defined('BASEPATH')) exit('No direct script access allowed'); class User extends MY_CONTROLLER { public function logout() { $this->logoutCurrentUser(); $this->index(); } public function newUser() { $this->data['active_page'] = ""; $this->data['title'] = 'Utilizator nou'; $this->loadView('new_user_view'); } public function addNewUser() { $userData = $this->getAddNewUserData(); if (md5($this->input->post('conf-password')) != $userData['password']) { $this->data['error'] = 'Confirmarea parolei nu a fost corecta.'; $this->newUser(); return; } if ($this->user_model->emailExists($userData['email'])) { $this->data['error'] = 'Acest email este deja folosit pentru un utilizator.'; $this->newUser(); return; } if ($this->user_model->userExists($userData['username'])) { $this->data['error'] = 'Acest nume de utilizator este deja folosit.'; $this->newUser(); return; } $userCount = count($this->user_model->getUserByName($userData['username'])); if ($userCount == 0) { $this->data['error'] = ''; $userData['user_id'] = $this->user_model->insert($userData); $this->loginUser($userData); $this->index(); } else { $this->data['error'] = 'Nume de utilizator folosit'; $this->newUser(); } } public function login() { $this->data['active_page'] = ""; $this->data['title'] = 'Autentificare'; $this->loadView('user_login_view'); } public function submitLogin() { $userData = $this->getUserLoginData(); $userId = $this->user_model->getUserId($userData); if ($userId != 0) { $this->data['error'] = ""; $userData['user_id'] = $userId; $this->loginUser($userData); $this->index(); } else { $this->data['error'] = "Ati gresiti datele de autentificare."; $this->login(); } } public function newAdvert() { if ($this->checkIfUserDataIsSet()) { $this->data['active_page'] = "newAdvert"; $this->data['title'] = "Anunt nou"; $this->session->set_userdata('advert_guid', uniqid()); $this->loadView('add_new_advert_view'); } else { $this->data['error'] = 'Va rugam sa va autentificati pentru a posta un anunt.'; $this->login(); } } private function loginUser($userData) { $this->session->set_userdata('username', $userData['username']); $this->session->set_userdata('user_id', $userData['user_id']); $this->session->set_userdata('is_logged', TRUE); } private function getAddNewUserData() { return array( 'username' => $this->input->post('username'), 'password' => md5($this->input->post('password')), 'email' => $this->input->post('email'), 'fullname' => $this->input->post('fullname'), 'city' => $this->input->post('city'), 'district' => $this->input->post('district'), // TODO: Regex for phone. 'phone' => $this->input->post('phone') ); } private function getUserLoginData() { return array( 'username' => $this->input->post('username'), 'password' => md5($this->input->post('password')) ); } }
uaandrei/Ann
anunturi/controllers/user.php
PHP
mit
3,621
/* jquery.flipper (c) MrKMG 2012 */ (function( $ ){ var methods = { init : function( o ) { return this.each(function(){ var $this = $(this), data = $this.data('flipper'), text = $this.text(); // If the plugin hasn't been initialized yet if ( ! data ) { var options = $.extend({ type:'fall', speed:'normal', queueSuper:true },o); $this .addClass('flipper') .addClass('fl-animate') .addClass('fl-'+options.type) .addClass('fl-'+options.speed); $this.css('line-height',($this.height()+1)+'px') var new1 = $('<span class="fl-new fl-top fl-num"></span>'); var new2 = $('<span class="fl-new fl-bottom fl-num"></span>'); var cur1 = $('<span class="fl-show fl-top fl-num">'+text+'</span>'); var cur2 = $('<span class="fl-show fl-bottom fl-num">'+text+'</span>'); $this.html('').append(new1,new2,cur1,cur2); $this.data('flipper', { new1:new1, new2:new2, cur1:cur1, cur2:cur2, type:options.type, speed:options.speed, queueSuper:options.queueSuper, running:false, insuper:false, presuperspeed:null, queue:[] }); } }); }, destroy : function( ) { return this.each(function(){ var $this = $(this), data = $this.data('flipper'); data.flipper.remove(); $this.removeData('flipper'); }); }, option:function(key,val){ if(key=="speed"){ var $this = $(this), o = $this.data().flipper; var oldspeed = o.speed; o.speed = val; $this.removeClass('fl-'+oldspeed).addClass('fl-'+val); $this.data('flipper',o); return true; } else if(key=="type"){ var $this = $(this), o = $this.data().flipper; var oldtype = o.type; o.type = val; $this.removeClass('fl-'+oldtype).addClass('fl-'+val); $this.data('flipper',o); return true; } else { return false; } }, update: function( newtext, callback ) { var $this = $(this); var o = $this.data().flipper; if(o.running){ o.queue.push([newtext,callback]); $this.data('flipper',o); return; }else{ o.running = true; methods._process(this,newtext,callback); } }, _process:function(obj,newtext,callback){ var $this = $(obj); var o = $this.data().flipper; $this.data('flipper',o); console.log(o.insuper,o.queue.length); if(o.queueSuper &&!o.insuper && o.queue.length){ var oldspeed = o.speed; o.speed = 'super'; $this.removeClass('fl-'+oldspeed).addClass('fl-super'); o.oldspeed = oldspeed; o.insuper = true; $this.data('flipper',o); }else if(o.queueSuper && o.insuper && !o.queue.length){ o.speed = o.oldspeed; $this.removeClass('fl-super').addClass('fl-'+o.speed); o.insuper = false; $this.data('flipper',o); } setTimeout(function(){ animators[o.type](obj,newtext,function(){ if(o.queue.length){ var q = o.queue.shift(); setTimeout(function(){methods._process(obj,q[0],q[1]);},1); if(typeof(callback) == 'function') callback(false); }else{ if(typeof(callback) == 'function') callback(true); o.running = false; $this.data('flipper',o); } }); },1); }, clearqueue: function(){ var $this = $(this); var o = $this.data().flipper; o.queue.length = 0; $this.data('flipper',o); } }; var animators = { fall:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, rise:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, clap:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(o.cur2.text()); o.cur2.text(newtext); if(o.speed=='slow') var t = 2000; else if(o.speed=='normal') var t = 1000; else if(o.speed=='fast') var t = 500; else if(o.speed=='super') var t = 50; setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t); }, slide:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } setTimeout(function(){ $this.removeClass('fl-go').addClass('fl-zfix'); o.cur2.text(newtext); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.new1.text(''); $this.removeClass('fl-zfix'); finished(); },t1); }, open:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(newtext); o.new2.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } setTimeout(function(){ $this.addClass('fl-zfix'); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go').removeClass('fl-zfix'); finished(); },t1); }, close:function(obj,newtext,finished){ var $this = $(obj); var o = $this.data().flipper; $this.addClass('fl-animate'); $this.addClass('fl-go'); o.new1.text(o.cur1.text()); o.new2.text(o.cur2.text()); o.cur1.text(newtext); o.cur2.text(newtext); if(o.speed=='slow'){ var t1 = 2000; var t2 = 1000; } else if(o.speed=='normal'){ var t1 = 1000; var t2 = 500; } else if(o.speed=='fast'){ var t1 = 500; var t2 = 250; } else if(o.speed=='super'){ var t1 = 50; var t2 = 25; } $this.addClass('fl-zfix'); setTimeout(function(){ $this.removeClass('fl-zfix'); },t2); setTimeout(function(){ $this.removeClass('fl-animate'); o.cur1.text(newtext); o.cur2.text(newtext); o.new1.text(''); o.new2.text(''); $this.removeClass('fl-go'); finished(); },t1); } }; $.fn.flipper = function( method ) { if ( methods[method] ) { return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if ( typeof method === 'object' || ! method ) { return methods.init.apply( this, arguments ); } else { $.error( 'Method ' + method + ' does not exist on jQuery.flipper' ); } }; })( jQuery );
mrkmg/jquery.flipper
jquery.flipper.js
JavaScript
mit
9,843
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // 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. // #endregion using System.Globalization; namespace DbLinq.Language { /// <summary> /// Languages factory /// </summary> internal interface ILanguages { /// <summary> /// Loads the specified language related to given culture info. /// </summary> /// <param name="cultureInfo">The culture info.</param> /// <returns></returns> ILanguageWords Load(CultureInfo cultureInfo); } }
lytico/dblinq2007
src/DbLinq/Language/ILanguages.cs
C#
mit
1,629
from __future__ import unicode_literals from django.apps import AppConfig class DevelopersConfig(AppConfig): name = 'developers'
neldom/qessera
developers/apps.py
Python
mit
136
define(['exports', 'aurelia-validation', 'aurelia-dependency-injection', './orm-metadata'], function (exports, _aureliaValidation, _aureliaDependencyInjection, _ormMetadata) { 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Entity = undefined; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _dec, _dec2, _class; var Entity = exports.Entity = (_dec = (0, _aureliaDependencyInjection.transient)(), _dec2 = (0, _aureliaDependencyInjection.inject)(_aureliaValidation.Validation), _dec(_class = _dec2(_class = function () { function Entity(validator) { _classCallCheck(this, Entity); this.define('__meta', _ormMetadata.OrmMetadata.forTarget(this.constructor)).define('__cleanValues', {}, true); if (!this.hasValidation()) { return this; } return this.define('__validator', validator); } Entity.prototype.getTransport = function getTransport() { return this.getRepository().getTransport(); }; Entity.prototype.getRepository = function getRepository() { return this.__repository; }; Entity.prototype.setRepository = function setRepository(repository) { return this.define('__repository', repository); }; Entity.prototype.define = function define(property, value, writable) { Object.defineProperty(this, property, { value: value, writable: !!writable, enumerable: false }); return this; }; Entity.prototype.getMeta = function getMeta() { return this.__meta; }; Entity.prototype.save = function save() { var _this = this; if (!this.isNew()) { return this.update(); } var response = void 0; return this.getTransport().create(this.getResource(), this.asObject(false)).then(function (created) { _this.id = created.id; response = created; }).then(function () { return _this.saveCollections(); }).then(function () { return _this.markClean(); }).then(function () { return response; }); }; Entity.prototype.update = function update() { var _this2 = this; if (this.isNew()) { throw new Error('Required value "id" missing on entity.'); } if (this.isClean()) { return this.saveCollections().then(function () { return _this2.markClean(); }).then(function () { return null; }); } var requestBody = this.asObject(false); var response = void 0; delete requestBody.id; return this.getTransport().update(this.getResource(), this.id, requestBody).then(function (updated) { return response = updated; }).then(function () { return _this2.saveCollections(); }).then(function () { return _this2.markClean(); }).then(function () { return response; }); }; Entity.prototype.addCollectionAssociation = function addCollectionAssociation(entity, property) { var _this3 = this; property = property || getPropertyForAssociation(this, entity); var url = [this.getResource(), this.id, property]; if (this.isNew()) { throw new Error('Cannot add association to entity that does not have an id.'); } if (!(entity instanceof Entity)) { url.push(entity); return this.getTransport().create(url.join('/')); } if (entity.isNew()) { var associationProperty = getPropertyForAssociation(entity, this); var relation = entity.getMeta().fetch('association', associationProperty); if (!relation || relation.type !== 'entity') { return entity.save().then(function () { return _this3.addCollectionAssociation(entity, property); }); } entity[associationProperty] = this.id; return entity.save().then(function () { return entity; }); } url.push(entity.id); return this.getTransport().create(url.join('/')).then(function () { return entity; }); }; Entity.prototype.removeCollectionAssociation = function removeCollectionAssociation(entity, property) { property = property || getPropertyForAssociation(this, entity); var idToRemove = entity; if (entity instanceof Entity) { if (!entity.id) { return Promise.resolve(null); } idToRemove = entity.id; } return this.getTransport().destroy([this.getResource(), this.id, property, idToRemove].join('/')); }; Entity.prototype.saveCollections = function saveCollections() { var _this4 = this; var tasks = []; var currentCollections = getCollectionsCompact(this, true); var cleanCollections = this.__cleanValues.data ? this.__cleanValues.data.collections : null; var addTasksForDifferences = function addTasksForDifferences(base, candidate, method) { if (base === null) { return; } Object.getOwnPropertyNames(base).forEach(function (property) { base[property].forEach(function (id) { if (candidate === null || !Array.isArray(candidate[property]) || candidate[property].indexOf(id) === -1) { tasks.push(method.call(_this4, id, property)); } }); }); }; addTasksForDifferences(currentCollections, cleanCollections, this.addCollectionAssociation); addTasksForDifferences(cleanCollections, currentCollections, this.removeCollectionAssociation); return Promise.all(tasks).then(function (results) { return _this4; }); }; Entity.prototype.markClean = function markClean() { var cleanValues = getFlat(this, false, false); this.__cleanValues = { checksum: JSON.stringify(cleanValues), data: cleanValues }; return this; }; Entity.prototype.isClean = function isClean() { return getFlat(this, true, false) === this.__cleanValues.checksum; }; Entity.prototype.isDirty = function isDirty() { return !this.isClean(); }; Entity.prototype.isNew = function isNew() { return typeof this.id === 'undefined'; }; Entity.getResource = function getResource() { return _ormMetadata.OrmMetadata.forTarget(this).fetch('resource'); }; Entity.prototype.getResource = function getResource() { return this.__resource || this.getMeta().fetch('resource'); }; Entity.prototype.setResource = function setResource(resource) { return this.define('__resource', resource); }; Entity.prototype.destroy = function destroy() { if (!this.id) { throw new Error('Required value "id" missing on entity.'); } return this.getTransport().destroy(this.getResource(), this.id); }; Entity.prototype.getName = function getName() { var metaName = this.getMeta().fetch('name'); if (metaName) { return metaName; } return this.getResource(); }; Entity.getName = function getName() { var metaName = _ormMetadata.OrmMetadata.forTarget(this).fetch('name'); if (metaName) { return metaName; } return this.getResource(); }; Entity.prototype.setData = function setData(data) { Object.assign(this, data); return this; }; Entity.prototype.enableValidation = function enableValidation() { if (!this.hasValidation()) { throw new Error('Entity not marked as validated. Did you forget the @validation() decorator?'); } if (this.__validation) { return this; } return this.define('__validation', this.__validator.on(this)); }; Entity.prototype.getValidation = function getValidation() { if (!this.hasValidation()) { return null; } if (!this.__validation) { this.enableValidation(); } return this.__validation; }; Entity.prototype.hasValidation = function hasValidation() { return !!this.getMeta().fetch('validation'); }; Entity.prototype.asObject = function asObject(shallow) { return _asObject(this, shallow); }; Entity.prototype.asJson = function asJson(shallow) { return _asJson(this, shallow); }; return Entity; }()) || _class) || _class); function _asObject(entity, shallow) { var pojo = {}; var metadata = entity.getMeta(); Object.keys(entity).forEach(function (propertyName) { var value = entity[propertyName]; var association = metadata.fetch('associations', propertyName); if (!association || !value) { pojo[propertyName] = value; return; } if (shallow) { if (association.type === 'collection') { return; } if (value.id) { pojo[propertyName] = value.id; } else if (value instanceof Entity) { pojo[propertyName] = value.asObject(); } else if (['string', 'number', 'boolean'].indexOf(typeof value === 'undefined' ? 'undefined' : _typeof(value)) > -1 || value.constructor === Object) { pojo[propertyName] = value; } return; } if (!Array.isArray(value)) { pojo[propertyName] = !(value instanceof Entity) ? value : value.asObject(shallow); return; } var asObjects = []; value.forEach(function (childValue) { if ((typeof childValue === 'undefined' ? 'undefined' : _typeof(childValue)) !== 'object') { return; } if (!(childValue instanceof Entity)) { asObjects.push(childValue); return; } if (!shallow || (typeof childValue === 'undefined' ? 'undefined' : _typeof(childValue)) === 'object' && !childValue.id) { asObjects.push(childValue.asObject(shallow)); } }); if (asObjects.length > 0) { pojo[propertyName] = asObjects; } }); return pojo; } function _asJson(entity, shallow) { var json = void 0; try { json = JSON.stringify(_asObject(entity, shallow)); } catch (error) { json = ''; } return json; } function getCollectionsCompact(forEntity, includeNew) { var associations = forEntity.getMeta().fetch('associations'); var collections = {}; Object.getOwnPropertyNames(associations).forEach(function (index) { var association = associations[index]; if (association.type !== 'collection') { return; } collections[index] = []; if (!Array.isArray(forEntity[index])) { return; } forEntity[index].forEach(function (entity) { if (typeof entity === 'number') { collections[index].push(entity); return; } if (entity.id) { collections[index].push(entity.id); } else if (includeNew && entity instanceof Entity) { collections[index].push(entity); } }); }); return collections; } function getFlat(entity, json, shallow) { var flat = { entity: _asObject(entity, !!shallow), collections: getCollectionsCompact(entity) }; if (json) { flat = JSON.stringify(flat); } return flat; } function getPropertyForAssociation(forEntity, entity) { var associations = forEntity.getMeta().fetch('associations'); return Object.keys(associations).filter(function (key) { return associations[key].entity === entity.getResource(); })[0]; } });
kellyethridge/aurelia-orm
dist/amd/entity.js
JavaScript
mit
11,971
<?php function ulepsz($gracz, $id,$kolejka_technologii){ //zabezpiecz zmienne $id = (int)$id; $tech = mysql_fetch_array(mysql_query("select tt.technologia, tt.drewno as drewno1, ttm.drewno as drewno2, tt.kamien as kamien1, ttm.kamien as kamien2, tt.zelazo as zelazo1, ttm.zelazo as zelazo2, tt.jedzenie as jedzenie1, ttm.jedzenie as jedzenie2, tt.czas_rozwoju as czas_rozwoju1, ttm.czas_rozwoju as czas_rozwoju2, tt.nazwa, ttm.poziom, tt.max_poziom, (select koniec - ".time()." from tribal_eventy where typ = 2 and podtyp = tt.technologia and miasto_id = ".$gracz['id_miasta'].") as w_kolejce from tribal_technologie tt left join tribal_technologie_miasta ttm on tt.technologia = ttm.technologia_id and ttm.miasto_id = ".$gracz['id_miasta']." where tt.technologia = ".$id." limit 1 ")); if(empty($tech)){ $error = "nie ma takiego obiektu"; } else { if(!empty($tech['poziom'])){ $tech['drewno1'] = $tech['drewno2']; $tech['kamien1'] = $tech['kamien2']; $tech['zelazo1'] = $tech['zelazo2']; $tech['jedzenie1'] = $tech['jedzenie2']; $tech['czas_rozwoju1'] = $tech['czas_rozwoju2']; } else $tech['poziom'] = 0; if( ($tech['drewno1'] > $gracz['dane_miasta']['drewno']) || ($tech['kamien1'] > $gracz['dane_miasta']['kamien']) || ($tech['zelazo1'] > $gracz['dane_miasta']['zelazo']) || ($tech['jedzenie1'] > $gracz['dane_miasta']['jedzenie']) ){ $error = "nie masz wystarczającej ilości surowców"; } elseif($tech['poziom'] == $tech['max_poziom']) { $error = "osiągnięto maksymalny poziom"; } elseif($kolejka == $kolejka_technologii){ $error ="kolejka zajęta"; } elseif(!empty($tech['w_kolejce'])){ $error ="rozwijasz tą naukę"; } else { //dodaj event require_once('dodaj_event.php'); dodaj_event($gracz['id_miasta'], 2, $id, 1, $tech['czas_rozwoju1']); require_once('surowce.php'); surowce($gracz['id_miasta'], -$tech['drewno1'], -$tech['kamien1'], -$tech['zelazo1'], -$tech['jedzenie1'], 0); //zabierz surowce $error = "rozpoczęto budowę"; } } return $error; } ?>
WlasnaGra/Tribal2
funkcje/ulepsz.php
PHP
mit
2,105
using System; namespace Cofoundry.Domain.Data { /// <summary> /// Used when a Sql Stored Procedure executes without error, but does not /// return the expected result e.g. when an output parameter should have /// always have a value, but does not. /// </summary> public class UnexpectedStoredProcedureResultException : Exception { const string DEFAULT_MESSAGE = "An error occurred calling stored procedure {0}. {1}"; public UnexpectedStoredProcedureResultException(string storedProcedureName) : base(string.Format(DEFAULT_MESSAGE, storedProcedureName, "An unexpected result was returned.")) { } public UnexpectedStoredProcedureResultException(string storedProcedureName, string message) : base(string.Format(DEFAULT_MESSAGE, storedProcedureName, message)) { } } }
cofoundry-cms/cofoundry
src/Cofoundry.Domain/Data/Exceptions/UnexpectedStoredProcedureResultException.cs
C#
mit
882
var detailSelector = function() { return { restrict: 'E', scope : { items: '=', selectedItem: '=' }, replace: true, templateUrl: 'js/directives/detailSelector.html', link: function (scope, element, attrs) { scope.updateCurrentItem = function(value) { scope.selectedItem = value; }; } }; } module.exports = detailSelector;
knutator2/Rolling-Stone
js/directives/detailSelector.js
JavaScript
mit
451
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Factorio_Mod_Manager { public partial class DownloadPrompt : Form { private Action cb; private Action deniedCallback = () => { }; public DownloadPrompt() { InitializeComponent(); AcceptButton = button2; } public void SetText(string s) { label1.Text = s; } public void SetTitle(string s) { Text = s; } public void SetFinishedCallback(Action callback) { cb = callback; } public void SetDeniedCallback(Action callback) { deniedCallback = callback; } private void button2_Click(object sender, EventArgs e) { cb(); Close(); } private void button1_Click(object sender, EventArgs e) { deniedCallback(); Close(); } } }
Danacus/FactorioModManager
Factorio Mod Manager/DownloadPrompt.cs
C#
mit
1,202
""" Contains all elements of this package. They act as the formal elements of the law. """ import json import sys def from_json(data): """ Reconstructs any `BaseElement` from its own `.as_json()`. Returns the element. """ def _decode(data_dict): values = [] if isinstance(data_dict, str): return data_dict assert(len(data_dict) == 1) klass_string = next(iter(data_dict.keys())) klass = getattr(sys.modules[__name__], klass_string) args = [] for e in data_dict[klass_string]: x = _decode(e) if isinstance(x, str): args.append(x) else: args += x values.append(klass(*args)) return values return _decode(json.loads(data))[0] class BaseElement(object): """ Defines the interface of all elements. """ def as_html(self): """ How the element converts itself to HTML. """ raise NotImplementedError def as_str(self): """ How the element converts itself to simple text. """ raise NotImplementedError def as_dict(self): """ How the element converts itself to a dictionary. """ raise NotImplementedError def as_json(self): """ How the element converts itself to JSON. Not to be overwritten. """ return json.dumps(self.as_dict()) def __repr__(self): return '<%s %s>' % (self.__class__.__name__, repr(self.as_str())) def __eq__(self, other): if isinstance(other, self.__class__): return self.as_dict() == other.as_dict() else: return False @staticmethod def _build_html(tag, text, attrib): text = text.replace('\n', '') # \n have no meaning in HTML if not text: # ignore empty elements return '' attributes = ' '.join('%s="%s"' % (key, value) for (key, value) in sorted(attrib.items()) if value is not None) if attributes: attributes = ' ' + attributes return '<{0}{1}>{2}</{0}>'.format(tag, attributes, text) class Token(BaseElement): """ A simple string. """ def __init__(self, string): assert isinstance(string, str) self._string = string def as_str(self): return self.string def as_html(self): return self.as_str() def as_dict(self): return {self.__class__.__name__: [self.as_str()]} @property def string(self): return self._string class Reference(Token): """ A generic reference to anything. Contains a number (str) and a parent, which must be either `None` or a `Token` (or a subclass of `Token`). """ def __init__(self, number, parent=None): super(Reference, self).__init__(number) assert isinstance(number, str) assert isinstance(parent, Token) or parent is None self._parent = parent def __repr__(self): return '<%s %s %s>' % (self.__class__.__name__, repr(self.number), repr(self.parent)) def as_html(self): return self._build_html('a', self.as_str(), {}) def as_dict(self): r = {self.__class__.__name__: [self.number]} if self.parent: r[self.__class__.__name__].append(self.parent.as_dict()) return r @property def number(self): return self.string @property def parent(self): return self._parent class DocumentReference(Reference): """ A concrete Reference to a document. Contains an href that identifies where it points to, as well as a `set_href` to set it. """ def __init__(self, number, parent, href=''): super(DocumentReference, self).__init__(number, parent) self._href = href def __repr__(self): return '<%s %s %s>' % (self.__class__.__name__, repr(self.as_str()), repr(self.parent.as_str())) @property def name(self): return self.parent.as_str() def set_href(self, href): self._href = href def as_html(self): if self._href: return self._build_html('a', self.as_str(), {'href': self._href}) return super(DocumentReference, self).as_html() def as_dict(self): r = super(DocumentReference, self).as_dict() if self._href: r[self.__class__.__name__].append(self._href) return r class LineReference(Reference): pass class NumberReference(Reference): pass class ArticleReference(Reference): pass class EULawReference(Reference): """ A reference to EU law. Its href is built from its name and number. """ @staticmethod def _build_eu_url(name, number): # example: '2000/29/CE' year, iden = number.split('/')[:2] label = {'Diretiva': 'L', 'Decisão de Execução': 'D', 'Regulamento (CE)': 'R', 'Regulamento CE': 'R', 'Regulamento CEE': 'R'}[name] if label == 'R': year, iden = iden, year eur_id = '3%s%s%04d' % (year, label, int(iden)) return 'http://eur-lex.europa.eu/legal-content/PT/TXT/?uri=CELEX:%s' \ % eur_id def __init__(self, number, parent): super(EULawReference, self).__init__(number, parent) def as_html(self): return self._build_html('a', self.as_str(), {'href': self._build_eu_url(self.parent.as_str(), self.number)}) class Anchor(Token): """ A generic anchor that defines a section that can be referred to. """ name = None def __init__(self, string): super(Anchor, self).__init__(string) self._document_section = None def as_str(self): return '%s %s\n' % (self.name, self.number) def as_dict(self): return {self.__class__.__name__: [self.number]} @property def number(self): return self.string @property def format(self): return self.__class__ @property def reference(self): return self._document_section @reference.setter def reference(self, document_section): assert(isinstance(document_section, DocumentSection)) self._document_section = document_section def ref_as_href(self): if self.reference.id_as_html(): return '#' + self.reference.id_as_html() else: return None class Section(Anchor): name = 'Secção' class SubSection(Anchor): name = 'Sub-Secção' class Clause(Anchor): name = 'Clausula' def as_str(self): return '%s\n' % self.number class Part(Anchor): name = 'Parte' class Chapter(Anchor): name = 'Capítulo' class Title(Anchor): name = 'Título' class Annex(Anchor): name = 'Anexo' def as_str(self): if self.number: return '%s %s\n' % (self.name, self.number) else: return '%s\n' % self.name class Article(Anchor): name = 'Artigo' def as_html(self): anchor = self._build_html('a', self.number, {'href': self.ref_as_href()}) return '%s %s' % (self.name, anchor) class Number(Anchor): name = 'Número' def as_str(self): return '%s -' % self.number def as_html(self): return self._build_html('a', self.as_str(), {'href': self.ref_as_href()}) class Line(Number): name = 'Alínea' def as_str(self): return '%s' % self.number class Item(Number): """ An item of an unordered list. """ name = 'Item' def as_str(self): return '%s' % self.number class BaseDocumentSection(BaseElement): def __init__(self, *children): self._children = [] for child in children: self.append(child) self._parent_section = None def append(self, element): if isinstance(element, BaseDocumentSection): element._parent_section = self self._children.append(element) def __len__(self): return len(self._children) def as_str(self): return ''.join(child.as_str() for child in self._children) def as_html(self): string = '' ol = False ul = False for child in self._children: if ul and not isinstance(child, UnorderedDocumentSection): string += '</ul>' ul = False if ol and not isinstance(child, OrderedDocumentSection): string += '</ol>' ol = False if not ul and isinstance(child, UnorderedDocumentSection): string += '<ul>' ul = True if not ol and isinstance(child, OrderedDocumentSection): string += '<ol>' ol = True string += child.as_html() if ol: string += '</ol>' if ul: string += '</ul>' return string def as_dict(self): return {self.__class__.__name__: [child.as_dict() for child in self._children]} def find_all(self, condition, recursive=False): if recursive: def _find_all(root): result = [] if isinstance(root, BaseDocumentSection): for child in root._children: if condition(child): result.append(child) result += _find_all(child) return result return _find_all(self) return [child for child in self._children if condition(child)] def id_tree(self): tree = [] if self._parent_section is not None: tree = self._parent_section.id_tree() tree += [self] return tree def get_doc_refs(self): """ Yields tuples (name, number) of all its `DocumentReference`s. """ refs = self.find_all(lambda x: isinstance(x, DocumentReference), True) ref_set = set() for ref in refs: ref_set.add((ref.name, ref.number)) return ref_set def set_doc_refs(self, mapping): """ Uses a dictionary of the form `(name, ref)-> url` to set the href of its own `DocumentReference`s. """ refs = self.find_all(lambda x: isinstance(x, DocumentReference), True) for ref in refs: if (ref.name, ref.number) in mapping: ref.set_href(mapping[(ref.name, ref.number)]) class Paragraph(BaseDocumentSection): def as_html(self): return self._build_html('p', super(Paragraph, self).as_html(), {}) class InlineParagraph(Paragraph): def as_html(self): return self._build_html('span', super(Paragraph, self).as_html(), {}) class Document(BaseDocumentSection): pass class DocumentSection(BaseDocumentSection): formal_sections = [Annex, Article, Number, Line, Item] html_classes = { Annex: 'annex', Part: 'part', Title: 'title', Chapter: 'chapter', Section: 'section', SubSection: 'sub-section', Clause: 'clause', Article: 'article', Number: 'number list-unstyled', Line: 'line list-unstyled', Item: 'item list-unstyled', } def __init__(self, anchor, *children): super(DocumentSection, self).__init__(*children) self._anchor = anchor self._anchor.reference = self def as_dict(self): json = super(DocumentSection, self).as_dict() json[self.__class__.__name__].insert(0, self.anchor.as_dict()) return json @property def anchor(self): return self._anchor @property def format(self): return self.anchor.format def formal_id_tree(self): filtered_tree = [] for e in self.id_tree(): if isinstance(e, QuotationSection): return [] # sections inside quotations have no tree if isinstance(e, DocumentSection) and e.format in self.formal_sections: filtered_tree.append(e) return filtered_tree def id_as_html(self): string = '-'.join(e.anchor.name + '-' + e.anchor.number for e in self.formal_id_tree()) if string != '': return string else: return None class TitledDocumentSection(DocumentSection): def __init__(self, anchor, title=None, *children): super(TitledDocumentSection, self).__init__(anchor, *children) self._title = title def as_dict(self): json = super(TitledDocumentSection, self).as_dict() if self._title is not None: json[self.__class__.__name__].insert(1, self._title.as_dict()) return json hierarchy_html_titles = { Part: 'h2', Annex: 'h2', Title: 'h3', Chapter: 'h3', Section: 'h4', SubSection: 'h5', Article: 'h5', Clause: 'h5', } def as_html(self): inner = self.anchor.as_html() if self._title is not None: inner += self._title.as_html() container = self._build_html(self.hierarchy_html_titles[self.format], inner, {'class': 'title'}) rest = super(TitledDocumentSection, self).as_html() return self._build_html('div', container + rest, {'class': self.html_classes[self.format], 'id': self.id_as_html()}) def as_str(self): string = self.anchor.as_str() if self._title is not None: string += self._title.as_str() return string + super(TitledDocumentSection, self).as_str() @property def title(self): return self._title @title.setter def title(self, title): assert(isinstance(title, Paragraph)) self._title = title class InlineDocumentSection(DocumentSection): """ A section whose elements are inline. """ formats = {} def as_html(self): container = self._build_html('span', self.anchor.as_html(), {}) rest = super(InlineDocumentSection, self).as_html() return self._build_html('li', container + rest, {'class': self.html_classes[self.format], 'id': self.id_as_html()}) def as_str(self): return self.anchor.as_str() + super(InlineDocumentSection, self).as_str() class OrderedDocumentSection(InlineDocumentSection): """ A section whose elements are inline and ordered. """ formats = {Number, Line} class UnorderedDocumentSection(InlineDocumentSection): """ A section whose elements are inline and un-ordered. """ formats = {Item} class QuotationSection(BaseDocumentSection): """ A Section quoting something. """ def as_html(self): return '<blockquote>%s</blockquote>' % \ super(QuotationSection, self).as_html() def as_str(self): return '«%s»' % super(QuotationSection, self).as_str()
publicos-pt/pt_law_parser
pt_law_parser/expressions.py
Python
mit
15,426
/*! * vue-i18n v9.0.0 * (c) 2021 kazuya kawaguchi * Released under the MIT License. */ import { getGlobalThis, format, makeSymbol, isPlainObject, isArray, isObject, isBoolean, isString, isRegExp, isFunction, isNumber, warn, isEmptyObject } from '@intlify/shared'; import { ref, getCurrentInstance, computed, watch, createVNode, Text, h, Fragment, inject, onMounted, onUnmounted, isRef } from 'vue'; import { createCompileError, createCoreContext, updateFallbackLocale, resolveValue, clearDateTimeFormat, clearNumberFormat, NOT_REOSLVED, parseTranslateArgs, translate, MISSING_RESOLVE_VALUE, parseDateTimeArgs, datetime, parseNumberArgs, number, DevToolsLabels, DevToolsPlaceholders, DevToolsTimelineColors, createEmitter } from '@intlify/core-base'; import { setupDevtoolsPlugin } from '@vue/devtools-api'; /** * Vue I18n Version * * @remarks * Semver format. Same format as the package.json `version` field. * * @VueI18nGeneral */ const VERSION = '9.0.0'; /** * This is only called in esm-bundler builds. * istanbul-ignore-next */ function initFeatureFlags() { let needWarn = false; if (typeof __VUE_I18N_FULL_INSTALL__ !== 'boolean') { needWarn = true; getGlobalThis().__VUE_I18N_FULL_INSTALL__ = true; } if (typeof __VUE_I18N_LEGACY_API__ !== 'boolean') { needWarn = true; getGlobalThis().__VUE_I18N_LEGACY_API__ = true; } if (typeof __INTLIFY_PROD_DEVTOOLS__ !== 'boolean') { needWarn = true; getGlobalThis().__INTLIFY_PROD_DEVTOOLS__ = false; } if ((process.env.NODE_ENV !== 'production') && needWarn) { console.warn(`You are running the esm-bundler build of vue-i18n. It is recommended to ` + `configure your bundler to explicitly replace feature flag globals ` + `with boolean literals to get proper tree-shaking in the final bundle.`); } } /** * This is only called development env * istanbul-ignore-next */ function initDev() { const target = getGlobalThis(); target.__INTLIFY__ = true; { console.info(`You are running a development build of vue-i18n.\n` + `Make sure to use the production build (*.prod.js) when deploying for production.`); } } const warnMessages = { [6 /* FALLBACK_TO_ROOT */]: `Fall back to {type} '{key}' with root locale.`, [7 /* NOT_SUPPORTED_PRESERVE */]: `Not supported 'preserve'.`, [8 /* NOT_SUPPORTED_FORMATTER */]: `Not supported 'formatter'.`, [9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */]: `Not supported 'preserveDirectiveContent'.`, [10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */]: `Not supported 'getChoiceIndex'.`, [11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */]: `Component name legacy compatible: '{name}' -> 'i18n'`, [12 /* NOT_FOUND_PARENT_SCOPE */]: `Not found parent scope. use the global scope.` }; function getWarnMessage(code, ...args) { return format(warnMessages[code], ...args); } function createI18nError(code, ...args) { return createCompileError(code, null, (process.env.NODE_ENV !== 'production') ? { messages: errorMessages, args } : undefined); } const errorMessages = { [14 /* UNEXPECTED_RETURN_TYPE */]: 'Unexpected return type in composer', [15 /* INVALID_ARGUMENT */]: 'Invalid argument', [16 /* MUST_BE_CALL_SETUP_TOP */]: 'Must be called at the top of a `setup` function', [17 /* NOT_INSLALLED */]: 'Need to install with `app.use` function', [22 /* UNEXPECTED_ERROR */]: 'Unexpected error', [18 /* NOT_AVAILABLE_IN_LEGACY_MODE */]: 'Not available in legacy mode', [19 /* REQUIRED_VALUE */]: `Required in value: {0}`, [20 /* INVALID_VALUE */]: `Invalid value`, [21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */]: `Cannot setup vue-devtools plugin` }; const TransrateVNodeSymbol = makeSymbol('__transrateVNode'); const DatetimePartsSymbol = makeSymbol('__datetimeParts'); const NumberPartsSymbol = makeSymbol('__numberParts'); const EnableEmitter = makeSymbol('__enableEmitter'); const DisableEmitter = makeSymbol('__disableEmitter'); const SetPluralRulesSymbol = makeSymbol('__setPluralRules'); let composerID = 0; function defineCoreMissingHandler(missing) { return ((ctx, locale, key, type) => { return missing(locale, key, getCurrentInstance() || undefined, type); }); } function getLocaleMessages(locale, options) { const { messages, __i18n } = options; // prettier-ignore const ret = isPlainObject(messages) ? messages : isArray(__i18n) ? {} : { [locale]: {} }; // merge locale messages of i18n custom block if (isArray(__i18n)) { __i18n.forEach(({ locale, resource }) => { if (locale) { ret[locale] = ret[locale] || {}; deepCopy(resource, ret[locale]); } else { deepCopy(resource, ret); } }); } return ret; } const hasOwnProperty = Object.prototype.hasOwnProperty; // eslint-disable-next-line @typescript-eslint/no-explicit-any function hasOwn(obj, key) { return hasOwnProperty.call(obj, key); } const isNotObjectOrIsArray = (val) => !isObject(val) || isArray(val); // eslint-disable-next-line @typescript-eslint/no-explicit-any function deepCopy(src, des) { // src and des should both be objects, and non of then can be a array if (isNotObjectOrIsArray(src) || isNotObjectOrIsArray(des)) { throw createI18nError(20 /* INVALID_VALUE */); } for (const key in src) { if (hasOwn(src, key)) { if (isNotObjectOrIsArray(src[key]) || isNotObjectOrIsArray(des[key])) { // replace with src[key] when: // src[key] or des[key] is not a object, or // src[key] or des[key] is a array des[key] = src[key]; } else { // src[key] and des[key] are both object, merge them deepCopy(src[key], des[key]); } } } } /** * Create composer interface factory * * @internal */ function createComposer(options = {}) { const { __root } = options; const _isGlobal = __root === undefined; let _inheritLocale = isBoolean(options.inheritLocale) ? options.inheritLocale : true; const _locale = ref( // prettier-ignore __root && _inheritLocale ? __root.locale.value : isString(options.locale) ? options.locale : 'en-US'); const _fallbackLocale = ref( // prettier-ignore __root && _inheritLocale ? __root.fallbackLocale.value : isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : _locale.value); const _messages = ref(getLocaleMessages(_locale.value, options)); const _datetimeFormats = ref(isPlainObject(options.datetimeFormats) ? options.datetimeFormats : { [_locale.value]: {} }); const _numberFormats = ref(isPlainObject(options.numberFormats) ? options.numberFormats : { [_locale.value]: {} }); // warning suppress options // prettier-ignore let _missingWarn = __root ? __root.missingWarn : isBoolean(options.missingWarn) || isRegExp(options.missingWarn) ? options.missingWarn : true; // prettier-ignore let _fallbackWarn = __root ? __root.fallbackWarn : isBoolean(options.fallbackWarn) || isRegExp(options.fallbackWarn) ? options.fallbackWarn : true; // prettier-ignore let _fallbackRoot = __root ? __root.fallbackRoot : isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; // configure fall back to root let _fallbackFormat = !!options.fallbackFormat; // runtime missing let _missing = isFunction(options.missing) ? options.missing : null; let _runtimeMissing = isFunction(options.missing) ? defineCoreMissingHandler(options.missing) : null; // postTranslation handler let _postTranslation = isFunction(options.postTranslation) ? options.postTranslation : null; let _warnHtmlMessage = isBoolean(options.warnHtmlMessage) ? options.warnHtmlMessage : true; let _escapeParameter = !!options.escapeParameter; // custom linked modifiers // prettier-ignore const _modifiers = __root ? __root.modifiers : isPlainObject(options.modifiers) ? options.modifiers : {}; // pluralRules let _pluralRules = options.pluralRules || (__root && __root.pluralRules); // runtime context // eslint-disable-next-line prefer-const let _context; function getCoreContext() { return createCoreContext({ locale: _locale.value, fallbackLocale: _fallbackLocale.value, messages: _messages.value, datetimeFormats: _datetimeFormats.value, numberFormats: _numberFormats.value, modifiers: _modifiers, pluralRules: _pluralRules, missing: _runtimeMissing === null ? undefined : _runtimeMissing, missingWarn: _missingWarn, fallbackWarn: _fallbackWarn, fallbackFormat: _fallbackFormat, unresolving: true, postTranslation: _postTranslation === null ? undefined : _postTranslation, warnHtmlMessage: _warnHtmlMessage, escapeParameter: _escapeParameter, __datetimeFormatters: isPlainObject(_context) ? _context.__datetimeFormatters : undefined, __numberFormatters: isPlainObject(_context) ? _context.__numberFormatters : undefined, __emitter: isPlainObject(_context) ? _context.__emitter : undefined }); } _context = getCoreContext(); updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); // locale const locale = computed({ get: () => _locale.value, set: val => { _locale.value = val; _context.locale = _locale.value; } }); // fallbackLocale const fallbackLocale = computed({ get: () => _fallbackLocale.value, set: val => { _fallbackLocale.value = val; _context.fallbackLocale = _fallbackLocale.value; updateFallbackLocale(_context, _locale.value, val); } }); // messages const messages = computed(() => _messages.value); // datetimeFormats const datetimeFormats = computed(() => _datetimeFormats.value); // numberFormats const numberFormats = computed(() => _numberFormats.value); // getPostTranslationHandler function getPostTranslationHandler() { return isFunction(_postTranslation) ? _postTranslation : null; } // setPostTranslationHandler function setPostTranslationHandler(handler) { _postTranslation = handler; _context.postTranslation = handler; } // getMissingHandler function getMissingHandler() { return _missing; } // setMissingHandler function setMissingHandler(handler) { if (handler !== null) { _runtimeMissing = defineCoreMissingHandler(handler); } _missing = handler; _context.missing = _runtimeMissing; } function wrapWithDeps(fn, argumentParser, warnType, fallbackSuccess, fallbackFail, successCondition) { const context = getCoreContext(); const ret = fn(context); // track reactive dependency, see the getRuntimeContext if (isNumber(ret) && ret === NOT_REOSLVED) { const key = argumentParser(); if ((process.env.NODE_ENV !== 'production') && __root) { if (!_fallbackRoot) { warn(getWarnMessage(6 /* FALLBACK_TO_ROOT */, { key, type: warnType })); } // for vue-devtools timeline event if ((process.env.NODE_ENV !== 'production')) { const { __emitter: emitter } = context; if (emitter) { emitter.emit("fallback" /* FALBACK */, { type: warnType, key, to: 'global', groupId: `${warnType}:${key}` }); } } } return __root && _fallbackRoot ? fallbackSuccess(__root) : fallbackFail(key); } else if (successCondition(ret)) { return ret; } else { /* istanbul ignore next */ throw createI18nError(14 /* UNEXPECTED_RETURN_TYPE */); } } // t function t(...args) { return wrapWithDeps(context => translate(context, ...args), () => parseTranslateArgs(...args)[0], 'translate', root => root.t(...args), key => key, val => isString(val)); } // d function d(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', root => root.d(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // n function n(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', root => root.n(...args), () => MISSING_RESOLVE_VALUE, val => isString(val)); } // for custom processor function normalize(values) { return values.map(val => isString(val) ? createVNode(Text, null, val, 0) : val); } const interpolate = (val) => val; const processor = { normalize, interpolate, type: 'vnode' }; // __transrateVNode, using for `i18n-t` component function __transrateVNode(...args) { return wrapWithDeps(context => { let ret; const _context = context; try { _context.processor = processor; ret = translate(_context, ...args); } finally { _context.processor = null; } return ret; }, () => parseTranslateArgs(...args)[0], 'translate', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[TransrateVNodeSymbol](...args), key => [createVNode(Text, null, key, 0)], val => isArray(val)); } // __numberParts, using for `i18n-n` component function __numberParts(...args) { return wrapWithDeps(context => number(context, ...args), () => parseNumberArgs(...args)[0], 'number format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[NumberPartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } // __datetimeParts, using for `i18n-d` component function __datetimeParts(...args) { return wrapWithDeps(context => datetime(context, ...args), () => parseDateTimeArgs(...args)[0], 'datetime format', // eslint-disable-next-line @typescript-eslint/no-explicit-any root => root[DatetimePartsSymbol](...args), () => [], val => isString(val) || isArray(val)); } function __setPluralRules(rules) { _pluralRules = rules; _context.pluralRules = _pluralRules; } // te function te(key, locale) { const targetLocale = isString(locale) ? locale : _locale.value; const message = getLocaleMessage(targetLocale); return resolveValue(message, key) !== null; } // tm function tm(key) { const messages = _messages.value[_locale.value] || {}; const target = resolveValue(messages, key); // prettier-ignore return target != null ? target : __root ? __root.tm(key) || {} : {}; } // getLocaleMessage function getLocaleMessage(locale) { return (_messages.value[locale] || {}); } // setLocaleMessage function setLocaleMessage(locale, message) { _messages.value[locale] = message; _context.messages = _messages.value; } // mergeLocaleMessage function mergeLocaleMessage(locale, message) { _messages.value[locale] = _messages.value[locale] || {}; deepCopy(message, _messages.value[locale]); _context.messages = _messages.value; } // getDateTimeFormat function getDateTimeFormat(locale) { return _datetimeFormats.value[locale] || {}; } // setDateTimeFormat function setDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = format; _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // mergeDateTimeFormat function mergeDateTimeFormat(locale, format) { _datetimeFormats.value[locale] = Object.assign(_datetimeFormats.value[locale] || {}, format); _context.datetimeFormats = _datetimeFormats.value; clearDateTimeFormat(_context, locale, format); } // getNumberFormat function getNumberFormat(locale) { return _numberFormats.value[locale] || {}; } // setNumberFormat function setNumberFormat(locale, format) { _numberFormats.value[locale] = format; _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // mergeNumberFormat function mergeNumberFormat(locale, format) { _numberFormats.value[locale] = Object.assign(_numberFormats.value[locale] || {}, format); _context.numberFormats = _numberFormats.value; clearNumberFormat(_context, locale, format); } // for debug composerID++; // watch root locale & fallbackLocale if (__root) { watch(__root.locale, (val) => { if (_inheritLocale) { _locale.value = val; _context.locale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); watch(__root.fallbackLocale, (val) => { if (_inheritLocale) { _fallbackLocale.value = val; _context.fallbackLocale = val; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }); } // export composition API! const composer = { id: composerID, locale, fallbackLocale, get inheritLocale() { return _inheritLocale; }, set inheritLocale(val) { _inheritLocale = val; if (val && __root) { _locale.value = __root.locale.value; _fallbackLocale.value = __root.fallbackLocale.value; updateFallbackLocale(_context, _locale.value, _fallbackLocale.value); } }, get availableLocales() { return Object.keys(_messages.value).sort(); }, messages, datetimeFormats, numberFormats, get modifiers() { return _modifiers; }, get pluralRules() { return _pluralRules || {}; }, get isGlobal() { return _isGlobal; }, get missingWarn() { return _missingWarn; }, set missingWarn(val) { _missingWarn = val; _context.missingWarn = _missingWarn; }, get fallbackWarn() { return _fallbackWarn; }, set fallbackWarn(val) { _fallbackWarn = val; _context.fallbackWarn = _fallbackWarn; }, get fallbackRoot() { return _fallbackRoot; }, set fallbackRoot(val) { _fallbackRoot = val; }, get fallbackFormat() { return _fallbackFormat; }, set fallbackFormat(val) { _fallbackFormat = val; _context.fallbackFormat = _fallbackFormat; }, get warnHtmlMessage() { return _warnHtmlMessage; }, set warnHtmlMessage(val) { _warnHtmlMessage = val; _context.warnHtmlMessage = val; }, get escapeParameter() { return _escapeParameter; }, set escapeParameter(val) { _escapeParameter = val; _context.escapeParameter = val; }, t, d, n, te, tm, getLocaleMessage, setLocaleMessage, mergeLocaleMessage, getDateTimeFormat, setDateTimeFormat, mergeDateTimeFormat, getNumberFormat, setNumberFormat, mergeNumberFormat, getPostTranslationHandler, setPostTranslationHandler, getMissingHandler, setMissingHandler, [TransrateVNodeSymbol]: __transrateVNode, [NumberPartsSymbol]: __numberParts, [DatetimePartsSymbol]: __datetimeParts, [SetPluralRulesSymbol]: __setPluralRules }; // for vue-devtools timeline event if ((process.env.NODE_ENV !== 'production')) { composer[EnableEmitter] = (emitter) => { _context.__emitter = emitter; }; composer[DisableEmitter] = () => { _context.__emitter = undefined; }; } return composer; } /** * Convert to I18n Composer Options from VueI18n Options * * @internal */ function convertComposerOptions(options) { const locale = isString(options.locale) ? options.locale : 'en-US'; const fallbackLocale = isString(options.fallbackLocale) || isArray(options.fallbackLocale) || isPlainObject(options.fallbackLocale) || options.fallbackLocale === false ? options.fallbackLocale : locale; const missing = isFunction(options.missing) ? options.missing : undefined; const missingWarn = isBoolean(options.silentTranslationWarn) || isRegExp(options.silentTranslationWarn) ? !options.silentTranslationWarn : true; const fallbackWarn = isBoolean(options.silentFallbackWarn) || isRegExp(options.silentFallbackWarn) ? !options.silentFallbackWarn : true; const fallbackRoot = isBoolean(options.fallbackRoot) ? options.fallbackRoot : true; const fallbackFormat = !!options.formatFallbackMessages; const modifiers = isPlainObject(options.modifiers) ? options.modifiers : {}; const pluralizationRules = options.pluralizationRules; const postTranslation = isFunction(options.postTranslation) ? options.postTranslation : undefined; const warnHtmlMessage = isString(options.warnHtmlInMessage) ? options.warnHtmlInMessage !== 'off' : true; const escapeParameter = !!options.escapeParameterHtml; const inheritLocale = isBoolean(options.sync) ? options.sync : true; if ((process.env.NODE_ENV !== 'production') && options.formatter) { warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); } if ((process.env.NODE_ENV !== 'production') && options.preserveDirectiveContent) { warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); } let messages = options.messages; if (isPlainObject(options.sharedMessages)) { const sharedMessages = options.sharedMessages; const locales = Object.keys(sharedMessages); messages = locales.reduce((messages, locale) => { const message = messages[locale] || (messages[locale] = {}); Object.assign(message, sharedMessages[locale]); return messages; }, (messages || {})); } const { __i18n, __root } = options; const datetimeFormats = options.datetimeFormats; const numberFormats = options.numberFormats; return { locale, fallbackLocale, messages, datetimeFormats, numberFormats, missing, missingWarn, fallbackWarn, fallbackRoot, fallbackFormat, modifiers, pluralRules: pluralizationRules, postTranslation, warnHtmlMessage, escapeParameter, inheritLocale, __i18n, __root }; } /** * create VueI18n interface factory * * @internal */ function createVueI18n(options = {}) { const composer = createComposer(convertComposerOptions(options)); // defines VueI18n const vueI18n = { // id id: composer.id, // locale get locale() { return composer.locale.value; }, set locale(val) { composer.locale.value = val; }, // fallbackLocale get fallbackLocale() { return composer.fallbackLocale.value; }, set fallbackLocale(val) { composer.fallbackLocale.value = val; }, // messages get messages() { return composer.messages.value; }, // datetimeFormats get datetimeFormats() { return composer.datetimeFormats.value; }, // numberFormats get numberFormats() { return composer.numberFormats.value; }, // availableLocales get availableLocales() { return composer.availableLocales; }, // formatter get formatter() { (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); // dummy return { interpolate() { return []; } }; }, set formatter(val) { (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(8 /* NOT_SUPPORTED_FORMATTER */)); }, // missing get missing() { return composer.getMissingHandler(); }, set missing(handler) { composer.setMissingHandler(handler); }, // silentTranslationWarn get silentTranslationWarn() { return isBoolean(composer.missingWarn) ? !composer.missingWarn : composer.missingWarn; }, set silentTranslationWarn(val) { composer.missingWarn = isBoolean(val) ? !val : val; }, // silentFallbackWarn get silentFallbackWarn() { return isBoolean(composer.fallbackWarn) ? !composer.fallbackWarn : composer.fallbackWarn; }, set silentFallbackWarn(val) { composer.fallbackWarn = isBoolean(val) ? !val : val; }, // modifiers get modifiers() { return composer.modifiers; }, // formatFallbackMessages get formatFallbackMessages() { return composer.fallbackFormat; }, set formatFallbackMessages(val) { composer.fallbackFormat = val; }, // postTranslation get postTranslation() { return composer.getPostTranslationHandler(); }, set postTranslation(handler) { composer.setPostTranslationHandler(handler); }, // sync get sync() { return composer.inheritLocale; }, set sync(val) { composer.inheritLocale = val; }, // warnInHtmlMessage get warnHtmlInMessage() { return composer.warnHtmlMessage ? 'warn' : 'off'; }, set warnHtmlInMessage(val) { composer.warnHtmlMessage = val !== 'off'; }, // escapeParameterHtml get escapeParameterHtml() { return composer.escapeParameter; }, set escapeParameterHtml(val) { composer.escapeParameter = val; }, // preserveDirectiveContent get preserveDirectiveContent() { (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); return true; }, set preserveDirectiveContent(val) { (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(9 /* NOT_SUPPORTED_PRESERVE_DIRECTIVE */)); }, // pluralizationRules get pluralizationRules() { return composer.pluralRules || {}; }, // for internal __composer: composer, // t t(...args) { const [arg1, arg2, arg3] = args; const options = {}; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(15 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // tc tc(...args) { const [arg1, arg2, arg3] = args; const options = { plural: 1 }; let list = null; let named = null; if (!isString(arg1)) { throw createI18nError(15 /* INVALID_ARGUMENT */); } const key = arg1; if (isString(arg2)) { options.locale = arg2; } else if (isNumber(arg2)) { options.plural = arg2; } else if (isArray(arg2)) { list = arg2; } else if (isPlainObject(arg2)) { named = arg2; } if (isString(arg3)) { options.locale = arg3; } else if (isArray(arg3)) { list = arg3; } else if (isPlainObject(arg3)) { named = arg3; } return composer.t(key, list || named || {}, options); }, // te te(key, locale) { return composer.te(key, locale); }, // tm tm(key) { return composer.tm(key); }, // getLocaleMessage getLocaleMessage(locale) { return composer.getLocaleMessage(locale); }, // setLocaleMessage setLocaleMessage(locale, message) { composer.setLocaleMessage(locale, message); }, // mergeLocaleMessage mergeLocaleMessage(locale, message) { composer.mergeLocaleMessage(locale, message); }, // d d(...args) { return composer.d(...args); }, // getDateTimeFormat getDateTimeFormat(locale) { return composer.getDateTimeFormat(locale); }, // setDateTimeFormat setDateTimeFormat(locale, format) { composer.setDateTimeFormat(locale, format); }, // mergeDateTimeFormat mergeDateTimeFormat(locale, format) { composer.mergeDateTimeFormat(locale, format); }, // n n(...args) { return composer.n(...args); }, // getNumberFormat getNumberFormat(locale) { return composer.getNumberFormat(locale); }, // setNumberFormat setNumberFormat(locale, format) { composer.setNumberFormat(locale, format); }, // mergeNumberFormat mergeNumberFormat(locale, format) { composer.mergeNumberFormat(locale, format); }, // getChoiceIndex // eslint-disable-next-line @typescript-eslint/no-unused-vars getChoiceIndex(choice, choicesLength) { (process.env.NODE_ENV !== 'production') && warn(getWarnMessage(10 /* NOT_SUPPORTED_GET_CHOICE_INDEX */)); return -1; }, // for internal __onComponentInstanceCreated(target) { const { componentInstanceCreatedListener } = options; if (componentInstanceCreatedListener) { componentInstanceCreatedListener(target, vueI18n); } } }; // for vue-devtools timeline event if ((process.env.NODE_ENV !== 'production')) { vueI18n.__enableEmitter = (emitter) => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[EnableEmitter] && __composer[EnableEmitter](emitter); }; vueI18n.__disableEmitter = () => { // eslint-disable-next-line @typescript-eslint/no-explicit-any const __composer = composer; __composer[DisableEmitter] && __composer[DisableEmitter](); }; } return vueI18n; } const baseFormatProps = { tag: { type: [String, Object] }, locale: { type: String }, scope: { type: String, validator: (val) => val === 'parent' || val === 'global', default: 'parent' } }; /** * Translation Component * * @remarks * See the following items for property about details * * @VueI18nSee [TranslationProps](component#translationprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Component Interpolation](../../guide/advanced/component) * * @example * ```html * <div id="app"> * <!-- ... --> * <i18n path="term" tag="label" for="tos"> * <a :href="url" target="_blank">{{ $t('tos') }}</a> * </i18n> * <!-- ... --> * </div> * ``` * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * const messages = { * en: { * tos: 'Term of Service', * term: 'I accept xxx {0}.' * }, * ja: { * tos: '利用規約', * term: '私は xxx の{0}に同意します。' * } * } * * const i18n = createI18n({ * locale: 'en', * messages * }) * * const app = createApp({ * data: { * url: '/term' * } * }).use(i18n).mount('#app') * ``` * * @VueI18nComponent */ const Translation = { /* eslint-disable */ name: 'i18n-t', props: { ...baseFormatProps, keypath: { type: String, required: true }, plural: { type: [Number, String], // eslint-disable-next-line @typescript-eslint/no-explicit-any validator: (val) => isNumber(val) || !isNaN(val) } }, /* eslint-enable */ setup(props, context) { const { slots, attrs } = context; const i18n = useI18n({ useScope: props.scope }); const keys = Object.keys(slots).filter(key => key !== '_'); return () => { const options = {}; if (props.locale) { options.locale = props.locale; } if (props.plural !== undefined) { options.plural = isString(props.plural) ? +props.plural : props.plural; } const arg = getInterpolateArg(context, keys); // eslint-disable-next-line @typescript-eslint/no-explicit-any const children = i18n[TransrateVNodeSymbol](props.keypath, arg, options); // prettier-ignore return isString(props.tag) ? h(props.tag, { ...attrs }, children) : isObject(props.tag) ? h(props.tag, { ...attrs }, children) : h(Fragment, { ...attrs }, children); }; } }; function getInterpolateArg({ slots }, keys) { if (keys.length === 1 && keys[0] === 'default') { // default slot only return slots.default ? slots.default() : []; } else { // named slots return keys.reduce((arg, key) => { const slot = slots[key]; if (slot) { arg[key] = slot(); } return arg; }, {}); } } function renderFormatter(props, context, slotKeys, partFormatter) { const { slots, attrs } = context; return () => { const options = { part: true }; let overrides = {}; if (props.locale) { options.locale = props.locale; } if (isString(props.format)) { options.key = props.format; } else if (isObject(props.format)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any if (isString(props.format.key)) { // eslint-disable-next-line @typescript-eslint/no-explicit-any options.key = props.format.key; } // Filter out number format options only overrides = Object.keys(props.format).reduce((options, prop) => { return slotKeys.includes(prop) ? Object.assign({}, options, { [prop]: props.format[prop] }) // eslint-disable-line @typescript-eslint/no-explicit-any : options; }, {}); } const parts = partFormatter(...[props.value, options, overrides]); let children = [options.key]; if (isArray(parts)) { children = parts.map((part, index) => { const slot = slots[part.type]; return slot ? slot({ [part.type]: part.value, index, parts }) : [part.value]; }); } else if (isString(parts)) { children = [parts]; } // prettier-ignore return isString(props.tag) ? h(props.tag, { ...attrs }, children) : isObject(props.tag) ? h(props.tag, { ...attrs }, children) : h(Fragment, { ...attrs }, children); }; } const NUMBER_FORMAT_KEYS = [ 'localeMatcher', 'style', 'unit', 'unitDisplay', 'currency', 'currencyDisplay', 'useGrouping', 'numberingSystem', 'minimumIntegerDigits', 'minimumFractionDigits', 'maximumFractionDigits', 'minimumSignificantDigits', 'maximumSignificantDigits', 'notation', 'formatMatcher' ]; /** * Number Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../../guide/essentials/number#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.NumberFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/NumberFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-numberformat) * * @VueI18nComponent */ const NumberFormat = { /* eslint-disable */ name: 'i18n-n', props: { ...baseFormatProps, value: { type: Number, required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, NUMBER_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[NumberPartsSymbol](...args)); } }; const DATETIME_FORMAT_KEYS = [ 'dateStyle', 'timeStyle', 'fractionalSecondDigits', 'calendar', 'dayPeriod', 'numberingSystem', 'localeMatcher', 'timeZone', 'hour12', 'hourCycle', 'formatMatcher', 'weekday', 'era', 'year', 'month', 'day', 'hour', 'minute', 'second', 'timeZoneName' ]; /** * Datetime Format Component * * @remarks * See the following items for property about details * * @VueI18nSee [FormattableProps](component#formattableprops) * @VueI18nSee [BaseFormatProps](component#baseformatprops) * @VueI18nSee [Custom Formatting](../../guide/essentials/datetime#custom-formatting) * * @VueI18nDanger * Not supported IE, due to no support `Intl.DateTimeFormat#formatToParts` in [IE](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/formatToParts) * * If you want to use it, you need to use [polyfill](https://github.com/formatjs/formatjs/tree/main/packages/intl-datetimeformat) * * @VueI18nComponent */ const DatetimeFormat = { /* eslint-disable */ name: 'i18n-d', props: { ...baseFormatProps, value: { type: [Number, Date], required: true }, format: { type: [String, Object] } }, /* eslint-enable */ setup(props, context) { const i18n = useI18n({ useScope: 'parent' }); return renderFormatter(props, context, DATETIME_FORMAT_KEYS, (...args) => // eslint-disable-next-line @typescript-eslint/no-explicit-any i18n[DatetimePartsSymbol](...args)); } }; function getComposer(i18n, instance) { const i18nInternal = i18n; if (i18n.mode === 'composition') { return (i18nInternal.__getInstance(instance) || i18n.global); } else { const vueI18n = i18nInternal.__getInstance(instance); return vueI18n != null ? vueI18n.__composer : i18n.global.__composer; } } function vTDirective(i18n) { const bind = (el, { instance, value, modifiers }) => { /* istanbul ignore if */ if (!instance || !instance.$) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const composer = getComposer(i18n, instance.$); if ((process.env.NODE_ENV !== 'production') && modifiers.preserve) { warn(getWarnMessage(7 /* NOT_SUPPORTED_PRESERVE */)); } const parsedValue = parseValue(value); el.textContent = composer.t(...makeParams(parsedValue)); }; return { beforeMount: bind, beforeUpdate: bind }; } function parseValue(value) { if (isString(value)) { return { path: value }; } else if (isPlainObject(value)) { if (!('path' in value)) { throw createI18nError(19 /* REQUIRED_VALUE */, 'path'); } return value; } else { throw createI18nError(20 /* INVALID_VALUE */); } } function makeParams(value) { const { path, locale, args, choice, plural } = value; const options = {}; const named = args || {}; if (isString(locale)) { options.locale = locale; } if (isNumber(choice)) { options.plural = choice; } if (isNumber(plural)) { options.plural = plural; } return [path, named, options]; } function apply(app, i18n, ...options) { const pluginOptions = isPlainObject(options[0]) ? options[0] : {}; const useI18nComponentName = !!pluginOptions.useI18nComponentName; const globalInstall = isBoolean(pluginOptions.globalInstall) ? pluginOptions.globalInstall : true; if ((process.env.NODE_ENV !== 'production') && globalInstall && useI18nComponentName) { warn(getWarnMessage(11 /* COMPONENT_NAME_LEGACY_COMPATIBLE */, { name: Translation.name })); } if (globalInstall) { // install components app.component(!useI18nComponentName ? Translation.name : 'i18n', Translation); app.component(NumberFormat.name, NumberFormat); app.component(DatetimeFormat.name, DatetimeFormat); } // install directive app.directive('t', vTDirective(i18n)); } let devtoolsApi; async function enableDevTools(app, i18n) { return new Promise((resolve, reject) => { try { setupDevtoolsPlugin({ id: "vue-devtools-plugin-vue-i18n" /* PLUGIN */, label: DevToolsLabels["vue-devtools-plugin-vue-i18n" /* PLUGIN */], app }, api => { devtoolsApi = api; api.on.walkComponentTree((payload, ctx) => { updateComponentTreeDataTags(ctx.currentAppRecord, payload.componentTreeData, i18n); }); api.on.inspectComponent(payload => { const componentInstance = payload.componentInstance; if (componentInstance.vnode.el.__INTLIFY__ && payload.instanceData) { if (i18n.mode === 'legacy') { // ignore global scope on legacy mode if (componentInstance.vnode.el.__INTLIFY__ !== i18n.global.__composer) { inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__); } } else { inspectComposer(payload.instanceData, componentInstance.vnode.el.__INTLIFY__); } } }); api.addInspector({ id: "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */, label: DevToolsLabels["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */], icon: 'language', treeFilterPlaceholder: DevToolsPlaceholders["vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */] }); api.on.getInspectorTree(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { registerScope(payload, i18n); } }); api.on.getInspectorState(payload => { if (payload.app === app && payload.inspectorId === "vue-i18n-resource-inspector" /* CUSTOM_INSPECTOR */) { inspectScope(payload, i18n); } }); api.addTimelineLayer({ id: "vue-i18n-timeline" /* TIMELINE */, label: DevToolsLabels["vue-i18n-timeline" /* TIMELINE */], color: DevToolsTimelineColors["vue-i18n-timeline" /* TIMELINE */] }); resolve(true); }); } catch (e) { console.error(e); reject(false); } }); } function updateComponentTreeDataTags(appRecord, treeData, i18n) { // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; for (const node of treeData) { const instance = appRecord.instanceMap.get(node.id); if (instance && instance.vnode.el.__INTLIFY__) { // add custom tags local scope only if (instance.vnode.el.__INTLIFY__ !== global) { const label = instance.type.name || instance.type.displayName || instance.type.__file; const tag = { label: `i18n (${label} Scope)`, textColor: 0x000000, backgroundColor: 0xffcd19 }; node.tags.push(tag); } } updateComponentTreeDataTags(appRecord, node.children, i18n); } } function inspectComposer(instanceData, composer) { const type = 'vue-i18n: composer properties'; instanceData.state.push({ type, key: 'locale', editable: false, value: composer.locale.value }); instanceData.state.push({ type, key: 'availableLocales', editable: false, value: composer.availableLocales }); instanceData.state.push({ type, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }); instanceData.state.push({ type, key: 'inheritLocale', editable: false, value: composer.inheritLocale }); instanceData.state.push({ type, key: 'messages', editable: false, value: getLocaleMessageValue(composer.messages.value) }); instanceData.state.push({ type, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value }); instanceData.state.push({ type, key: 'numberFormats', editable: false, value: composer.numberFormats.value }); } // eslint-disable-next-line @typescript-eslint/no-explicit-any function getLocaleMessageValue(messages) { const value = {}; Object.keys(messages).forEach((key) => { const v = messages[key]; if (isFunction(v) && 'source' in v) { value[key] = getMessageFunctionDetails(v); } else if (isObject(v)) { value[key] = getLocaleMessageValue(v); } else { value[key] = v; } }); return value; } const ESC = { '<': '&lt;', '>': '&gt;', '"': '&quot;', '&': '&amp;' }; function escape(s) { return s.replace(/[<>"&]/g, escapeChar); } function escapeChar(a) { return ESC[a] || a; } // eslint-disable-next-line @typescript-eslint/no-explicit-any function getMessageFunctionDetails(func) { const argString = func.source ? `("${escape(func.source)}")` : `(?)`; return { _custom: { type: 'function', display: `<span>ƒ</span> ${argString}` } }; } function registerScope(payload, i18n) { payload.rootNodes.push({ id: 'global', label: 'Global Scope' }); // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; for (const [keyInstance, instance] of i18n.__instances) { // prettier-ignore const composer = i18n.mode === 'composition' ? instance : instance.__composer; if (global === composer) { continue; } const label = keyInstance.type.name || keyInstance.type.displayName || keyInstance.type.__file; payload.rootNodes.push({ id: composer.id.toString(), label: `${label} Scope` }); } } function inspectScope(payload, i18n) { if (payload.nodeId === 'global') { payload.state = makeScopeInspectState(i18n.mode === 'composition' ? i18n.global : i18n.global.__composer); } else { const instance = Array.from(i18n.__instances.values()).find(item => item.id.toString() === payload.nodeId); if (instance) { const composer = i18n.mode === 'composition' ? instance : instance.__composer; payload.state = makeScopeInspectState(composer); } } } function makeScopeInspectState(composer) { const state = {}; const localeType = 'Locale related info'; const localeStates = [ { type: localeType, key: 'locale', editable: false, value: composer.locale.value }, { type: localeType, key: 'fallbackLocale', editable: false, value: composer.fallbackLocale.value }, { type: localeType, key: 'availableLocales', editable: false, value: composer.availableLocales }, { type: localeType, key: 'inheritLocale', editable: false, value: composer.inheritLocale } ]; state[localeType] = localeStates; const localeMessagesType = 'Locale messages info'; const localeMessagesStates = [ { type: localeMessagesType, key: 'messages', editable: false, value: getLocaleMessageValue(composer.messages.value) } ]; state[localeMessagesType] = localeMessagesStates; const datetimeFormatsType = 'Datetime formats info'; const datetimeFormatsStates = [ { type: datetimeFormatsType, key: 'datetimeFormats', editable: false, value: composer.datetimeFormats.value } ]; state[datetimeFormatsType] = datetimeFormatsStates; const numberFormatsType = 'Datetime formats info'; const numberFormatsStates = [ { type: numberFormatsType, key: 'numberFormats', editable: false, value: composer.numberFormats.value } ]; state[numberFormatsType] = numberFormatsStates; return state; } function addTimelineEvent(event, payload) { if (devtoolsApi) { let groupId; if (payload && 'groupId' in payload) { groupId = payload.groupId; delete payload.groupId; } devtoolsApi.addTimelineEvent({ layerId: "vue-i18n-timeline" /* TIMELINE */, event: { title: event, groupId, time: Date.now(), meta: {}, data: payload || {}, logType: event === "compile-error" /* COMPILE_ERROR */ ? 'error' : event === "fallback" /* FALBACK */ || event === "missing" /* MISSING */ ? 'warning' : 'default' } }); } } // supports compatibility for legacy vue-i18n APIs function defineMixin(vuei18n, composer, i18n) { return { beforeCreate() { const instance = getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const options = this.$options; if (options.i18n) { const optionsI18n = options.i18n; if (options.__i18n) { optionsI18n.__i18n = options.__i18n; } optionsI18n.__root = composer; if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, optionsI18n); } else { this.$i18n = createVueI18n(optionsI18n); } } else if (options.__i18n) { if (this === this.$root) { this.$i18n = mergeToRoot(vuei18n, options); } else { this.$i18n = createVueI18n({ __i18n: options.__i18n, __root: composer }); } } else { // set global this.$i18n = vuei18n; } vuei18n.__onComponentInstanceCreated(this.$i18n); i18n.__setInstance(instance, this.$i18n); // defines vue-i18n legacy APIs this.$t = (...args) => this.$i18n.t(...args); this.$tc = (...args) => this.$i18n.tc(...args); this.$te = (key, locale) => this.$i18n.te(key, locale); this.$d = (...args) => this.$i18n.d(...args); this.$n = (...args) => this.$i18n.n(...args); this.$tm = (key) => this.$i18n.tm(key); }, mounted() { /* istanbul ignore if */ if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) { this.$el.__INTLIFY__ = this.$i18n.__composer; const emitter = (this.__emitter = createEmitter()); const _vueI18n = this.$i18n; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); emitter.on('*', addTimelineEvent); } }, beforeUnmount() { const instance = getCurrentInstance(); /* istanbul ignore if */ if (!instance) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } /* istanbul ignore if */ if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) { if (this.__emitter) { this.__emitter.off('*', addTimelineEvent); delete this.__emitter; } const _vueI18n = this.$i18n; _vueI18n.__disableEmitter && _vueI18n.__disableEmitter(); delete this.$el.__INTLIFY__; } delete this.$t; delete this.$tc; delete this.$te; delete this.$d; delete this.$n; delete this.$tm; i18n.__deleteInstance(instance); delete this.$i18n; } }; } function mergeToRoot(root, options) { root.locale = options.locale || root.locale; root.fallbackLocale = options.fallbackLocale || root.fallbackLocale; root.missing = options.missing || root.missing; root.silentTranslationWarn = options.silentTranslationWarn || root.silentFallbackWarn; root.silentFallbackWarn = options.silentFallbackWarn || root.silentFallbackWarn; root.formatFallbackMessages = options.formatFallbackMessages || root.formatFallbackMessages; root.postTranslation = options.postTranslation || root.postTranslation; root.warnHtmlInMessage = options.warnHtmlInMessage || root.warnHtmlInMessage; root.escapeParameterHtml = options.escapeParameterHtml || root.escapeParameterHtml; root.sync = options.sync || root.sync; root.__composer[SetPluralRulesSymbol](options.pluralizationRules || root.pluralizationRules); const messages = getLocaleMessages(root.locale, { messages: options.messages, __i18n: options.__i18n }); Object.keys(messages).forEach(locale => root.mergeLocaleMessage(locale, messages[locale])); if (options.datetimeFormats) { Object.keys(options.datetimeFormats).forEach(locale => root.mergeDateTimeFormat(locale, options.datetimeFormats[locale])); } if (options.numberFormats) { Object.keys(options.numberFormats).forEach(locale => root.mergeNumberFormat(locale, options.numberFormats[locale])); } return root; } /** * Vue I18n factory * * @param options - An options, see the {@link I18nOptions} * * @returns {@link I18n} instance * * @remarks * If you use Legacy API mode, you need toto specify {@link VueI18nOptions} and `legacy: true` option. * * If you use composition API mode, you need to specify {@link ComposerOptions}. * * @VueI18nSee [Getting Started](../../guide/) * @VueI18nSee [Composition API](../../guide/advanced/composition) * * @example * case: for Legacy API * ```js * import { createApp } from 'vue' * import { createI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * // ... * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @example * case: for composition API * ```js * import { createApp } from 'vue' * import { createI18n, useI18n } from 'vue-i18n' * * // call with I18n option * const i18n = createI18n({ * legacy: false, // you must specify 'legacy: false' option * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * * const App = { * setup() { * // ... * const { t } = useI18n({ ... }) * return { ... , t } * } * } * * const app = createApp(App) * * // install! * app.use(i18n) * app.mount('#app') * ``` * * @VueI18nGeneral */ function createI18n(options = {}) { // prettier-ignore const __legacyMode = __VUE_I18N_LEGACY_API__ && isBoolean(options.legacy) ? options.legacy : __VUE_I18N_LEGACY_API__; const __globalInjection = !!options.globalInjection; const __instances = new Map(); // prettier-ignore const __global = __VUE_I18N_LEGACY_API__ && __legacyMode ? createVueI18n(options) : createComposer(options); const symbol = makeSymbol((process.env.NODE_ENV !== 'production') ? 'vue-i18n' : ''); const i18n = { // mode get mode() { // prettier-ignore return __VUE_I18N_LEGACY_API__ ? __legacyMode ? 'legacy' : 'composition' : 'composition'; }, // install plugin async install(app, ...options) { if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) { app.__VUE_I18N__ = i18n; } // setup global provider app.__VUE_I18N_SYMBOL__ = symbol; app.provide(app.__VUE_I18N_SYMBOL__, i18n); // global method and properties injection for Composition API if (!__legacyMode && __globalInjection) { injectGlobalFields(app, i18n.global); } // install built-in components and directive if (__VUE_I18N_FULL_INSTALL__) { apply(app, i18n, ...options); } // setup mixin for Legacy API if (__VUE_I18N_LEGACY_API__ && __legacyMode) { app.mixin(defineMixin(__global, __global.__composer, i18n)); } // setup vue-devtools plugin if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false) { const ret = await enableDevTools(app, i18n); if (!ret) { throw createI18nError(21 /* CANNOT_SETUP_VUE_DEVTOOLS_PLUGIN */); } const emitter = createEmitter(); if (__legacyMode) { const _vueI18n = __global; _vueI18n.__enableEmitter && _vueI18n.__enableEmitter(emitter); } else { // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = __global; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); } emitter.on('*', addTimelineEvent); } }, // global accessor get global() { return __global; }, // @internal __instances, // @internal __getInstance(component) { return __instances.get(component) || null; }, // @internal __setInstance(component, instance) { __instances.set(component, instance); }, // @internal __deleteInstance(component) { __instances.delete(component); } }; return i18n; } /** * Use Composition API for Vue I18n * * @param options - An options, see {@link UseI18nOptions} * * @returns {@link Composer} instance * * @remarks * This function is mainly used by `setup`. * * If options are specified, Composer instance is created for each component and you can be localized on the component. * * If options are not specified, you can be localized using the global Composer. * * @example * case: Component resource base localization * ```html * <template> * <form> * <label>{{ t('language') }}</label> * <select v-model="locale"> * <option value="en">en</option> * <option value="ja">ja</option> * </select> * </form> * <p>message: {{ t('hello') }}</p> * </template> * * <script> * import { useI18n } from 'vue-i18n' * * export default { * setup() { * const { t, locale } = useI18n({ * locale: 'ja', * messages: { * en: { ... }, * ja: { ... } * } * }) * // Something to do ... * * return { ..., t, locale } * } * } * </script> * ``` * * @VueI18nComposition */ function useI18n(options = {}) { const instance = getCurrentInstance(); if (instance == null) { throw createI18nError(16 /* MUST_BE_CALL_SETUP_TOP */); } if (!instance.appContext.app.__VUE_I18N_SYMBOL__) { throw createI18nError(17 /* NOT_INSLALLED */); } const i18n = inject(instance.appContext.app.__VUE_I18N_SYMBOL__); /* istanbul ignore if */ if (!i18n) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } // prettier-ignore const global = i18n.mode === 'composition' ? i18n.global : i18n.global.__composer; // prettier-ignore const scope = isEmptyObject(options) ? ('__i18n' in instance.type) ? 'local' : 'global' : !options.useScope ? 'local' : options.useScope; if (scope === 'global') { let messages = isObject(options.messages) ? options.messages : {}; if ('__i18nGlobal' in instance.type) { messages = getLocaleMessages(global.locale.value, { messages, __i18n: instance.type.__i18nGlobal }); } // merge locale messages const locales = Object.keys(messages); if (locales.length) { locales.forEach(locale => { global.mergeLocaleMessage(locale, messages[locale]); }); } // merge datetime formats if (isObject(options.datetimeFormats)) { const locales = Object.keys(options.datetimeFormats); if (locales.length) { locales.forEach(locale => { global.mergeDateTimeFormat(locale, options.datetimeFormats[locale]); }); } } // merge number formats if (isObject(options.numberFormats)) { const locales = Object.keys(options.numberFormats); if (locales.length) { locales.forEach(locale => { global.mergeNumberFormat(locale, options.numberFormats[locale]); }); } } return global; } if (scope === 'parent') { let composer = getComposer$1(i18n, instance); if (composer == null) { if ((process.env.NODE_ENV !== 'production')) { warn(getWarnMessage(12 /* NOT_FOUND_PARENT_SCOPE */)); } composer = global; } return composer; } // scope 'local' case if (i18n.mode === 'legacy') { throw createI18nError(18 /* NOT_AVAILABLE_IN_LEGACY_MODE */); } const i18nInternal = i18n; let composer = i18nInternal.__getInstance(instance); if (composer == null) { const type = instance.type; const composerOptions = { ...options }; if (type.__i18n) { composerOptions.__i18n = type.__i18n; } if (global) { composerOptions.__root = global; } composer = createComposer(composerOptions); setupLifeCycle(i18nInternal, instance, composer); i18nInternal.__setInstance(instance, composer); } return composer; } function getComposer$1(i18n, target) { let composer = null; const root = target.root; let current = target.parent; while (current != null) { const i18nInternal = i18n; if (i18n.mode === 'composition') { composer = i18nInternal.__getInstance(current); } else { const vueI18n = i18nInternal.__getInstance(current); if (vueI18n != null) { composer = vueI18n .__composer; } } if (composer != null) { break; } if (root === current) { break; } current = current.parent; } return composer; } function setupLifeCycle(i18n, target, composer) { let emitter = null; onMounted(() => { // inject composer instance to DOM for intlify-devtools if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false && target.vnode.el) { target.vnode.el.__INTLIFY__ = composer; emitter = createEmitter(); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[EnableEmitter] && _composer[EnableEmitter](emitter); emitter.on('*', addTimelineEvent); } }, target); onUnmounted(() => { // remove composer instance from DOM for intlify-devtools if (((process.env.NODE_ENV !== 'production') || __INTLIFY_PROD_DEVTOOLS__) && !false && target.vnode.el && target.vnode.el.__INTLIFY__) { emitter && emitter.off('*', addTimelineEvent); // eslint-disable-next-line @typescript-eslint/no-explicit-any const _composer = composer; _composer[DisableEmitter] && _composer[DisableEmitter](); delete target.vnode.el.__INTLIFY__; } i18n.__deleteInstance(target); }, target); } const globalExportProps = [ 'locale', 'fallbackLocale', 'availableLocales' ]; const globalExportMethods = ['t', 'd', 'n', 'tm']; function injectGlobalFields(app, composer) { const i18n = Object.create(null); globalExportProps.forEach(prop => { const desc = Object.getOwnPropertyDescriptor(composer, prop); if (!desc) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } const wrap = isRef(desc.value) // check computed props ? { get() { return desc.value.value; }, // eslint-disable-next-line @typescript-eslint/no-explicit-any set(val) { desc.value.value = val; } } : { get() { return desc.get && desc.get(); } }; Object.defineProperty(i18n, prop, wrap); }); app.config.globalProperties.$i18n = i18n; globalExportMethods.forEach(method => { const desc = Object.getOwnPropertyDescriptor(composer, method); if (!desc) { throw createI18nError(22 /* UNEXPECTED_ERROR */); } Object.defineProperty(app.config.globalProperties, `$${method}`, desc); }); } { initFeatureFlags(); } (process.env.NODE_ENV !== 'production') && initDev(); export { DatetimeFormat, NumberFormat, Translation, VERSION, createI18n, useI18n, vTDirective };
cdnjs/cdnjs
ajax/libs/vue-i18n/9.0.0/vue-i18n.runtime.esm-bundler.js
JavaScript
mit
73,202
/*! * froala_editor v3.2.5 (https://www.froala.com/wysiwyg-editor) * License https://froala.com/wysiwyg-editor/terms/ * Copyright 2014-2020 Froala Labs */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('froala-editor')) : typeof define === 'function' && define.amd ? define(['froala-editor'], factory) : (factory(global.FroalaEditor)); }(this, (function (FE) { 'use strict'; FE = FE && FE.hasOwnProperty('default') ? FE['default'] : FE; /** * Portuguese spoken in Portugal */ FE.LANGUAGE['pt_pt'] = { translation: { // Place holder 'Type something': 'Digite algo', // Basic formatting 'Bold': 'Negrito', 'Italic': "It\xE1lico", 'Underline': 'Sublinhado', 'Strikethrough': 'Rasurado', // Main buttons 'Insert': 'Inserir', 'Delete': 'Apagar', 'Cancel': 'Cancelar', 'OK': 'Ok', 'Back': 'Voltar', 'Remove': 'Remover', 'More': 'Mais', 'Update': 'Atualizar', 'Style': 'Estilo', // Font 'Font Family': 'Fonte', 'Font Size': 'Tamanho da fonte', // Colors 'Colors': 'Cores', 'Background': 'Fundo', 'Text': 'Texto', 'HEX Color': 'Cor hexadecimal', // Paragraphs 'Paragraph Format': 'Formatos', 'Normal': 'Normal', 'Code': "C\xF3digo", 'Heading 1': "Cabe\xE7alho 1", 'Heading 2': "Cabe\xE7alho 2", 'Heading 3': "Cabe\xE7alho 3", 'Heading 4': "Cabe\xE7alho 4", // Style 'Paragraph Style': "Estilo de par\xE1grafo", 'Inline Style': 'Estilo embutido', // Alignment 'Align': 'Alinhar', 'Align Left': "Alinhar \xE0 esquerda", 'Align Center': 'Alinhar ao centro', 'Align Right': "Alinhar \xE0 direita", 'Align Justify': 'Justificado', 'None': 'Nenhum', // Lists 'Ordered List': 'Lista ordenada', 'Unordered List': "Lista n\xE3o ordenada", // Indent 'Decrease Indent': "Diminuir avan\xE7o", 'Increase Indent': "Aumentar avan\xE7o", // Links 'Insert Link': 'Inserir link', 'Open in new tab': 'Abrir em uma nova aba', 'Open Link': 'Abrir link', 'Edit Link': 'Editar link', 'Unlink': 'Remover link', 'Choose Link': 'Escolha o link', // Images 'Insert Image': 'Inserir imagem', 'Upload Image': 'Carregar imagem', 'By URL': 'Por URL', 'Browse': 'Procurar', 'Drop image': 'Largue imagem', 'or click': 'ou clique em', 'Manage Images': 'Gerenciar as imagens', 'Loading': 'Carregando', 'Deleting': 'Excluindo', 'Tags': 'Etiquetas', 'Are you sure? Image will be deleted.': "Voc\xEA tem certeza? Imagem ser\xE1 apagada.", 'Replace': 'Substituir', 'Uploading': 'Carregando', 'Loading image': 'Carregando imagem', 'Display': 'Exibir', 'Inline': 'Em linha', 'Break Text': 'Texto de quebra', 'Alternative Text': 'Texto alternativo', 'Change Size': 'Alterar tamanho', 'Width': 'Largura', 'Height': 'Altura', 'Something went wrong. Please try again.': 'Algo deu errado. Por favor, tente novamente.', 'Image Caption': 'Legenda da imagem', 'Advanced Edit': 'Edição avançada', // Video 'Insert Video': "Inserir v\xEDdeo", 'Embedded Code': "C\xF3digo embutido", 'Paste in a video URL': 'Colar em um URL de vídeo', 'Drop video': 'Solte o video', 'Your browser does not support HTML5 video.': 'Seu navegador não suporta o vídeo html5.', 'Upload Video': 'Envio vídeo', // Tables 'Insert Table': 'Inserir tabela', 'Table Header': "Cabe\xE7alho da tabela", 'Remove Table': 'Remover tabela', 'Table Style': 'estilo de tabela', 'Horizontal Align': 'Alinhamento horizontal', 'Row': 'Linha', 'Insert row above': 'Inserir linha antes', 'Insert row below': 'Inserir linha depois', 'Delete row': 'Eliminar linha', 'Column': 'Coluna', 'Insert column before': 'Inserir coluna antes', 'Insert column after': 'Inserir coluna depois', 'Delete column': 'Eliminar coluna', 'Cell': "C\xE9lula", 'Merge cells': "Unir c\xE9lulas", 'Horizontal split': "Divis\xE3o horizontal", 'Vertical split': "Divis\xE3o vertical", 'Cell Background': "Fundo da c\xE9lula", 'Vertical Align': 'Alinhar vertical', 'Top': 'Topo', 'Middle': 'Meio', 'Bottom': 'Fundo', 'Align Top': 'Alinhar topo', 'Align Middle': 'Alinhar meio', 'Align Bottom': 'Alinhar fundo', 'Cell Style': "Estilo de c\xE9lula", // Files 'Upload File': 'Upload de arquivo', 'Drop file': 'Largar arquivo', // Emoticons 'Emoticons': 'Emoticons', 'Grinning face': 'Sorrindo a cara', 'Grinning face with smiling eyes': 'Sorrindo rosto com olhos sorridentes', 'Face with tears of joy': "Rosto com l\xE1grimas de alegria", 'Smiling face with open mouth': 'Rosto de sorriso com a boca aberta', 'Smiling face with open mouth and smiling eyes': 'Rosto de sorriso com a boca aberta e olhos sorridentes', 'Smiling face with open mouth and cold sweat': 'Rosto de sorriso com a boca aberta e suor frio', 'Smiling face with open mouth and tightly-closed eyes': 'Rosto de sorriso com a boca aberta e os olhos bem fechados', 'Smiling face with halo': 'Rosto de sorriso com halo', 'Smiling face with horns': 'Rosto de sorriso com chifres', 'Winking face': 'Pisc a rosto', 'Smiling face with smiling eyes': 'Rosto de sorriso com olhos sorridentes', 'Face savoring delicious food': 'Rosto saboreando uma deliciosa comida', 'Relieved face': 'Rosto aliviado', 'Smiling face with heart-shaped eyes': "Rosto de sorriso com os olhos em forma de cora\xE7\xE3o", 'Smiling face with sunglasses': "Rosto de sorriso com \xF3culos de sol", 'Smirking face': 'Rosto sorridente', 'Neutral face': 'Rosto neutra', 'Expressionless face': 'Rosto inexpressivo', 'Unamused face': "O rosto n\xE3o divertido", 'Face with cold sweat': 'Rosto com suor frio', 'Pensive face': 'O rosto pensativo', 'Confused face': 'Cara confusa', 'Confounded face': "Rosto at\xF4nito", 'Kissing face': 'Beijar Rosto', 'Face throwing a kiss': 'Rosto jogando um beijo', 'Kissing face with smiling eyes': 'Beijar rosto com olhos sorridentes', 'Kissing face with closed eyes': 'Beijando a cara com os olhos fechados', 'Face with stuck out tongue': "Preso de cara com a l\xEDngua para fora", 'Face with stuck out tongue and winking eye': "Rosto com estendeu a l\xEDngua e olho piscando", 'Face with stuck out tongue and tightly-closed eyes': 'Rosto com estendeu a língua e os olhos bem fechados', 'Disappointed face': 'Rosto decepcionado', 'Worried face': 'O rosto preocupado', 'Angry face': 'Rosto irritado', 'Pouting face': 'Beicinho Rosto', 'Crying face': 'Cara de choro', 'Persevering face': 'Perseverar Rosto', 'Face with look of triumph': 'Rosto com olhar de triunfo', 'Disappointed but relieved face': 'Fiquei Desapontado mas aliviado Rosto', 'Frowning face with open mouth': 'Sobrancelhas franzidas rosto com a boca aberta', 'Anguished face': 'O rosto angustiado', 'Fearful face': 'Cara com medo', 'Weary face': 'Rosto cansado', 'Sleepy face': 'Cara de sono', 'Tired face': 'Rosto cansado', 'Grimacing face': 'Fazendo caretas face', 'Loudly crying face': 'Alto chorando rosto', 'Face with open mouth': 'Enfrentar com a boca aberta', 'Hushed face': 'Flagrantes de rosto', 'Face with open mouth and cold sweat': 'Enfrentar com a boca aberta e suor frio', 'Face screaming in fear': 'Cara gritando de medo', 'Astonished face': 'Cara de surpresa', 'Flushed face': 'Rosto vermelho', 'Sleeping face': 'O rosto de sono', 'Dizzy face': 'Cara tonto', 'Face without mouth': 'Rosto sem boca', 'Face with medical mask': "Rosto com m\xE1scara m\xE9dica", // Line breaker 'Break': 'Partir', // Math 'Subscript': 'Subscrito', 'Superscript': 'Sobrescrito', // Full screen 'Fullscreen': 'Tela cheia', // Horizontal line 'Insert Horizontal Line': 'Inserir linha horizontal', // Clear formatting 'Clear Formatting': "Remover formata\xE7\xE3o", // Save 'Save': "Salve", // Undo, redo 'Undo': 'Anular', 'Redo': 'Restaurar', // Select all 'Select All': 'Seleccionar tudo', // Code view 'Code View': "Exibi\xE7\xE3o de c\xF3digo", // Quote 'Quote': "Cita\xE7\xE3o", 'Increase': 'Aumentar', 'Decrease': 'Diminuir', // Quick Insert 'Quick Insert': "Inser\xE7\xE3o r\xE1pida", // Spcial Characters 'Special Characters': 'Caracteres especiais', 'Latin': 'Latino', 'Greek': 'Grego', 'Cyrillic': 'Cirílico', 'Punctuation': 'Pontuação', 'Currency': 'Moeda', 'Arrows': 'Setas; flechas', 'Math': 'Matemática', 'Misc': 'Misc', // Print. 'Print': 'Impressão', // Spell Checker. 'Spell Checker': 'Verificador ortográfico', // Help 'Help': 'Socorro', 'Shortcuts': 'Atalhos', 'Inline Editor': 'Editor em linha', 'Show the editor': 'Mostre o editor', 'Common actions': 'Ações comuns', 'Copy': 'Cópia de', 'Cut': 'Cortar', 'Paste': 'Colar', 'Basic Formatting': 'Formatação básica', 'Increase quote level': 'Aumentar o nível de cotação', 'Decrease quote level': 'Diminuir o nível de cotação', 'Image / Video': 'Imagem / video', 'Resize larger': 'Redimensionar maior', 'Resize smaller': 'Redimensionar menor', 'Table': 'Tabela', 'Select table cell': 'Selecione a célula da tabela', 'Extend selection one cell': 'Ampliar a seleção de uma célula', 'Extend selection one row': 'Ampliar a seleção uma linha', 'Navigation': 'Navegação', 'Focus popup / toolbar': 'Foco popup / barra de ferramentas', 'Return focus to previous position': 'Retornar o foco para a posição anterior', // Embed.ly 'Embed URL': 'URL de inserção', 'Paste in a URL to embed': 'Colar em url para incorporar', // Word Paste. 'The pasted content is coming from a Microsoft Word document. Do you want to keep the format or clean it up?': 'O conteúdo colado vem de um documento Microsoft Word. Você quer manter o formato ou limpá-lo?', 'Keep': 'Guarda', 'Clean': 'Limpar limpo', 'Word Paste Detected': 'Pasta de palavras detectada', // Character Counter 'Characters': 'Caracteres', // More Buttons 'More Text': 'Mais Texto', 'More Paragraph': 'Mais Parágrafo', 'More Rich': 'Mais Rico', 'More Misc': 'Mais Misc' }, direction: 'ltr' }; }))); //# sourceMappingURL=pt_pt.js.map
cdnjs/cdnjs
ajax/libs/froala-editor/3.2.5/js/languages/pt_pt.js
JavaScript
mit
11,192
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var __chunk_1 = require('./chunk-14c82365.js'); require('./helpers.js'); var __chunk_2 = require('./chunk-185921d7.js'); var __chunk_4 = require('./chunk-925c5339.js'); var __chunk_5 = require('./chunk-13e039f5.js'); var script = { name: 'BRate', components: __chunk_1._defineProperty({}, __chunk_4.Icon.name, __chunk_4.Icon), props: { value: { type: Number, default: 0 }, max: { type: Number, default: 5 }, icon: { type: String, default: 'star' }, iconPack: String, size: String, spaced: Boolean, rtl: Boolean, disabled: Boolean, showScore: Boolean, showText: Boolean, customText: String, texts: Array, locale: { type: [String, Array], default: function _default() { return __chunk_2.config.defaultLocale; } } }, data: function data() { return { newValue: this.value, hoverValue: 0 }; }, computed: { halfStyle: function halfStyle() { return "width:".concat(this.valueDecimal, "%"); }, showMe: function showMe() { var result = ''; if (this.showScore) { result = this.disabled ? this.value : this.newValue; if (result === 0) { result = ''; } else { result = new Intl.NumberFormat(this.locale).format(this.value); } } else if (this.showText) { result = this.texts[Math.ceil(this.newValue) - 1]; } return result; }, valueDecimal: function valueDecimal() { return this.value * 100 - Math.floor(this.value) * 100; } }, watch: { // When v-model is changed set the new value. value: function value(_value) { this.newValue = _value; } }, methods: { resetNewValue: function resetNewValue() { if (this.disabled) return; this.hoverValue = 0; }, previewRate: function previewRate(index, event) { if (this.disabled) return; this.hoverValue = index; event.stopPropagation(); }, confirmValue: function confirmValue(index) { if (this.disabled) return; this.newValue = index; this.$emit('change', this.newValue); this.$emit('input', this.newValue); }, checkHalf: function checkHalf(index) { var showWhenDisabled = this.disabled && this.valueDecimal > 0 && index - 1 < this.value && index > this.value; return showWhenDisabled; }, rateClass: function rateClass(index) { var output = ''; var currentValue = this.hoverValue !== 0 ? this.hoverValue : this.newValue; if (index <= currentValue) { output = 'set-on'; } else if (this.disabled && Math.ceil(this.value) === index) { output = 'set-half'; } return output; } } }; /* script */ const __vue_script__ = script; /* template */ var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"rate",class:{ 'is-disabled': _vm.disabled, 'is-spaced': _vm.spaced, 'is-rtl': _vm.rtl }},[_vm._l((_vm.max),function(item,index){return _c('div',{key:index,staticClass:"rate-item",class:_vm.rateClass(item),on:{"mousemove":function($event){return _vm.previewRate(item, $event)},"mouseleave":_vm.resetNewValue,"click":function($event){$event.preventDefault();return _vm.confirmValue(item)}}},[_c('b-icon',{attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}),(_vm.checkHalf(item))?_c('b-icon',{staticClass:"is-half",style:(_vm.halfStyle),attrs:{"pack":_vm.iconPack,"icon":_vm.icon,"size":_vm.size}}):_vm._e()],1)}),(_vm.showText || _vm.showScore || _vm.customText)?_c('div',{staticClass:"rate-text",class:_vm.size},[_c('span',[_vm._v(_vm._s(_vm.showMe))]),(_vm.customText && !_vm.showText)?_c('span',[_vm._v(_vm._s(_vm.customText))]):_vm._e()]):_vm._e()],2)}; var __vue_staticRenderFns__ = []; /* style */ const __vue_inject_styles__ = undefined; /* scoped */ const __vue_scope_id__ = undefined; /* module identifier */ const __vue_module_identifier__ = undefined; /* functional template */ const __vue_is_functional_template__ = false; /* style inject */ /* style inject SSR */ var Rate = __chunk_5.__vue_normalize__( { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, undefined, undefined ); var Plugin = { install: function install(Vue) { __chunk_5.registerComponent(Vue, Rate); } }; __chunk_5.use(Plugin); exports.BRate = Rate; exports.default = Plugin;
cdnjs/cdnjs
ajax/libs/buefy/0.9.3/cjs/rate.js
JavaScript
mit
4,726
/*! UIkit 3.6.13 | https://www.getuikit.com | (c) 2014 - 2021 YOOtheme | MIT License */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory(require('uikit-util')) : typeof define === 'function' && define.amd ? define('uikitlightbox', ['uikit-util'], factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.UIkitLightbox = factory(global.UIkit.util)); }(this, (function (uikitUtil) { 'use strict'; var Animations = { slide: { show: function(dir) { return [ {transform: translate(dir * -100)}, {transform: translate()} ]; }, percent: function(current) { return translated(current); }, translate: function(percent, dir) { return [ {transform: translate(dir * -100 * percent)}, {transform: translate(dir * 100 * (1 - percent))} ]; } } }; function translated(el) { return Math.abs(uikitUtil.css(el, 'transform').split(',')[4] / el.offsetWidth) || 0; } function translate(value, unit) { if ( value === void 0 ) value = 0; if ( unit === void 0 ) unit = '%'; value += value ? unit : ''; return uikitUtil.isIE ? ("translateX(" + value + ")") : ("translate3d(" + value + ", 0, 0)"); // currently not translate3d in IE, translate3d within translate3d does not work while transitioning } function scale3d(value) { return ("scale3d(" + value + ", " + value + ", 1)"); } var Animations$1 = uikitUtil.assign({}, Animations, { fade: { show: function() { return [ {opacity: 0}, {opacity: 1} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent}, {opacity: percent} ]; } }, scale: { show: function() { return [ {opacity: 0, transform: scale3d(1 - .2)}, {opacity: 1, transform: scale3d(1)} ]; }, percent: function(current) { return 1 - uikitUtil.css(current, 'opacity'); }, translate: function(percent) { return [ {opacity: 1 - percent, transform: scale3d(1 - .2 * percent)}, {opacity: percent, transform: scale3d(1 - .2 + .2 * percent)} ]; } } }); var Container = { props: { container: Boolean }, data: { container: true }, computed: { container: function(ref) { var container = ref.container; return container === true && this.$container || container && uikitUtil.$(container); } } }; var Class = { connected: function() { !uikitUtil.hasClass(this.$el, this.$name) && uikitUtil.addClass(this.$el, this.$name); } }; var Togglable = { props: { cls: Boolean, animation: 'list', duration: Number, origin: String, transition: String }, data: { cls: false, animation: [false], duration: 200, origin: false, transition: 'linear', clsEnter: 'uk-togglabe-enter', clsLeave: 'uk-togglabe-leave', initProps: { overflow: '', height: '', paddingTop: '', paddingBottom: '', marginTop: '', marginBottom: '' }, hideProps: { overflow: 'hidden', height: 0, paddingTop: 0, paddingBottom: 0, marginTop: 0, marginBottom: 0 } }, computed: { hasAnimation: function(ref) { var animation = ref.animation; return !!animation[0]; }, hasTransition: function(ref) { var animation = ref.animation; return this.hasAnimation && animation[0] === true; } }, methods: { toggleElement: function(targets, toggle, animate) { var this$1 = this; return new uikitUtil.Promise(function (resolve) { return uikitUtil.Promise.all(uikitUtil.toNodes(targets).map(function (el) { var show = uikitUtil.isBoolean(toggle) ? toggle : !this$1.isToggled(el); if (!uikitUtil.trigger(el, ("before" + (show ? 'show' : 'hide')), [this$1])) { return uikitUtil.Promise.reject(); } var promise = ( uikitUtil.isFunction(animate) ? animate : animate === false || !this$1.hasAnimation ? this$1._toggle : this$1.hasTransition ? toggleHeight(this$1) : toggleAnimation(this$1) )(el, show) || uikitUtil.Promise.resolve(); uikitUtil.addClass(el, show ? this$1.clsEnter : this$1.clsLeave); uikitUtil.trigger(el, show ? 'show' : 'hide', [this$1]); promise .catch(uikitUtil.noop) .then(function () { return uikitUtil.removeClass(el, show ? this$1.clsEnter : this$1.clsLeave); }); return promise.then(function () { uikitUtil.removeClass(el, show ? this$1.clsEnter : this$1.clsLeave); uikitUtil.trigger(el, show ? 'shown' : 'hidden', [this$1]); this$1.$update(el); }); })).then(resolve, uikitUtil.noop); } ); }, isToggled: function(el) { if ( el === void 0 ) el = this.$el; return uikitUtil.hasClass(el, this.clsEnter) ? true : uikitUtil.hasClass(el, this.clsLeave) ? false : this.cls ? uikitUtil.hasClass(el, this.cls.split(' ')[0]) : !uikitUtil.hasAttr(el, 'hidden'); }, _toggle: function(el, toggled) { if (!el) { return; } toggled = Boolean(toggled); var changed; if (this.cls) { changed = uikitUtil.includes(this.cls, ' ') || toggled !== uikitUtil.hasClass(el, this.cls); changed && uikitUtil.toggleClass(el, this.cls, uikitUtil.includes(this.cls, ' ') ? undefined : toggled); } else { changed = toggled === el.hidden; changed && (el.hidden = !toggled); } uikitUtil.$$('[autofocus]', el).some(function (el) { return uikitUtil.isVisible(el) ? el.focus() || true : el.blur(); }); if (changed) { uikitUtil.trigger(el, 'toggled', [toggled, this]); this.$update(el); } } } }; function toggleHeight(ref) { var isToggled = ref.isToggled; var duration = ref.duration; var initProps = ref.initProps; var hideProps = ref.hideProps; var transition = ref.transition; var _toggle = ref._toggle; return function (el, show) { var inProgress = uikitUtil.Transition.inProgress(el); var inner = el.hasChildNodes ? uikitUtil.toFloat(uikitUtil.css(el.firstElementChild, 'marginTop')) + uikitUtil.toFloat(uikitUtil.css(el.lastElementChild, 'marginBottom')) : 0; var currentHeight = uikitUtil.isVisible(el) ? uikitUtil.height(el) + (inProgress ? 0 : inner) : 0; uikitUtil.Transition.cancel(el); if (!isToggled(el)) { _toggle(el, true); } uikitUtil.height(el, ''); // Update child components first uikitUtil.fastdom.flush(); var endHeight = uikitUtil.height(el) + (inProgress ? 0 : inner); uikitUtil.height(el, currentHeight); return (show ? uikitUtil.Transition.start(el, uikitUtil.assign({}, initProps, {overflow: 'hidden', height: endHeight}), Math.round(duration * (1 - currentHeight / endHeight)), transition) : uikitUtil.Transition.start(el, hideProps, Math.round(duration * (currentHeight / endHeight)), transition).then(function () { return _toggle(el, false); }) ).then(function () { return uikitUtil.css(el, initProps); }); }; } function toggleAnimation(cmp) { return function (el, show) { uikitUtil.Animation.cancel(el); var animation = cmp.animation; var duration = cmp.duration; var _toggle = cmp._toggle; if (show) { _toggle(el, true); return uikitUtil.Animation.in(el, animation[0], duration, cmp.origin); } return uikitUtil.Animation.out(el, animation[1] || animation[0], duration, cmp.origin).then(function () { return _toggle(el, false); }); }; } var active = []; var Modal = { mixins: [Class, Container, Togglable], props: { selPanel: String, selClose: String, escClose: Boolean, bgClose: Boolean, stack: Boolean }, data: { cls: 'uk-open', escClose: true, bgClose: true, overlay: true, stack: false }, computed: { panel: function(ref, $el) { var selPanel = ref.selPanel; return uikitUtil.$(selPanel, $el); }, transitionElement: function() { return this.panel; }, bgClose: function(ref) { var bgClose = ref.bgClose; return bgClose && this.panel; } }, beforeDisconnect: function() { if (this.isToggled()) { this.toggleElement(this.$el, false, false); } }, events: [ { name: 'click', delegate: function() { return this.selClose; }, handler: function(e) { e.preventDefault(); this.hide(); } }, { name: 'toggle', self: true, handler: function(e) { if (e.defaultPrevented) { return; } e.preventDefault(); if (this.isToggled() === uikitUtil.includes(active, this)) { this.toggle(); } } }, { name: 'beforeshow', self: true, handler: function(e) { if (uikitUtil.includes(active, this)) { return false; } if (!this.stack && active.length) { uikitUtil.Promise.all(active.map(function (modal) { return modal.hide(); })).then(this.show); e.preventDefault(); } else { active.push(this); } } }, { name: 'show', self: true, handler: function() { var this$1 = this; if (uikitUtil.width(window) - uikitUtil.width(document) && this.overlay) { uikitUtil.css(document.body, 'overflowY', 'scroll'); } if (this.stack) { uikitUtil.css(this.$el, 'zIndex', uikitUtil.toFloat(uikitUtil.css(this.$el, 'zIndex')) + active.length); } uikitUtil.addClass(document.documentElement, this.clsPage); if (this.bgClose) { uikitUtil.once(this.$el, 'hide', uikitUtil.on(document, uikitUtil.pointerDown, function (ref) { var target = ref.target; if (uikitUtil.last(active) !== this$1 || this$1.overlay && !uikitUtil.within(target, this$1.$el) || uikitUtil.within(target, this$1.panel)) { return; } uikitUtil.once(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel + " scroll"), function (ref) { var defaultPrevented = ref.defaultPrevented; var type = ref.type; var newTarget = ref.target; if (!defaultPrevented && type === uikitUtil.pointerUp && target === newTarget) { this$1.hide(); } }, true); }), {self: true}); } if (this.escClose) { uikitUtil.once(this.$el, 'hide', uikitUtil.on(document, 'keydown', function (e) { if (e.keyCode === 27 && uikitUtil.last(active) === this$1) { this$1.hide(); } }), {self: true}); } } }, { name: 'hidden', self: true, handler: function() { var this$1 = this; active.splice(active.indexOf(this), 1); if (!active.length) { uikitUtil.css(document.body, 'overflowY', ''); } uikitUtil.css(this.$el, 'zIndex', ''); if (!active.some(function (modal) { return modal.clsPage === this$1.clsPage; })) { uikitUtil.removeClass(document.documentElement, this.clsPage); } } } ], methods: { toggle: function() { return this.isToggled() ? this.hide() : this.show(); }, show: function() { var this$1 = this; if (this.isToggled()) { return uikitUtil.Promise.resolve(); } if (this.container && uikitUtil.parent(this.$el) !== this.container) { uikitUtil.append(this.container, this.$el); return new uikitUtil.Promise(function (resolve) { return requestAnimationFrame(function () { return this$1.show().then(resolve); } ); } ); } return this.toggleElement(this.$el, true, animate(this)); }, hide: function() { if (!this.isToggled()) { return uikitUtil.Promise.resolve(); } return this.toggleElement(this.$el, false, animate(this)); } } }; function animate(ref) { var transitionElement = ref.transitionElement; var _toggle = ref._toggle; return function (el, show) { return new uikitUtil.Promise(function (resolve, reject) { return uikitUtil.once(el, 'show hide', function () { el._reject && el._reject(); el._reject = reject; _toggle(el, show); var off = uikitUtil.once(transitionElement, 'transitionstart', function () { uikitUtil.once(transitionElement, 'transitionend transitioncancel', resolve, {self: true}); clearTimeout(timer); }, {self: true}); var timer = setTimeout(function () { off(); resolve(); }, uikitUtil.toMs(uikitUtil.css(transitionElement, 'transitionDuration'))); }); } ).then(function () { return delete el._reject; }); }; } function Transitioner(prev, next, dir, ref) { var animation = ref.animation; var easing = ref.easing; var percent = animation.percent; var translate = animation.translate; var show = animation.show; if ( show === void 0 ) show = uikitUtil.noop; var props = show(dir); var deferred = new uikitUtil.Deferred(); return { dir: dir, show: function(duration, percent, linear) { var this$1 = this; if ( percent === void 0 ) percent = 0; var timing = linear ? 'linear' : easing; duration -= Math.round(duration * uikitUtil.clamp(percent, -1, 1)); this.translate(percent); triggerUpdate(next, 'itemin', {percent: percent, duration: duration, timing: timing, dir: dir}); triggerUpdate(prev, 'itemout', {percent: 1 - percent, duration: duration, timing: timing, dir: dir}); uikitUtil.Promise.all([ uikitUtil.Transition.start(next, props[1], duration, timing), uikitUtil.Transition.start(prev, props[0], duration, timing) ]).then(function () { this$1.reset(); deferred.resolve(); }, uikitUtil.noop); return deferred.promise; }, cancel: function() { uikitUtil.Transition.cancel([next, prev]); }, reset: function() { for (var prop in props[0]) { uikitUtil.css([next, prev], prop, ''); } }, forward: function(duration, percent) { if ( percent === void 0 ) percent = this.percent(); uikitUtil.Transition.cancel([next, prev]); return this.show(duration, percent, true); }, translate: function(percent) { this.reset(); var props = translate(percent, dir); uikitUtil.css(next, props[1]); uikitUtil.css(prev, props[0]); triggerUpdate(next, 'itemtranslatein', {percent: percent, dir: dir}); triggerUpdate(prev, 'itemtranslateout', {percent: 1 - percent, dir: dir}); }, percent: function() { return percent(prev || next, next, dir); }, getDistance: function() { return prev && prev.offsetWidth; } }; } function triggerUpdate(el, type, data) { uikitUtil.trigger(el, uikitUtil.createEvent(type, false, false, data)); } var SliderAutoplay = { props: { autoplay: Boolean, autoplayInterval: Number, pauseOnHover: Boolean }, data: { autoplay: false, autoplayInterval: 7000, pauseOnHover: true }, connected: function() { this.autoplay && this.startAutoplay(); }, disconnected: function() { this.stopAutoplay(); }, update: function() { uikitUtil.attr(this.slides, 'tabindex', '-1'); }, events: [ { name: 'visibilitychange', el: uikitUtil.inBrowser && document, filter: function() { return this.autoplay; }, handler: function() { if (document.hidden) { this.stopAutoplay(); } else { this.startAutoplay(); } } } ], methods: { startAutoplay: function() { var this$1 = this; this.stopAutoplay(); this.interval = setInterval( function () { return (!this$1.draggable || !uikitUtil.$(':focus', this$1.$el)) && (!this$1.pauseOnHover || !uikitUtil.matches(this$1.$el, ':hover')) && !this$1.stack.length && this$1.show('next'); }, this.autoplayInterval ); }, stopAutoplay: function() { this.interval && clearInterval(this.interval); } } }; var SliderDrag = { props: { draggable: Boolean }, data: { draggable: true, threshold: 10 }, created: function() { var this$1 = this; ['start', 'move', 'end'].forEach(function (key) { var fn = this$1[key]; this$1[key] = function (e) { var pos = uikitUtil.getEventPos(e).x * (uikitUtil.isRtl ? -1 : 1); this$1.prevPos = pos !== this$1.pos ? this$1.pos : this$1.prevPos; this$1.pos = pos; fn(e); }; }); }, events: [ { name: uikitUtil.pointerDown, delegate: function() { return this.selSlides; }, handler: function(e) { if (!this.draggable || !uikitUtil.isTouch(e) && hasTextNodesOnly(e.target) || uikitUtil.closest(e.target, uikitUtil.selInput) || e.button > 0 || this.length < 2 ) { return; } this.start(e); } }, { name: 'dragstart', handler: function(e) { e.preventDefault(); } } ], methods: { start: function() { this.drag = this.pos; if (this._transitioner) { this.percent = this._transitioner.percent(); this.drag += this._transitioner.getDistance() * this.percent * this.dir; this._transitioner.cancel(); this._transitioner.translate(this.percent); this.dragging = true; this.stack = []; } else { this.prevIndex = this.index; } // Workaround for iOS's inert scrolling preventing pointerdown event // https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action uikitUtil.on(this.list, 'touchmove', this.move, {passive: false}); uikitUtil.on(document, uikitUtil.pointerMove, this.move, {passive: false}); uikitUtil.on(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel), this.end, true); uikitUtil.css(this.list, 'userSelect', 'none'); }, move: function(e) { var this$1 = this; var distance = this.pos - this.drag; if (distance === 0 || this.prevPos === this.pos || !this.dragging && Math.abs(distance) < this.threshold) { return; } e.cancelable && e.preventDefault(); this.dragging = true; this.dir = (distance < 0 ? 1 : -1); var ref = this; var slides = ref.slides; var ref$1 = this; var prevIndex = ref$1.prevIndex; var dis = Math.abs(distance); var nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); var width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; while (nextIndex !== prevIndex && dis > width) { this.drag -= width * this.dir; prevIndex = nextIndex; dis -= width; nextIndex = this.getIndex(prevIndex + this.dir, prevIndex); width = this._getDistance(prevIndex, nextIndex) || slides[prevIndex].offsetWidth; } this.percent = dis / width; var prev = slides[prevIndex]; var next = slides[nextIndex]; var changed = this.index !== nextIndex; var edge = prevIndex === nextIndex; var itemShown; [this.index, this.prevIndex].filter(function (i) { return !uikitUtil.includes([nextIndex, prevIndex], i); }).forEach(function (i) { uikitUtil.trigger(slides[i], 'itemhidden', [this$1]); if (edge) { itemShown = true; this$1.prevIndex = prevIndex; } }); if (this.index === prevIndex && this.prevIndex !== prevIndex || itemShown) { uikitUtil.trigger(slides[this.index], 'itemshown', [this]); } if (changed) { this.prevIndex = prevIndex; this.index = nextIndex; !edge && uikitUtil.trigger(prev, 'beforeitemhide', [this]); uikitUtil.trigger(next, 'beforeitemshow', [this]); } this._transitioner = this._translate(Math.abs(this.percent), prev, !edge && next); if (changed) { !edge && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); } }, end: function() { uikitUtil.off(this.list, 'touchmove', this.move, {passive: false}); uikitUtil.off(document, uikitUtil.pointerMove, this.move, {passive: false}); uikitUtil.off(document, (uikitUtil.pointerUp + " " + uikitUtil.pointerCancel), this.end, true); if (this.dragging) { this.dragging = null; if (this.index === this.prevIndex) { this.percent = 1 - this.percent; this.dir *= -1; this._show(false, this.index, true); this._transitioner = null; } else { var dirChange = (uikitUtil.isRtl ? this.dir * (uikitUtil.isRtl ? 1 : -1) : this.dir) < 0 === this.prevPos > this.pos; this.index = dirChange ? this.index : this.prevIndex; if (dirChange) { this.percent = 1 - this.percent; } this.show(this.dir > 0 && !dirChange || this.dir < 0 && dirChange ? 'next' : 'previous', true); } } uikitUtil.css(this.list, {userSelect: '', pointerEvents: ''}); this.drag = this.percent = null; } } }; function hasTextNodesOnly(el) { return !el.children.length && el.childNodes.length; } var SliderNav = { data: { selNav: false }, computed: { nav: function(ref, $el) { var selNav = ref.selNav; return uikitUtil.$(selNav, $el); }, selNavItem: function(ref) { var attrItem = ref.attrItem; return ("[" + attrItem + "],[data-" + attrItem + "]"); }, navItems: function(_, $el) { return uikitUtil.$$(this.selNavItem, $el); } }, update: { write: function() { var this$1 = this; if (this.nav && this.length !== this.nav.children.length) { uikitUtil.html(this.nav, this.slides.map(function (_, i) { return ("<li " + (this$1.attrItem) + "=\"" + i + "\"><a href></a></li>"); }).join('')); } this.navItems.concat(this.nav).forEach(function (el) { return el && (el.hidden = !this$1.maxIndex); }); this.updateNav(); }, events: ['resize'] }, events: [ { name: 'click', delegate: function() { return this.selNavItem; }, handler: function(e) { e.preventDefault(); this.show(uikitUtil.data(e.current, this.attrItem)); } }, { name: 'itemshow', handler: 'updateNav' } ], methods: { updateNav: function() { var this$1 = this; var i = this.getValidIndex(); this.navItems.forEach(function (el) { var cmd = uikitUtil.data(el, this$1.attrItem); uikitUtil.toggleClass(el, this$1.clsActive, uikitUtil.toNumber(cmd) === i); uikitUtil.toggleClass(el, 'uk-invisible', this$1.finite && (cmd === 'previous' && i === 0 || cmd === 'next' && i >= this$1.maxIndex)); }); } } }; var Slider = { mixins: [SliderAutoplay, SliderDrag, SliderNav], props: { clsActivated: Boolean, easing: String, index: Number, finite: Boolean, velocity: Number, selSlides: String }, data: function () { return ({ easing: 'ease', finite: false, velocity: 1, index: 0, prevIndex: -1, stack: [], percent: 0, clsActive: 'uk-active', clsActivated: false, Transitioner: false, transitionOptions: {} }); }, connected: function() { this.prevIndex = -1; this.index = this.getValidIndex(this.$props.index); this.stack = []; }, disconnected: function() { uikitUtil.removeClass(this.slides, this.clsActive); }, computed: { duration: function(ref, $el) { var velocity = ref.velocity; return speedUp($el.offsetWidth / velocity); }, list: function(ref, $el) { var selList = ref.selList; return uikitUtil.$(selList, $el); }, maxIndex: function() { return this.length - 1; }, selSlides: function(ref) { var selList = ref.selList; var selSlides = ref.selSlides; return (selList + " " + (selSlides || '> *')); }, slides: { get: function() { return uikitUtil.$$(this.selSlides, this.$el); }, watch: function() { this.$reset(); } }, length: function() { return this.slides.length; } }, events: { itemshown: function() { this.$update(this.list); } }, methods: { show: function(index, force) { var this$1 = this; if ( force === void 0 ) force = false; if (this.dragging || !this.length) { return; } var ref = this; var stack = ref.stack; var queueIndex = force ? 0 : stack.length; var reset = function () { stack.splice(queueIndex, 1); if (stack.length) { this$1.show(stack.shift(), true); } }; stack[force ? 'unshift' : 'push'](index); if (!force && stack.length > 1) { if (stack.length === 2) { this._transitioner.forward(Math.min(this.duration, 200)); } return; } var prevIndex = this.getIndex(this.index); var prev = uikitUtil.hasClass(this.slides, this.clsActive) && this.slides[prevIndex]; var nextIndex = this.getIndex(index, this.index); var next = this.slides[nextIndex]; if (prev === next) { reset(); return; } this.dir = getDirection(index, prevIndex); this.prevIndex = prevIndex; this.index = nextIndex; if (prev && !uikitUtil.trigger(prev, 'beforeitemhide', [this]) || !uikitUtil.trigger(next, 'beforeitemshow', [this, prev]) ) { this.index = this.prevIndex; reset(); return; } var promise = this._show(prev, next, force).then(function () { prev && uikitUtil.trigger(prev, 'itemhidden', [this$1]); uikitUtil.trigger(next, 'itemshown', [this$1]); return new uikitUtil.Promise(function (resolve) { uikitUtil.fastdom.write(function () { stack.shift(); if (stack.length) { this$1.show(stack.shift(), true); } else { this$1._transitioner = null; } resolve(); }); }); }); prev && uikitUtil.trigger(prev, 'itemhide', [this]); uikitUtil.trigger(next, 'itemshow', [this]); return promise; }, getIndex: function(index, prev) { if ( index === void 0 ) index = this.index; if ( prev === void 0 ) prev = this.index; return uikitUtil.clamp(uikitUtil.getIndex(index, this.slides, prev, this.finite), 0, this.maxIndex); }, getValidIndex: function(index, prevIndex) { if ( index === void 0 ) index = this.index; if ( prevIndex === void 0 ) prevIndex = this.prevIndex; return this.getIndex(index, prevIndex); }, _show: function(prev, next, force) { this._transitioner = this._getTransitioner( prev, next, this.dir, uikitUtil.assign({ easing: force ? next.offsetWidth < 600 ? 'cubic-bezier(0.25, 0.46, 0.45, 0.94)' /* easeOutQuad */ : 'cubic-bezier(0.165, 0.84, 0.44, 1)' /* easeOutQuart */ : this.easing }, this.transitionOptions) ); if (!force && !prev) { this._translate(1); return uikitUtil.Promise.resolve(); } var ref = this.stack; var length = ref.length; return this._transitioner[length > 1 ? 'forward' : 'show'](length > 1 ? Math.min(this.duration, 75 + 75 / (length - 1)) : this.duration, this.percent); }, _getDistance: function(prev, next) { return this._getTransitioner(prev, prev !== next && next).getDistance(); }, _translate: function(percent, prev, next) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; var transitioner = this._getTransitioner(prev !== next ? prev : false, next); transitioner.translate(percent); return transitioner; }, _getTransitioner: function(prev, next, dir, options) { if ( prev === void 0 ) prev = this.prevIndex; if ( next === void 0 ) next = this.index; if ( dir === void 0 ) dir = this.dir || 1; if ( options === void 0 ) options = this.transitionOptions; return new this.Transitioner( uikitUtil.isNumber(prev) ? this.slides[prev] : prev, uikitUtil.isNumber(next) ? this.slides[next] : next, dir * (uikitUtil.isRtl ? -1 : 1), options ); } } }; function getDirection(index, prevIndex) { return index === 'next' ? 1 : index === 'previous' ? -1 : index < prevIndex ? -1 : 1; } function speedUp(x) { return .5 * x + 300; // parabola through (400,500; 600,600; 1800,1200) } var Slideshow = { mixins: [Slider], props: { animation: String }, data: { animation: 'slide', clsActivated: 'uk-transition-active', Animations: Animations, Transitioner: Transitioner }, computed: { animation: function(ref) { var animation = ref.animation; var Animations = ref.Animations; return uikitUtil.assign(Animations[animation] || Animations.slide, {name: animation}); }, transitionOptions: function() { return {animation: this.animation}; } }, events: { 'itemshow itemhide itemshown itemhidden': function(ref) { var target = ref.target; this.$update(target); }, beforeitemshow: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActive); }, itemshown: function(ref) { var target = ref.target; uikitUtil.addClass(target, this.clsActivated); }, itemhidden: function(ref) { var target = ref.target; uikitUtil.removeClass(target, this.clsActive, this.clsActivated); } } }; var LightboxPanel = { mixins: [Container, Modal, Togglable, Slideshow], functional: true, props: { delayControls: Number, preload: Number, videoAutoplay: Boolean, template: String }, data: function () { return ({ preload: 1, videoAutoplay: false, delayControls: 3000, items: [], cls: 'uk-open', clsPage: 'uk-lightbox-page', selList: '.uk-lightbox-items', attrItem: 'uk-lightbox-item', selClose: '.uk-close-large', selCaption: '.uk-lightbox-caption', pauseOnHover: false, velocity: 2, Animations: Animations$1, template: "<div class=\"uk-lightbox uk-overflow-hidden\"> <ul class=\"uk-lightbox-items\"></ul> <div class=\"uk-lightbox-toolbar uk-position-top uk-text-right uk-transition-slide-top uk-transition-opaque\"> <button class=\"uk-lightbox-toolbar-icon uk-close-large\" type=\"button\" uk-close></button> </div> <a class=\"uk-lightbox-button uk-position-center-left uk-position-medium uk-transition-fade\" href uk-slidenav-previous uk-lightbox-item=\"previous\"></a> <a class=\"uk-lightbox-button uk-position-center-right uk-position-medium uk-transition-fade\" href uk-slidenav-next uk-lightbox-item=\"next\"></a> <div class=\"uk-lightbox-toolbar uk-lightbox-caption uk-position-bottom uk-text-center uk-transition-slide-bottom uk-transition-opaque\"></div> </div>" }); }, created: function() { var $el = uikitUtil.$(this.template); var list = uikitUtil.$(this.selList, $el); this.items.forEach(function () { return uikitUtil.append(list, '<li>'); }); this.$mount(uikitUtil.append(this.container, $el)); }, computed: { caption: function(ref, $el) { var selCaption = ref.selCaption; return uikitUtil.$('.uk-lightbox-caption', $el); } }, events: [ { name: (uikitUtil.pointerMove + " " + uikitUtil.pointerDown + " keydown"), handler: 'showControls' }, { name: 'click', self: true, delegate: function() { return this.selSlides; }, handler: function(e) { if (e.defaultPrevented) { return; } this.hide(); } }, { name: 'shown', self: true, handler: function() { this.showControls(); } }, { name: 'hide', self: true, handler: function() { this.hideControls(); uikitUtil.removeClass(this.slides, this.clsActive); uikitUtil.Transition.stop(this.slides); } }, { name: 'hidden', self: true, handler: function() { this.$destroy(true); } }, { name: 'keyup', el: uikitUtil.inBrowser && document, handler: function(e) { if (!this.isToggled(this.$el) || !this.draggable) { return; } switch (e.keyCode) { case 37: this.show('previous'); break; case 39: this.show('next'); break; } } }, { name: 'beforeitemshow', handler: function(e) { if (this.isToggled()) { return; } this.draggable = false; e.preventDefault(); this.toggleElement(this.$el, true, false); this.animation = Animations$1['scale']; uikitUtil.removeClass(e.target, this.clsActive); this.stack.splice(1, 0, this.index); } }, { name: 'itemshow', handler: function() { uikitUtil.html(this.caption, this.getItem().caption || ''); for (var j = -this.preload; j <= this.preload; j++) { this.loadItem(this.index + j); } } }, { name: 'itemshown', handler: function() { this.draggable = this.$props.draggable; } }, { name: 'itemload', handler: function(_, item) { var this$1 = this; var src = item.source; var type = item.type; var alt = item.alt; if ( alt === void 0 ) alt = ''; var poster = item.poster; var attrs = item.attrs; if ( attrs === void 0 ) attrs = {}; this.setItem(item, '<span uk-spinner></span>'); if (!src) { return; } var matches; var iframeAttrs = { frameborder: '0', allow: 'autoplay', allowfullscreen: '', style: 'max-width: 100%; box-sizing: border-box;', 'uk-responsive': '', 'uk-video': ("" + (this.videoAutoplay)) }; // Image if (type === 'image' || src.match(/\.(jpe?g|png|gif|svg|webp)($|\?)/i)) { uikitUtil.getImage(src, attrs.srcset, attrs.size).then( function (ref) { var width = ref.width; var height = ref.height; return this$1.setItem(item, createEl('img', uikitUtil.assign({src: src, width: width, height: height, alt: alt}, attrs))); }, function () { return this$1.setError(item); } ); // Video } else if (type === 'video' || src.match(/\.(mp4|webm|ogv)($|\?)/i)) { var video = createEl('video', uikitUtil.assign({ src: src, poster: poster, controls: '', playsinline: '', 'uk-video': ("" + (this.videoAutoplay)) }, attrs)); uikitUtil.on(video, 'loadedmetadata', function () { uikitUtil.attr(video, {width: video.videoWidth, height: video.videoHeight}); this$1.setItem(item, video); }); uikitUtil.on(video, 'error', function () { return this$1.setError(item); }); // Iframe } else if (type === 'iframe' || src.match(/\.(html|php)($|\?)/i)) { this.setItem(item, createEl('iframe', uikitUtil.assign({ src: src, frameborder: '0', allowfullscreen: '', class: 'uk-lightbox-iframe' }, attrs))); // YouTube } else if ((matches = src.match(/\/\/(?:.*?youtube(-nocookie)?\..*?[?&]v=|youtu\.be\/)([\w-]{11})[&?]?(.*)?/))) { this.setItem(item, createEl('iframe', uikitUtil.assign({ src: ("https://www.youtube" + (matches[1] || '') + ".com/embed/" + (matches[2]) + (matches[3] ? ("?" + (matches[3])) : '')), width: 1920, height: 1080 }, iframeAttrs, attrs))); // Vimeo } else if ((matches = src.match(/\/\/.*?vimeo\.[a-z]+\/(\d+)[&?]?(.*)?/))) { uikitUtil.ajax(("https://vimeo.com/api/oembed.json?maxwidth=1920&url=" + (encodeURI(src))), { responseType: 'json', withCredentials: false }).then( function (ref) { var ref_response = ref.response; var height = ref_response.height; var width = ref_response.width; return this$1.setItem(item, createEl('iframe', uikitUtil.assign({ src: ("https://player.vimeo.com/video/" + (matches[1]) + (matches[2] ? ("?" + (matches[2])) : '')), width: width, height: height }, iframeAttrs, attrs))); }, function () { return this$1.setError(item); } ); } } } ], methods: { loadItem: function(index) { if ( index === void 0 ) index = this.index; var item = this.getItem(index); if (!this.getSlide(item).childElementCount) { uikitUtil.trigger(this.$el, 'itemload', [item]); } }, getItem: function(index) { if ( index === void 0 ) index = this.index; return this.items[uikitUtil.getIndex(index, this.slides)]; }, setItem: function(item, content) { uikitUtil.trigger(this.$el, 'itemloaded', [this, uikitUtil.html(this.getSlide(item), content) ]); }, getSlide: function(item) { return this.slides[this.items.indexOf(item)]; }, setError: function(item) { this.setItem(item, '<span uk-icon="icon: bolt; ratio: 2"></span>'); }, showControls: function() { clearTimeout(this.controlsTimer); this.controlsTimer = setTimeout(this.hideControls, this.delayControls); uikitUtil.addClass(this.$el, 'uk-active', 'uk-transition-active'); }, hideControls: function() { uikitUtil.removeClass(this.$el, 'uk-active', 'uk-transition-active'); } } }; function createEl(tag, attrs) { var el = uikitUtil.fragment(("<" + tag + ">")); uikitUtil.attr(el, attrs); return el; } var Component = { install: install, props: {toggle: String}, data: {toggle: 'a'}, computed: { toggles: { get: function(ref, $el) { var toggle = ref.toggle; return uikitUtil.$$(toggle, $el); }, watch: function() { this.hide(); } } }, disconnected: function() { this.hide(); }, events: [ { name: 'click', delegate: function() { return ((this.toggle) + ":not(.uk-disabled)"); }, handler: function(e) { e.preventDefault(); this.show(e.current); } } ], methods: { show: function(index) { var this$1 = this; var items = uikitUtil.uniqueBy(this.toggles.map(toItem), 'source'); if (uikitUtil.isElement(index)) { var ref = toItem(index); var source = ref.source; index = uikitUtil.findIndex(items, function (ref) { var src = ref.source; return source === src; }); } this.panel = this.panel || this.$create('lightboxPanel', uikitUtil.assign({}, this.$props, {items: items})); uikitUtil.on(this.panel.$el, 'hidden', function () { return this$1.panel = false; }); return this.panel.show(index); }, hide: function() { return this.panel && this.panel.hide(); } } }; function install(UIkit, Lightbox) { if (!UIkit.lightboxPanel) { UIkit.component('lightboxPanel', LightboxPanel); } uikitUtil.assign( Lightbox.props, UIkit.component('lightboxPanel').options.props ); } function toItem(el) { var item = {}; ['href', 'caption', 'type', 'poster', 'alt', 'attrs'].forEach(function (attr) { item[attr === 'href' ? 'source' : attr] = uikitUtil.data(el, attr); }); item.attrs = uikitUtil.parseOptions(item.attrs); return item; } if (typeof window !== 'undefined' && window.UIkit) { window.UIkit.component('lightbox', Component); } return Component; })));
cdnjs/cdnjs
ajax/libs/uikit/3.6.13/js/components/lightbox.js
JavaScript
mit
53,708
/*! * ui-grid - v4.8.2 - 2019-10-07 * Copyright (c) 2019 ; License: MIT */ (function () { angular.module('ui.grid').config(['$provide', function($provide) { $provide.decorator('i18nService', ['$delegate', function($delegate) { $delegate.add('sv', { headerCell: { aria: { defaultFilterLabel: 'Kolumnfilter', removeFilter: 'Ta bort filter', columnMenuButtonLabel: 'Kolumnmeny', column: 'Kolumn' }, priority: 'Prioritet:', filterLabel: "Filter för kolumn: " }, aggregate: { label: 'Poster' }, groupPanel: { description: 'Dra en kolumnrubrik hit och släpp den för att gruppera efter den kolumnen.' }, search: { aria: { selected: 'Rad är vald', notSelected: 'Rad är inte vald' }, placeholder: 'Sök...', showingItems: 'Visar:', selectedItems: 'Valda:', totalItems: 'Antal:', size: 'Sidstorlek:', first: 'Första sidan', next: 'Nästa sida', previous: 'Föregående sida', last: 'Sista sidan' }, menu: { text: 'Välj kolumner:' }, sort: { ascending: 'Sortera stigande', descending: 'Sortera fallande', none: 'Ingen sortering', remove: 'Inaktivera sortering' }, column: { hide: 'Göm kolumn' }, aggregation: { count: 'Antal rader: ', sum: 'Summa: ', avg: 'Genomsnitt: ', min: 'Min: ', max: 'Max: ' }, pinning: { pinLeft: 'Fäst vänster', pinRight: 'Fäst höger', unpin: 'Lösgör' }, columnMenu: { close: 'Stäng' }, gridMenu: { aria: { buttonLabel: 'Meny' }, columns: 'Kolumner:', importerTitle: 'Importera fil', exporterAllAsCsv: 'Exportera all data som CSV', exporterVisibleAsCsv: 'Exportera synlig data som CSV', exporterSelectedAsCsv: 'Exportera markerad data som CSV', exporterAllAsPdf: 'Exportera all data som PDF', exporterVisibleAsPdf: 'Exportera synlig data som PDF', exporterSelectedAsPdf: 'Exportera markerad data som PDF', exporterAllAsExcel: 'Exportera all data till Excel', exporterVisibleAsExcel: 'Exportera synlig data till Excel', exporterSelectedAsExcel: 'Exportera markerad data till Excel', clearAllFilters: 'Nollställ alla filter' }, importer: { noHeaders: 'Kolumnnamn kunde inte härledas. Har filen ett sidhuvud?', noObjects: 'Objekt kunde inte härledas. Har filen data undantaget sidhuvud?', invalidCsv: 'Filen kunde inte behandlas, är den en giltig CSV?', invalidJson: 'Filen kunde inte behandlas, är den en giltig JSON?', jsonNotArray: 'Importerad JSON-fil måste innehålla ett fält. Import avbruten.' }, pagination: { aria: { pageToFirst: 'Gå till första sidan', pageBack: 'Gå en sida bakåt', pageSelected: 'Vald sida', pageForward: 'Gå en sida framåt', pageToLast: 'Gå till sista sidan' }, sizes: 'Poster per sida', totalItems: 'Poster', through: 'genom', of: 'av' }, grouping: { group: 'Gruppera', ungroup: 'Dela upp', aggregate_count: 'Agg: Antal', aggregate_sum: 'Agg: Summa', aggregate_max: 'Agg: Max', aggregate_min: 'Agg: Min', aggregate_avg: 'Agg: Genomsnitt', aggregate_remove: 'Agg: Ta bort' }, validate: { error: 'Error:', minLength: 'Värdet borde vara minst THRESHOLD tecken långt.', maxLength: 'Värdet borde vara max THRESHOLD tecken långt.', required: 'Ett värde krävs.' } }); return $delegate; }]); }]); })();
cdnjs/cdnjs
ajax/libs/angular-ui-grid/4.8.2/i18n/ui-grid.language.sv.js
JavaScript
mit
4,183
/** MobX - (c) Michel Weststrate 2015 - 2020 - MIT Licensed */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.mobx = {})); }(this, (function (exports) { 'use strict'; var OBFUSCATED_ERROR = "An invariant failed, however the error is obfuscated because this is a production build."; var EMPTY_ARRAY = []; Object.freeze(EMPTY_ARRAY); var EMPTY_OBJECT = {}; Object.freeze(EMPTY_OBJECT); function getNextId() { return ++globalState.mobxGuid; } function fail(message) { invariant(false, message); throw "X"; // unreachable } function invariant(check, message) { if (!check) throw new Error("[mobx] " + (message || OBFUSCATED_ERROR)); } /** * Prints a deprecation message, but only one time. * Returns false if the deprecated message was already printed before */ var deprecatedMessages = []; function deprecated(msg, thing) { if (process.env.NODE_ENV === "production") return false; if (thing) { return deprecated("'" + msg + "', use '" + thing + "' instead."); } if (deprecatedMessages.indexOf(msg) !== -1) return false; deprecatedMessages.push(msg); console.error("[mobx] Deprecated: " + msg); return true; } /** * Makes sure that the provided function is invoked at most once. */ function once(func) { var invoked = false; return function () { if (invoked) return; invoked = true; return func.apply(this, arguments); }; } var noop = function () { }; function unique(list) { var res = []; list.forEach(function (item) { if (res.indexOf(item) === -1) res.push(item); }); return res; } function isObject(value) { return value !== null && typeof value === "object"; } function isPlainObject(value) { if (value === null || typeof value !== "object") return false; var proto = Object.getPrototypeOf(value); return proto === Object.prototype || proto === null; } function convertToMap(dataStructure) { if (isES6Map(dataStructure) || isObservableMap(dataStructure)) { return dataStructure; } else if (Array.isArray(dataStructure)) { return new Map(dataStructure); } else if (isPlainObject(dataStructure)) { var map = new Map(); for (var key in dataStructure) { map.set(key, dataStructure[key]); } return map; } else { return fail("Cannot convert to map from '" + dataStructure + "'"); } } function addHiddenProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: true, configurable: true, value: value }); } function addHiddenFinalProp(object, propName, value) { Object.defineProperty(object, propName, { enumerable: false, writable: false, configurable: true, value: value }); } function isPropertyConfigurable(object, prop) { var descriptor = Object.getOwnPropertyDescriptor(object, prop); return !descriptor || (descriptor.configurable !== false && descriptor.writable !== false); } function assertPropertyConfigurable(object, prop) { if (process.env.NODE_ENV !== "production" && !isPropertyConfigurable(object, prop)) fail("Cannot make property '" + prop.toString() + "' observable, it is not configurable and writable in the target object"); } function createInstanceofPredicate(name, clazz) { var propName = "isMobX" + name; clazz.prototype[propName] = true; return function (x) { return isObject(x) && x[propName] === true; }; } /** * Returns whether the argument is an array, disregarding observability. */ function isArrayLike(x) { return Array.isArray(x) || isObservableArray(x); } function isES6Map(thing) { return thing instanceof Map; } function isES6Set(thing) { return thing instanceof Set; } /** * Returns the following: own keys, prototype keys & own symbol keys, if they are enumerable. */ function getPlainObjectKeys(object) { var enumerables = new Set(); for (var key in object) enumerables.add(key); // *all* enumerables Object.getOwnPropertySymbols(object).forEach(function (k) { if (Object.getOwnPropertyDescriptor(object, k).enumerable) enumerables.add(k); }); // *own* symbols // Note: this implementation is missing enumerable, inherited, symbolic property names! That would however pretty expensive to add, // as there is no efficient iterator that returns *all* properties return Array.from(enumerables); } function stringifyKey(key) { if (key && key.toString) return key.toString(); else return new String(key).toString(); } function toPrimitive(value) { return value === null ? null : typeof value === "object" ? "" + value : value; } var ownKeys = typeof Reflect !== "undefined" && Reflect.ownKeys ? Reflect.ownKeys : Object.getOwnPropertySymbols ? function (obj) { return Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj)); } : /* istanbul ignore next */ Object.getOwnPropertyNames; var $mobx = Symbol("mobx administration"); var Atom = /** @class */ (function () { /** * Create a new atom. For debugging purposes it is recommended to give it a name. * The onBecomeObserved and onBecomeUnobserved callbacks can be used for resource management. */ function Atom(name) { if (name === void 0) { name = "Atom@" + getNextId(); } this.name = name; this.isPendingUnobservation = false; // for effective unobserving. BaseAtom has true, for extra optimization, so its onBecomeUnobserved never gets called, because it's not needed this.isBeingObserved = false; this.observers = new Set(); this.diffValue = 0; this.lastAccessedBy = 0; this.lowestObserverState = exports.IDerivationState.NOT_TRACKING; } Atom.prototype.onBecomeObserved = function () { if (this.onBecomeObservedListeners) { this.onBecomeObservedListeners.forEach(function (listener) { return listener(); }); } }; Atom.prototype.onBecomeUnobserved = function () { if (this.onBecomeUnobservedListeners) { this.onBecomeUnobservedListeners.forEach(function (listener) { return listener(); }); } }; /** * Invoke this method to notify mobx that your atom has been used somehow. * Returns true if there is currently a reactive context. */ Atom.prototype.reportObserved = function () { return reportObserved(this); }; /** * Invoke this method _after_ this method has changed to signal mobx that all its observers should invalidate. */ Atom.prototype.reportChanged = function () { startBatch(); propagateChanged(this); endBatch(); }; Atom.prototype.toString = function () { return this.name; }; return Atom; }()); var isAtom = createInstanceofPredicate("Atom", Atom); function createAtom(name, onBecomeObservedHandler, onBecomeUnobservedHandler) { if (onBecomeObservedHandler === void 0) { onBecomeObservedHandler = noop; } if (onBecomeUnobservedHandler === void 0) { onBecomeUnobservedHandler = noop; } var atom = new Atom(name); // default `noop` listener will not initialize the hook Set if (onBecomeObservedHandler !== noop) { onBecomeObserved(atom, onBecomeObservedHandler); } if (onBecomeUnobservedHandler !== noop) { onBecomeUnobserved(atom, onBecomeUnobservedHandler); } return atom; } function identityComparer(a, b) { return a === b; } function structuralComparer(a, b) { return deepEqual(a, b); } function shallowComparer(a, b) { return deepEqual(a, b, 1); } function defaultComparer(a, b) { return Object.is(a, b); } var comparer = { identity: identityComparer, structural: structuralComparer, default: defaultComparer, shallow: shallowComparer }; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } var __assign = function() { __assign = Object.assign || function __assign(t) { for (var s, i = 1, n = arguments.length; i < n; i++) { s = arguments[i]; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; } return t; }; return __assign.apply(this, arguments); }; function __values(o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; } function __read(o, n) { var m = typeof Symbol === "function" && o[Symbol.iterator]; if (!m) return o; var i = m.call(o), r, ar = [], e; try { while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); } catch (error) { e = { error: error }; } finally { try { if (r && !r.done && (m = i["return"])) m.call(i); } finally { if (e) throw e.error; } } return ar; } function __spread() { for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); return ar; } var mobxDidRunLazyInitializersSymbol = Symbol("mobx did run lazy initializers"); var mobxPendingDecorators = Symbol("mobx pending decorators"); var enumerableDescriptorCache = {}; var nonEnumerableDescriptorCache = {}; function createPropertyInitializerDescriptor(prop, enumerable) { var cache = enumerable ? enumerableDescriptorCache : nonEnumerableDescriptorCache; return (cache[prop] || (cache[prop] = { configurable: true, enumerable: enumerable, get: function () { initializeInstance(this); return this[prop]; }, set: function (value) { initializeInstance(this); this[prop] = value; } })); } function initializeInstance(target) { var e_1, _a; if (target[mobxDidRunLazyInitializersSymbol] === true) return; var decorators = target[mobxPendingDecorators]; if (decorators) { addHiddenProp(target, mobxDidRunLazyInitializersSymbol, true); // Build property key array from both strings and symbols var keys = __spread(Object.getOwnPropertySymbols(decorators), Object.keys(decorators)); try { for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { var key = keys_1_1.value; var d = decorators[key]; d.propertyCreator(target, d.prop, d.descriptor, d.decoratorTarget, d.decoratorArguments); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); } finally { if (e_1) throw e_1.error; } } } } function createPropDecorator(propertyInitiallyEnumerable, propertyCreator) { return function decoratorFactory() { var decoratorArguments; var decorator = function decorate(target, prop, descriptor, applyImmediately // This is a special parameter to signal the direct application of a decorator, allow extendObservable to skip the entire type decoration part, // as the instance to apply the decorator to equals the target ) { if (applyImmediately === true) { propertyCreator(target, prop, descriptor, target, decoratorArguments); return null; } if (process.env.NODE_ENV !== "production" && !quacksLikeADecorator(arguments)) fail("This function is a decorator, but it wasn't invoked like a decorator"); if (!Object.prototype.hasOwnProperty.call(target, mobxPendingDecorators)) { var inheritedDecorators = target[mobxPendingDecorators]; addHiddenProp(target, mobxPendingDecorators, __assign({}, inheritedDecorators)); } target[mobxPendingDecorators][prop] = { prop: prop, propertyCreator: propertyCreator, descriptor: descriptor, decoratorTarget: target, decoratorArguments: decoratorArguments }; return createPropertyInitializerDescriptor(prop, propertyInitiallyEnumerable); }; if (quacksLikeADecorator(arguments)) { // @decorator decoratorArguments = EMPTY_ARRAY; return decorator.apply(null, arguments); } else { // @decorator(args) decoratorArguments = Array.prototype.slice.call(arguments); return decorator; } }; } function quacksLikeADecorator(args) { return (((args.length === 2 || args.length === 3) && (typeof args[1] === "string" || typeof args[1] === "symbol")) || (args.length === 4 && args[3] === true)); } function deepEnhancer(v, _, name) { // it is an observable already, done if (isObservable(v)) return v; // something that can be converted and mutated? if (Array.isArray(v)) return observable.array(v, { name: name }); if (isPlainObject(v)) return observable.object(v, undefined, { name: name }); if (isES6Map(v)) return observable.map(v, { name: name }); if (isES6Set(v)) return observable.set(v, { name: name }); return v; } function shallowEnhancer(v, _, name) { if (v === undefined || v === null) return v; if (isObservableObject(v) || isObservableArray(v) || isObservableMap(v) || isObservableSet(v)) return v; if (Array.isArray(v)) return observable.array(v, { name: name, deep: false }); if (isPlainObject(v)) return observable.object(v, undefined, { name: name, deep: false }); if (isES6Map(v)) return observable.map(v, { name: name, deep: false }); if (isES6Set(v)) return observable.set(v, { name: name, deep: false }); return fail(process.env.NODE_ENV !== "production" && "The shallow modifier / decorator can only used in combination with arrays, objects, maps and sets"); } function referenceEnhancer(newValue) { // never turn into an observable return newValue; } function refStructEnhancer(v, oldValue, name) { if (process.env.NODE_ENV !== "production" && isObservable(v)) throw "observable.struct should not be used with observable values"; if (deepEqual(v, oldValue)) return oldValue; return v; } function createDecoratorForEnhancer(enhancer) { invariant(enhancer); var decorator = createPropDecorator(true, function (target, propertyName, descriptor, _decoratorTarget, decoratorArgs) { if (process.env.NODE_ENV !== "production") { invariant(!descriptor || !descriptor.get, "@observable cannot be used on getter (property \"" + stringifyKey(propertyName) + "\"), use @computed instead."); } var initialValue = descriptor ? descriptor.initializer ? descriptor.initializer.call(target) : descriptor.value : undefined; asObservableObject(target).addObservableProp(propertyName, initialValue, enhancer); }); var res = // Extra process checks, as this happens during module initialization typeof process !== "undefined" && process.env && process.env.NODE_ENV !== "production" ? function observableDecorator() { // This wrapper function is just to detect illegal decorator invocations, deprecate in a next version // and simply return the created prop decorator if (arguments.length < 2) return fail("Incorrect decorator invocation. @observable decorator doesn't expect any arguments"); return decorator.apply(null, arguments); } : decorator; res.enhancer = enhancer; return res; } // Predefined bags of create observable options, to avoid allocating temporarily option objects // in the majority of cases var defaultCreateObservableOptions = { deep: true, name: undefined, defaultDecorator: undefined, proxy: true }; Object.freeze(defaultCreateObservableOptions); function assertValidOption(key) { if (!/^(deep|name|equals|defaultDecorator|proxy)$/.test(key)) fail("invalid option for (extend)observable: " + key); } function asCreateObservableOptions(thing) { if (thing === null || thing === undefined) return defaultCreateObservableOptions; if (typeof thing === "string") return { name: thing, deep: true, proxy: true }; if (process.env.NODE_ENV !== "production") { if (typeof thing !== "object") return fail("expected options object"); Object.keys(thing).forEach(assertValidOption); } return thing; } var deepDecorator = createDecoratorForEnhancer(deepEnhancer); var shallowDecorator = createDecoratorForEnhancer(shallowEnhancer); var refDecorator = createDecoratorForEnhancer(referenceEnhancer); var refStructDecorator = createDecoratorForEnhancer(refStructEnhancer); function getEnhancerFromOptions(options) { return options.defaultDecorator ? options.defaultDecorator.enhancer : options.deep === false ? referenceEnhancer : deepEnhancer; } /** * Turns an object, array or function into a reactive structure. * @param v the value which should become observable. */ function createObservable(v, arg2, arg3) { // @observable someProp; if (typeof arguments[1] === "string" || typeof arguments[1] === "symbol") { return deepDecorator.apply(null, arguments); } // it is an observable already, done if (isObservable(v)) return v; // something that can be converted and mutated? var res = isPlainObject(v) ? observable.object(v, arg2, arg3) : Array.isArray(v) ? observable.array(v, arg2) : isES6Map(v) ? observable.map(v, arg2) : isES6Set(v) ? observable.set(v, arg2) : v; // this value could be converted to a new observable data structure, return it if (res !== v) return res; // otherwise, just box it fail(process.env.NODE_ENV !== "production" && "The provided value could not be converted into an observable. If you want just create an observable reference to the object use 'observable.box(value)'"); } var observableFactories = { box: function (value, options) { if (arguments.length > 2) incorrectlyUsedAsDecorator("box"); var o = asCreateObservableOptions(options); return new ObservableValue(value, getEnhancerFromOptions(o), o.name, true, o.equals); }, array: function (initialValues, options) { if (arguments.length > 2) incorrectlyUsedAsDecorator("array"); var o = asCreateObservableOptions(options); return createObservableArray(initialValues, getEnhancerFromOptions(o), o.name); }, map: function (initialValues, options) { if (arguments.length > 2) incorrectlyUsedAsDecorator("map"); var o = asCreateObservableOptions(options); return new ObservableMap(initialValues, getEnhancerFromOptions(o), o.name); }, set: function (initialValues, options) { if (arguments.length > 2) incorrectlyUsedAsDecorator("set"); var o = asCreateObservableOptions(options); return new ObservableSet(initialValues, getEnhancerFromOptions(o), o.name); }, object: function (props, decorators, options) { if (typeof arguments[1] === "string") incorrectlyUsedAsDecorator("object"); var o = asCreateObservableOptions(options); if (o.proxy === false) { return extendObservable({}, props, decorators, o); } else { var defaultDecorator = getDefaultDecoratorFromObjectOptions(o); var base = extendObservable({}, undefined, undefined, o); var proxy = createDynamicObservableObject(base); extendObservableObjectWithProperties(proxy, props, decorators, defaultDecorator); return proxy; } }, ref: refDecorator, shallow: shallowDecorator, deep: deepDecorator, struct: refStructDecorator }; var observable = createObservable; // weird trick to keep our typings nicely with our funcs, and still extend the observable function Object.keys(observableFactories).forEach(function (name) { return (observable[name] = observableFactories[name]); }); function incorrectlyUsedAsDecorator(methodName) { fail( // process.env.NODE_ENV !== "production" && "Expected one or two arguments to observable." + methodName + ". Did you accidentally try to use observable." + methodName + " as decorator?"); } var computedDecorator = createPropDecorator(false, function (instance, propertyName, descriptor, decoratorTarget, decoratorArgs) { if (process.env.NODE_ENV !== "production") { invariant(descriptor && descriptor.get, "Trying to declare a computed value for unspecified getter '" + stringifyKey(propertyName) + "'"); } var get = descriptor.get, set = descriptor.set; // initialValue is the descriptor for get / set props // Optimization: faster on decorator target or instance? Assuming target // Optimization: find out if declaring on instance isn't just faster. (also makes the property descriptor simpler). But, more memory usage.. // Forcing instance now, fixes hot reloadig issues on React Native: var options = decoratorArgs[0] || {}; asObservableObject(instance).addComputedProp(instance, propertyName, __assign({ get: get, set: set, context: instance }, options)); }); var computedStructDecorator = computedDecorator({ equals: comparer.structural }); /** * Decorator for class properties: @computed get value() { return expr; }. * For legacy purposes also invokable as ES5 observable created: `computed(() => expr)`; */ var computed = function computed(arg1, arg2, arg3) { if (typeof arg2 === "string") { // @computed return computedDecorator.apply(null, arguments); } if (arg1 !== null && typeof arg1 === "object" && arguments.length === 1) { // @computed({ options }) return computedDecorator.apply(null, arguments); } // computed(expr, options?) if (process.env.NODE_ENV !== "production") { invariant(typeof arg1 === "function", "First argument to `computed` should be an expression."); invariant(arguments.length < 3, "Computed takes one or two arguments if used as function"); } var opts = typeof arg2 === "object" ? arg2 : {}; opts.get = arg1; opts.set = typeof arg2 === "function" ? arg2 : opts.set; opts.name = opts.name || arg1.name || ""; /* for generated name */ return new ComputedValue(opts); }; computed.struct = computedStructDecorator; (function (IDerivationState) { // before being run or (outside batch and not being observed) // at this point derivation is not holding any data about dependency tree IDerivationState[IDerivationState["NOT_TRACKING"] = -1] = "NOT_TRACKING"; // no shallow dependency changed since last computation // won't recalculate derivation // this is what makes mobx fast IDerivationState[IDerivationState["UP_TO_DATE"] = 0] = "UP_TO_DATE"; // some deep dependency changed, but don't know if shallow dependency changed // will require to check first if UP_TO_DATE or POSSIBLY_STALE // currently only ComputedValue will propagate POSSIBLY_STALE // // having this state is second big optimization: // don't have to recompute on every dependency change, but only when it's needed IDerivationState[IDerivationState["POSSIBLY_STALE"] = 1] = "POSSIBLY_STALE"; // A shallow dependency has changed since last computation and the derivation // will need to recompute when it's needed next. IDerivationState[IDerivationState["STALE"] = 2] = "STALE"; })(exports.IDerivationState || (exports.IDerivationState = {})); var TraceMode; (function (TraceMode) { TraceMode[TraceMode["NONE"] = 0] = "NONE"; TraceMode[TraceMode["LOG"] = 1] = "LOG"; TraceMode[TraceMode["BREAK"] = 2] = "BREAK"; })(TraceMode || (TraceMode = {})); var CaughtException = /** @class */ (function () { function CaughtException(cause) { this.cause = cause; // Empty } return CaughtException; }()); function isCaughtException(e) { return e instanceof CaughtException; } /** * Finds out whether any dependency of the derivation has actually changed. * If dependenciesState is 1 then it will recalculate dependencies, * if any dependency changed it will propagate it by changing dependenciesState to 2. * * By iterating over the dependencies in the same order that they were reported and * stopping on the first change, all the recalculations are only called for ComputedValues * that will be tracked by derivation. That is because we assume that if the first x * dependencies of the derivation doesn't change then the derivation should run the same way * up until accessing x-th dependency. */ function shouldCompute(derivation) { switch (derivation.dependenciesState) { case exports.IDerivationState.UP_TO_DATE: return false; case exports.IDerivationState.NOT_TRACKING: case exports.IDerivationState.STALE: return true; case exports.IDerivationState.POSSIBLY_STALE: { // state propagation can occur outside of action/reactive context #2195 var prevAllowStateReads = allowStateReadsStart(true); var prevUntracked = untrackedStart(); // no need for those computeds to be reported, they will be picked up in trackDerivedFunction. var obs = derivation.observing, l = obs.length; for (var i = 0; i < l; i++) { var obj = obs[i]; if (isComputedValue(obj)) { if (globalState.disableErrorBoundaries) { obj.get(); } else { try { obj.get(); } catch (e) { // we are not interested in the value *or* exception at this moment, but if there is one, notify all untrackedEnd(prevUntracked); allowStateReadsEnd(prevAllowStateReads); return true; } } // if ComputedValue `obj` actually changed it will be computed and propagated to its observers. // and `derivation` is an observer of `obj` // invariantShouldCompute(derivation) if (derivation.dependenciesState === exports.IDerivationState.STALE) { untrackedEnd(prevUntracked); allowStateReadsEnd(prevAllowStateReads); return true; } } } changeDependenciesStateTo0(derivation); untrackedEnd(prevUntracked); allowStateReadsEnd(prevAllowStateReads); return false; } } } // function invariantShouldCompute(derivation: IDerivation) { // const newDepState = (derivation as any).dependenciesState // if ( // process.env.NODE_ENV === "production" && // (newDepState === IDerivationState.POSSIBLY_STALE || // newDepState === IDerivationState.NOT_TRACKING) // ) // fail("Illegal dependency state") // } function isComputingDerivation() { return globalState.trackingDerivation !== null; // filter out actions inside computations } function checkIfStateModificationsAreAllowed(atom) { var hasObservers = atom.observers.size > 0; // Should never be possible to change an observed observable from inside computed, see #798 if (globalState.computationDepth > 0 && hasObservers) fail(process.env.NODE_ENV !== "production" && "Computed values are not allowed to cause side effects by changing observables that are already being observed. Tried to modify: " + atom.name); // Should not be possible to change observed state outside strict mode, except during initialization, see #563 if (!globalState.allowStateChanges && (hasObservers || globalState.enforceActions === "strict")) fail(process.env.NODE_ENV !== "production" && (globalState.enforceActions ? "Since strict-mode is enabled, changing observed observable values outside actions is not allowed. Please wrap the code in an `action` if this change is intended. Tried to modify: " : "Side effects like changing state are not allowed at this point. Are you trying to modify state from, for example, the render function of a React component? Tried to modify: ") + atom.name); } function checkIfStateReadsAreAllowed(observable) { if (process.env.NODE_ENV !== "production" && !globalState.allowStateReads && globalState.observableRequiresReaction) { console.warn("[mobx] Observable " + observable.name + " being read outside a reactive context"); } } /** * Executes the provided function `f` and tracks which observables are being accessed. * The tracking information is stored on the `derivation` object and the derivation is registered * as observer of any of the accessed observables. */ function trackDerivedFunction(derivation, f, context) { var prevAllowStateReads = allowStateReadsStart(true); // pre allocate array allocation + room for variation in deps // array will be trimmed by bindDependencies changeDependenciesStateTo0(derivation); derivation.newObserving = new Array(derivation.observing.length + 100); derivation.unboundDepsCount = 0; derivation.runId = ++globalState.runId; var prevTracking = globalState.trackingDerivation; globalState.trackingDerivation = derivation; var result; if (globalState.disableErrorBoundaries === true) { result = f.call(context); } else { try { result = f.call(context); } catch (e) { result = new CaughtException(e); } } globalState.trackingDerivation = prevTracking; bindDependencies(derivation); warnAboutDerivationWithoutDependencies(derivation); allowStateReadsEnd(prevAllowStateReads); return result; } function warnAboutDerivationWithoutDependencies(derivation) { if (process.env.NODE_ENV === "production") return; if (derivation.observing.length !== 0) return; if (globalState.reactionRequiresObservable || derivation.requiresObservable) { console.warn("[mobx] Derivation " + derivation.name + " is created/updated without reading any observable value"); } } /** * diffs newObserving with observing. * update observing to be newObserving with unique observables * notify observers that become observed/unobserved */ function bindDependencies(derivation) { // invariant(derivation.dependenciesState !== IDerivationState.NOT_TRACKING, "INTERNAL ERROR bindDependencies expects derivation.dependenciesState !== -1"); var prevObserving = derivation.observing; var observing = (derivation.observing = derivation.newObserving); var lowestNewObservingDerivationState = exports.IDerivationState.UP_TO_DATE; // Go through all new observables and check diffValue: (this list can contain duplicates): // 0: first occurrence, change to 1 and keep it // 1: extra occurrence, drop it var i0 = 0, l = derivation.unboundDepsCount; for (var i = 0; i < l; i++) { var dep = observing[i]; if (dep.diffValue === 0) { dep.diffValue = 1; if (i0 !== i) observing[i0] = dep; i0++; } // Upcast is 'safe' here, because if dep is IObservable, `dependenciesState` will be undefined, // not hitting the condition if (dep.dependenciesState > lowestNewObservingDerivationState) { lowestNewObservingDerivationState = dep.dependenciesState; } } observing.length = i0; derivation.newObserving = null; // newObserving shouldn't be needed outside tracking (statement moved down to work around FF bug, see #614) // Go through all old observables and check diffValue: (it is unique after last bindDependencies) // 0: it's not in new observables, unobserve it // 1: it keeps being observed, don't want to notify it. change to 0 l = prevObserving.length; while (l--) { var dep = prevObserving[l]; if (dep.diffValue === 0) { removeObserver(dep, derivation); } dep.diffValue = 0; } // Go through all new observables and check diffValue: (now it should be unique) // 0: it was set to 0 in last loop. don't need to do anything. // 1: it wasn't observed, let's observe it. set back to 0 while (i0--) { var dep = observing[i0]; if (dep.diffValue === 1) { dep.diffValue = 0; addObserver(dep, derivation); } } // Some new observed derivations may become stale during this derivation computation // so they have had no chance to propagate staleness (#916) if (lowestNewObservingDerivationState !== exports.IDerivationState.UP_TO_DATE) { derivation.dependenciesState = lowestNewObservingDerivationState; derivation.onBecomeStale(); } } function clearObserving(derivation) { // invariant(globalState.inBatch > 0, "INTERNAL ERROR clearObserving should be called only inside batch"); var obs = derivation.observing; derivation.observing = []; var i = obs.length; while (i--) removeObserver(obs[i], derivation); derivation.dependenciesState = exports.IDerivationState.NOT_TRACKING; } function untracked(action) { var prev = untrackedStart(); try { return action(); } finally { untrackedEnd(prev); } } function untrackedStart() { var prev = globalState.trackingDerivation; globalState.trackingDerivation = null; return prev; } function untrackedEnd(prev) { globalState.trackingDerivation = prev; } function allowStateReadsStart(allowStateReads) { var prev = globalState.allowStateReads; globalState.allowStateReads = allowStateReads; return prev; } function allowStateReadsEnd(prev) { globalState.allowStateReads = prev; } /** * needed to keep `lowestObserverState` correct. when changing from (2 or 1) to 0 * */ function changeDependenciesStateTo0(derivation) { if (derivation.dependenciesState === exports.IDerivationState.UP_TO_DATE) return; derivation.dependenciesState = exports.IDerivationState.UP_TO_DATE; var obs = derivation.observing; var i = obs.length; while (i--) obs[i].lowestObserverState = exports.IDerivationState.UP_TO_DATE; } // we don't use globalState for these in order to avoid possible issues with multiple // mobx versions var currentActionId = 0; var nextActionId = 1; var functionNameDescriptor = Object.getOwnPropertyDescriptor(function () { }, "name"); var isFunctionNameConfigurable = functionNameDescriptor && functionNameDescriptor.configurable; function createAction(actionName, fn, ref) { if (process.env.NODE_ENV !== "production") { invariant(typeof fn === "function", "`action` can only be invoked on functions"); if (typeof actionName !== "string" || !actionName) fail("actions should have valid names, got: '" + actionName + "'"); } var res = function () { return executeAction(actionName, fn, ref || this, arguments); }; res.isMobxAction = true; if (process.env.NODE_ENV !== "production") { if (isFunctionNameConfigurable) { Object.defineProperty(res, "name", { value: actionName }); } } return res; } function executeAction(actionName, fn, scope, args) { var runInfo = _startAction(actionName, scope, args); try { return fn.apply(scope, args); } catch (err) { runInfo.error = err; throw err; } finally { _endAction(runInfo); } } function _startAction(actionName, scope, args) { var notifySpy = isSpyEnabled() && !!actionName; var startTime = 0; if (notifySpy && process.env.NODE_ENV !== "production") { startTime = Date.now(); var l = (args && args.length) || 0; var flattendArgs = new Array(l); if (l > 0) for (var i = 0; i < l; i++) flattendArgs[i] = args[i]; spyReportStart({ type: "action", name: actionName, object: scope, arguments: flattendArgs }); } var prevDerivation = untrackedStart(); startBatch(); var prevAllowStateChanges = allowStateChangesStart(true); var prevAllowStateReads = allowStateReadsStart(true); var runInfo = { prevDerivation: prevDerivation, prevAllowStateChanges: prevAllowStateChanges, prevAllowStateReads: prevAllowStateReads, notifySpy: notifySpy, startTime: startTime, actionId: nextActionId++, parentActionId: currentActionId }; currentActionId = runInfo.actionId; return runInfo; } function _endAction(runInfo) { if (currentActionId !== runInfo.actionId) { fail("invalid action stack. did you forget to finish an action?"); } currentActionId = runInfo.parentActionId; if (runInfo.error !== undefined) { globalState.suppressReactionErrors = true; } allowStateChangesEnd(runInfo.prevAllowStateChanges); allowStateReadsEnd(runInfo.prevAllowStateReads); endBatch(); untrackedEnd(runInfo.prevDerivation); if (runInfo.notifySpy && process.env.NODE_ENV !== "production") { spyReportEnd({ time: Date.now() - runInfo.startTime }); } globalState.suppressReactionErrors = false; } function allowStateChanges(allowStateChanges, func) { var prev = allowStateChangesStart(allowStateChanges); var res; try { res = func(); } finally { allowStateChangesEnd(prev); } return res; } function allowStateChangesStart(allowStateChanges) { var prev = globalState.allowStateChanges; globalState.allowStateChanges = allowStateChanges; return prev; } function allowStateChangesEnd(prev) { globalState.allowStateChanges = prev; } function allowStateChangesInsideComputed(func) { var prev = globalState.computationDepth; globalState.computationDepth = 0; var res; try { res = func(); } finally { globalState.computationDepth = prev; } return res; } var ObservableValue = /** @class */ (function (_super) { __extends(ObservableValue, _super); function ObservableValue(value, enhancer, name, notifySpy, equals) { if (name === void 0) { name = "ObservableValue@" + getNextId(); } if (notifySpy === void 0) { notifySpy = true; } if (equals === void 0) { equals = comparer.default; } var _this = _super.call(this, name) || this; _this.enhancer = enhancer; _this.name = name; _this.equals = equals; _this.hasUnreportedChange = false; _this.value = enhancer(value, undefined, name); if (notifySpy && isSpyEnabled() && process.env.NODE_ENV !== "production") { // only notify spy if this is a stand-alone observable spyReport({ type: "create", name: _this.name, newValue: "" + _this.value }); } return _this; } ObservableValue.prototype.dehanceValue = function (value) { if (this.dehancer !== undefined) return this.dehancer(value); return value; }; ObservableValue.prototype.set = function (newValue) { var oldValue = this.value; newValue = this.prepareNewValue(newValue); if (newValue !== globalState.UNCHANGED) { var notifySpy = isSpyEnabled(); if (notifySpy && process.env.NODE_ENV !== "production") { spyReportStart({ type: "update", name: this.name, newValue: newValue, oldValue: oldValue }); } this.setNewValue(newValue); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); } }; ObservableValue.prototype.prepareNewValue = function (newValue) { checkIfStateModificationsAreAllowed(this); if (hasInterceptors(this)) { var change = interceptChange(this, { object: this, type: "update", newValue: newValue }); if (!change) return globalState.UNCHANGED; newValue = change.newValue; } // apply modifier newValue = this.enhancer(newValue, this.value, this.name); return this.equals(this.value, newValue) ? globalState.UNCHANGED : newValue; }; ObservableValue.prototype.setNewValue = function (newValue) { var oldValue = this.value; this.value = newValue; this.reportChanged(); if (hasListeners(this)) { notifyListeners(this, { type: "update", object: this, newValue: newValue, oldValue: oldValue }); } }; ObservableValue.prototype.get = function () { this.reportObserved(); return this.dehanceValue(this.value); }; ObservableValue.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableValue.prototype.observe = function (listener, fireImmediately) { if (fireImmediately) listener({ object: this, type: "update", newValue: this.value, oldValue: undefined }); return registerListener(this, listener); }; ObservableValue.prototype.toJSON = function () { return this.get(); }; ObservableValue.prototype.toString = function () { return this.name + "[" + this.value + "]"; }; ObservableValue.prototype.valueOf = function () { return toPrimitive(this.get()); }; ObservableValue.prototype[Symbol.toPrimitive] = function () { return this.valueOf(); }; return ObservableValue; }(Atom)); var isObservableValue = createInstanceofPredicate("ObservableValue", ObservableValue); /** * A node in the state dependency root that observes other nodes, and can be observed itself. * * ComputedValue will remember the result of the computation for the duration of the batch, or * while being observed. * * During this time it will recompute only when one of its direct dependencies changed, * but only when it is being accessed with `ComputedValue.get()`. * * Implementation description: * 1. First time it's being accessed it will compute and remember result * give back remembered result until 2. happens * 2. First time any deep dependency change, propagate POSSIBLY_STALE to all observers, wait for 3. * 3. When it's being accessed, recompute if any shallow dependency changed. * if result changed: propagate STALE to all observers, that were POSSIBLY_STALE from the last step. * go to step 2. either way * * If at any point it's outside batch and it isn't observed: reset everything and go to 1. */ var ComputedValue = /** @class */ (function () { /** * Create a new computed value based on a function expression. * * The `name` property is for debug purposes only. * * The `equals` property specifies the comparer function to use to determine if a newly produced * value differs from the previous value. Two comparers are provided in the library; `defaultComparer` * compares based on identity comparison (===), and `structualComparer` deeply compares the structure. * Structural comparison can be convenient if you always produce a new aggregated object and * don't want to notify observers if it is structurally the same. * This is useful for working with vectors, mouse coordinates etc. */ function ComputedValue(options) { this.dependenciesState = exports.IDerivationState.NOT_TRACKING; this.observing = []; // nodes we are looking at. Our value depends on these nodes this.newObserving = null; // during tracking it's an array with new observed observers this.isBeingObserved = false; this.isPendingUnobservation = false; this.observers = new Set(); this.diffValue = 0; this.runId = 0; this.lastAccessedBy = 0; this.lowestObserverState = exports.IDerivationState.UP_TO_DATE; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.value = new CaughtException(null); this.isComputing = false; // to check for cycles this.isRunningSetter = false; this.isTracing = TraceMode.NONE; invariant(options.get, "missing option for computed: get"); this.derivation = options.get; this.name = options.name || "ComputedValue@" + getNextId(); if (options.set) this.setter = createAction(this.name + "-setter", options.set); this.equals = options.equals || (options.compareStructural || options.struct ? comparer.structural : comparer.default); this.scope = options.context; this.requiresReaction = !!options.requiresReaction; this.keepAlive = !!options.keepAlive; } ComputedValue.prototype.onBecomeStale = function () { propagateMaybeChanged(this); }; ComputedValue.prototype.onBecomeObserved = function () { if (this.onBecomeObservedListeners) { this.onBecomeObservedListeners.forEach(function (listener) { return listener(); }); } }; ComputedValue.prototype.onBecomeUnobserved = function () { if (this.onBecomeUnobservedListeners) { this.onBecomeUnobservedListeners.forEach(function (listener) { return listener(); }); } }; /** * Returns the current value of this computed value. * Will evaluate its computation first if needed. */ ComputedValue.prototype.get = function () { if (this.isComputing) fail("Cycle detected in computation " + this.name + ": " + this.derivation); if (globalState.inBatch === 0 && this.observers.size === 0 && !this.keepAlive) { if (shouldCompute(this)) { this.warnAboutUntrackedRead(); startBatch(); // See perf test 'computed memoization' this.value = this.computeValue(false); endBatch(); } } else { reportObserved(this); if (shouldCompute(this)) if (this.trackAndCompute()) propagateChangeConfirmed(this); } var result = this.value; if (isCaughtException(result)) throw result.cause; return result; }; ComputedValue.prototype.peek = function () { var res = this.computeValue(false); if (isCaughtException(res)) throw res.cause; return res; }; ComputedValue.prototype.set = function (value) { if (this.setter) { invariant(!this.isRunningSetter, "The setter of computed value '" + this.name + "' is trying to update itself. Did you intend to update an _observable_ value, instead of the computed property?"); this.isRunningSetter = true; try { this.setter.call(this.scope, value); } finally { this.isRunningSetter = false; } } else invariant(false, process.env.NODE_ENV !== "production" && "[ComputedValue '" + this.name + "'] It is not possible to assign a new value to a computed value."); }; ComputedValue.prototype.trackAndCompute = function () { if (isSpyEnabled() && process.env.NODE_ENV !== "production") { spyReport({ object: this.scope, type: "compute", name: this.name }); } var oldValue = this.value; var wasSuspended = /* see #1208 */ this.dependenciesState === exports.IDerivationState.NOT_TRACKING; var newValue = this.computeValue(true); var changed = wasSuspended || isCaughtException(oldValue) || isCaughtException(newValue) || !this.equals(oldValue, newValue); if (changed) { this.value = newValue; } return changed; }; ComputedValue.prototype.computeValue = function (track) { this.isComputing = true; globalState.computationDepth++; var res; if (track) { res = trackDerivedFunction(this, this.derivation, this.scope); } else { if (globalState.disableErrorBoundaries === true) { res = this.derivation.call(this.scope); } else { try { res = this.derivation.call(this.scope); } catch (e) { res = new CaughtException(e); } } } globalState.computationDepth--; this.isComputing = false; return res; }; ComputedValue.prototype.suspend = function () { if (!this.keepAlive) { clearObserving(this); this.value = undefined; // don't hold on to computed value! } }; ComputedValue.prototype.observe = function (listener, fireImmediately) { var _this = this; var firstTime = true; var prevValue = undefined; return autorun(function () { var newValue = _this.get(); if (!firstTime || fireImmediately) { var prevU = untrackedStart(); listener({ type: "update", object: _this, newValue: newValue, oldValue: prevValue }); untrackedEnd(prevU); } firstTime = false; prevValue = newValue; }); }; ComputedValue.prototype.warnAboutUntrackedRead = function () { if (process.env.NODE_ENV === "production") return; if (this.requiresReaction === true) { fail("[mobx] Computed value " + this.name + " is read outside a reactive context"); } if (this.isTracing !== TraceMode.NONE) { console.log("[mobx.trace] '" + this.name + "' is being read outside a reactive context. Doing a full recompute"); } if (globalState.computedRequiresReaction) { console.warn("[mobx] Computed value " + this.name + " is being read outside a reactive context. Doing a full recompute"); } }; ComputedValue.prototype.toJSON = function () { return this.get(); }; ComputedValue.prototype.toString = function () { return this.name + "[" + this.derivation.toString() + "]"; }; ComputedValue.prototype.valueOf = function () { return toPrimitive(this.get()); }; ComputedValue.prototype[Symbol.toPrimitive] = function () { return this.valueOf(); }; return ComputedValue; }()); var isComputedValue = createInstanceofPredicate("ComputedValue", ComputedValue); /** * These values will persist if global state is reset */ var persistentKeys = [ "mobxGuid", "spyListeners", "enforceActions", "computedRequiresReaction", "reactionRequiresObservable", "observableRequiresReaction", "allowStateReads", "disableErrorBoundaries", "runId", "UNCHANGED" ]; var MobXGlobals = /** @class */ (function () { function MobXGlobals() { /** * MobXGlobals version. * MobX compatiblity with other versions loaded in memory as long as this version matches. * It indicates that the global state still stores similar information * * N.B: this version is unrelated to the package version of MobX, and is only the version of the * internal state storage of MobX, and can be the same across many different package versions */ this.version = 5; /** * globally unique token to signal unchanged */ this.UNCHANGED = {}; /** * Currently running derivation */ this.trackingDerivation = null; /** * Are we running a computation currently? (not a reaction) */ this.computationDepth = 0; /** * Each time a derivation is tracked, it is assigned a unique run-id */ this.runId = 0; /** * 'guid' for general purpose. Will be persisted amongst resets. */ this.mobxGuid = 0; /** * Are we in a batch block? (and how many of them) */ this.inBatch = 0; /** * Observables that don't have observers anymore, and are about to be * suspended, unless somebody else accesses it in the same batch * * @type {IObservable[]} */ this.pendingUnobservations = []; /** * List of scheduled, not yet executed, reactions. */ this.pendingReactions = []; /** * Are we currently processing reactions? */ this.isRunningReactions = false; /** * Is it allowed to change observables at this point? * In general, MobX doesn't allow that when running computations and React.render. * To ensure that those functions stay pure. */ this.allowStateChanges = true; /** * Is it allowed to read observables at this point? * Used to hold the state needed for `observableRequiresReaction` */ this.allowStateReads = true; /** * If strict mode is enabled, state changes are by default not allowed */ this.enforceActions = false; /** * Spy callbacks */ this.spyListeners = []; /** * Globally attached error handlers that react specifically to errors in reactions */ this.globalReactionErrorHandlers = []; /** * Warn if computed values are accessed outside a reactive context */ this.computedRequiresReaction = false; /** * (Experimental) * Warn if you try to create to derivation / reactive context without accessing any observable. */ this.reactionRequiresObservable = false; /** * (Experimental) * Warn if observables are accessed outside a reactive context */ this.observableRequiresReaction = false; /** * Allows overwriting of computed properties, useful in tests but not prod as it can cause * memory leaks. See https://github.com/mobxjs/mobx/issues/1867 */ this.computedConfigurable = false; /* * Don't catch and rethrow exceptions. This is useful for inspecting the state of * the stack when an exception occurs while debugging. */ this.disableErrorBoundaries = false; /* * If true, we are already handling an exception in an action. Any errors in reactions should be suppressed, as * they are not the cause, see: https://github.com/mobxjs/mobx/issues/1836 */ this.suppressReactionErrors = false; } return MobXGlobals; }()); var mockGlobal = {}; function getGlobal() { if (typeof window !== "undefined") { return window; } if (typeof global !== "undefined") { return global; } if (typeof self !== "undefined") { return self; } return mockGlobal; } var canMergeGlobalState = true; var isolateCalled = false; var globalState = (function () { var global = getGlobal(); if (global.__mobxInstanceCount > 0 && !global.__mobxGlobals) canMergeGlobalState = false; if (global.__mobxGlobals && global.__mobxGlobals.version !== new MobXGlobals().version) canMergeGlobalState = false; if (!canMergeGlobalState) { setTimeout(function () { if (!isolateCalled) { fail("There are multiple, different versions of MobX active. Make sure MobX is loaded only once or use `configure({ isolateGlobalState: true })`"); } }, 1); return new MobXGlobals(); } else if (global.__mobxGlobals) { global.__mobxInstanceCount += 1; if (!global.__mobxGlobals.UNCHANGED) global.__mobxGlobals.UNCHANGED = {}; // make merge backward compatible return global.__mobxGlobals; } else { global.__mobxInstanceCount = 1; return (global.__mobxGlobals = new MobXGlobals()); } })(); function isolateGlobalState() { if (globalState.pendingReactions.length || globalState.inBatch || globalState.isRunningReactions) fail("isolateGlobalState should be called before MobX is running any reactions"); isolateCalled = true; if (canMergeGlobalState) { if (--getGlobal().__mobxInstanceCount === 0) getGlobal().__mobxGlobals = undefined; globalState = new MobXGlobals(); } } function getGlobalState() { return globalState; } /** * For testing purposes only; this will break the internal state of existing observables, * but can be used to get back at a stable state after throwing errors */ function resetGlobalState() { var defaultGlobals = new MobXGlobals(); for (var key in defaultGlobals) if (persistentKeys.indexOf(key) === -1) globalState[key] = defaultGlobals[key]; globalState.allowStateChanges = !globalState.enforceActions; } function hasObservers(observable) { return observable.observers && observable.observers.size > 0; } function getObservers(observable) { return observable.observers; } // function invariantObservers(observable: IObservable) { // const list = observable.observers // const map = observable.observersIndexes // const l = list.length // for (let i = 0; i < l; i++) { // const id = list[i].__mapid // if (i) { // invariant(map[id] === i, "INTERNAL ERROR maps derivation.__mapid to index in list") // for performance // } else { // invariant(!(id in map), "INTERNAL ERROR observer on index 0 shouldn't be held in map.") // for performance // } // } // invariant( // list.length === 0 || Object.keys(map).length === list.length - 1, // "INTERNAL ERROR there is no junk in map" // ) // } function addObserver(observable, node) { // invariant(node.dependenciesState !== -1, "INTERNAL ERROR, can add only dependenciesState !== -1"); // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR add already added node"); // invariantObservers(observable); observable.observers.add(node); if (observable.lowestObserverState > node.dependenciesState) observable.lowestObserverState = node.dependenciesState; // invariantObservers(observable); // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR didn't add node"); } function removeObserver(observable, node) { // invariant(globalState.inBatch > 0, "INTERNAL ERROR, remove should be called only inside batch"); // invariant(observable._observers.indexOf(node) !== -1, "INTERNAL ERROR remove already removed node"); // invariantObservers(observable); observable.observers.delete(node); if (observable.observers.size === 0) { // deleting last observer queueForUnobservation(observable); } // invariantObservers(observable); // invariant(observable._observers.indexOf(node) === -1, "INTERNAL ERROR remove already removed node2"); } function queueForUnobservation(observable) { if (observable.isPendingUnobservation === false) { // invariant(observable._observers.length === 0, "INTERNAL ERROR, should only queue for unobservation unobserved observables"); observable.isPendingUnobservation = true; globalState.pendingUnobservations.push(observable); } } /** * Batch starts a transaction, at least for purposes of memoizing ComputedValues when nothing else does. * During a batch `onBecomeUnobserved` will be called at most once per observable. * Avoids unnecessary recalculations. */ function startBatch() { globalState.inBatch++; } function endBatch() { if (--globalState.inBatch === 0) { runReactions(); // the batch is actually about to finish, all unobserving should happen here. var list = globalState.pendingUnobservations; for (var i = 0; i < list.length; i++) { var observable = list[i]; observable.isPendingUnobservation = false; if (observable.observers.size === 0) { if (observable.isBeingObserved) { // if this observable had reactive observers, trigger the hooks observable.isBeingObserved = false; observable.onBecomeUnobserved(); } if (observable instanceof ComputedValue) { // computed values are automatically teared down when the last observer leaves // this process happens recursively, this computed might be the last observable of another, etc.. observable.suspend(); } } } globalState.pendingUnobservations = []; } } function reportObserved(observable) { checkIfStateReadsAreAllowed(observable); var derivation = globalState.trackingDerivation; if (derivation !== null) { /** * Simple optimization, give each derivation run an unique id (runId) * Check if last time this observable was accessed the same runId is used * if this is the case, the relation is already known */ if (derivation.runId !== observable.lastAccessedBy) { observable.lastAccessedBy = derivation.runId; // Tried storing newObserving, or observing, or both as Set, but performance didn't come close... derivation.newObserving[derivation.unboundDepsCount++] = observable; if (!observable.isBeingObserved) { observable.isBeingObserved = true; observable.onBecomeObserved(); } } return true; } else if (observable.observers.size === 0 && globalState.inBatch > 0) { queueForUnobservation(observable); } return false; } // function invariantLOS(observable: IObservable, msg: string) { // // it's expensive so better not run it in produciton. but temporarily helpful for testing // const min = getObservers(observable).reduce((a, b) => Math.min(a, b.dependenciesState), 2) // if (min >= observable.lowestObserverState) return // <- the only assumption about `lowestObserverState` // throw new Error( // "lowestObserverState is wrong for " + // msg + // " because " + // min + // " < " + // observable.lowestObserverState // ) // } /** * NOTE: current propagation mechanism will in case of self reruning autoruns behave unexpectedly * It will propagate changes to observers from previous run * It's hard or maybe impossible (with reasonable perf) to get it right with current approach * Hopefully self reruning autoruns aren't a feature people should depend on * Also most basic use cases should be ok */ // Called by Atom when its value changes function propagateChanged(observable) { // invariantLOS(observable, "changed start"); if (observable.lowestObserverState === exports.IDerivationState.STALE) return; observable.lowestObserverState = exports.IDerivationState.STALE; // Ideally we use for..of here, but the downcompiled version is really slow... observable.observers.forEach(function (d) { if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE) { if (d.isTracing !== TraceMode.NONE) { logTraceInfo(d, observable); } d.onBecomeStale(); } d.dependenciesState = exports.IDerivationState.STALE; }); // invariantLOS(observable, "changed end"); } // Called by ComputedValue when it recalculate and its value changed function propagateChangeConfirmed(observable) { // invariantLOS(observable, "confirmed start"); if (observable.lowestObserverState === exports.IDerivationState.STALE) return; observable.lowestObserverState = exports.IDerivationState.STALE; observable.observers.forEach(function (d) { if (d.dependenciesState === exports.IDerivationState.POSSIBLY_STALE) d.dependenciesState = exports.IDerivationState.STALE; else if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE // this happens during computing of `d`, just keep lowestObserverState up to date. ) observable.lowestObserverState = exports.IDerivationState.UP_TO_DATE; }); // invariantLOS(observable, "confirmed end"); } // Used by computed when its dependency changed, but we don't wan't to immediately recompute. function propagateMaybeChanged(observable) { // invariantLOS(observable, "maybe start"); if (observable.lowestObserverState !== exports.IDerivationState.UP_TO_DATE) return; observable.lowestObserverState = exports.IDerivationState.POSSIBLY_STALE; observable.observers.forEach(function (d) { if (d.dependenciesState === exports.IDerivationState.UP_TO_DATE) { d.dependenciesState = exports.IDerivationState.POSSIBLY_STALE; if (d.isTracing !== TraceMode.NONE) { logTraceInfo(d, observable); } d.onBecomeStale(); } }); // invariantLOS(observable, "maybe end"); } function logTraceInfo(derivation, observable) { console.log("[mobx.trace] '" + derivation.name + "' is invalidated due to a change in: '" + observable.name + "'"); if (derivation.isTracing === TraceMode.BREAK) { var lines = []; printDepTree(getDependencyTree(derivation), lines, 1); // prettier-ignore new Function("debugger;\n/*\nTracing '" + derivation.name + "'\n\nYou are entering this break point because derivation '" + derivation.name + "' is being traced and '" + observable.name + "' is now forcing it to update.\nJust follow the stacktrace you should now see in the devtools to see precisely what piece of your code is causing this update\nThe stackframe you are looking for is at least ~6-8 stack-frames up.\n\n" + (derivation instanceof ComputedValue ? derivation.derivation.toString().replace(/[*]\//g, "/") : "") + "\n\nThe dependencies for this derivation are:\n\n" + lines.join("\n") + "\n*/\n ")(); } } function printDepTree(tree, lines, depth) { if (lines.length >= 1000) { lines.push("(and many more)"); return; } lines.push("" + new Array(depth).join("\t") + tree.name); // MWE: not the fastest, but the easiest way :) if (tree.dependencies) tree.dependencies.forEach(function (child) { return printDepTree(child, lines, depth + 1); }); } var Reaction = /** @class */ (function () { function Reaction(name, onInvalidate, errorHandler, requiresObservable) { if (name === void 0) { name = "Reaction@" + getNextId(); } if (requiresObservable === void 0) { requiresObservable = false; } this.name = name; this.onInvalidate = onInvalidate; this.errorHandler = errorHandler; this.requiresObservable = requiresObservable; this.observing = []; // nodes we are looking at. Our value depends on these nodes this.newObserving = []; this.dependenciesState = exports.IDerivationState.NOT_TRACKING; this.diffValue = 0; this.runId = 0; this.unboundDepsCount = 0; this.__mapid = "#" + getNextId(); this.isDisposed = false; this._isScheduled = false; this._isTrackPending = false; this._isRunning = false; this.isTracing = TraceMode.NONE; } Reaction.prototype.onBecomeStale = function () { this.schedule(); }; Reaction.prototype.schedule = function () { if (!this._isScheduled) { this._isScheduled = true; globalState.pendingReactions.push(this); runReactions(); } }; Reaction.prototype.isScheduled = function () { return this._isScheduled; }; /** * internal, use schedule() if you intend to kick off a reaction */ Reaction.prototype.runReaction = function () { if (!this.isDisposed) { startBatch(); this._isScheduled = false; if (shouldCompute(this)) { this._isTrackPending = true; try { this.onInvalidate(); if (this._isTrackPending && isSpyEnabled() && process.env.NODE_ENV !== "production") { // onInvalidate didn't trigger track right away.. spyReport({ name: this.name, type: "scheduled-reaction" }); } } catch (e) { this.reportExceptionInDerivation(e); } } endBatch(); } }; Reaction.prototype.track = function (fn) { if (this.isDisposed) { return; // console.warn("Reaction already disposed") // Note: Not a warning / error in mobx 4 either } startBatch(); var notify = isSpyEnabled(); var startTime; if (notify && process.env.NODE_ENV !== "production") { startTime = Date.now(); spyReportStart({ name: this.name, type: "reaction" }); } this._isRunning = true; var result = trackDerivedFunction(this, fn, undefined); this._isRunning = false; this._isTrackPending = false; if (this.isDisposed) { // disposed during last run. Clean up everything that was bound after the dispose call. clearObserving(this); } if (isCaughtException(result)) this.reportExceptionInDerivation(result.cause); if (notify && process.env.NODE_ENV !== "production") { spyReportEnd({ time: Date.now() - startTime }); } endBatch(); }; Reaction.prototype.reportExceptionInDerivation = function (error) { var _this = this; if (this.errorHandler) { this.errorHandler(error, this); return; } if (globalState.disableErrorBoundaries) throw error; var message = "[mobx] Encountered an uncaught exception that was thrown by a reaction or observer component, in: '" + this + "'"; if (globalState.suppressReactionErrors) { console.warn("[mobx] (error in reaction '" + this.name + "' suppressed, fix error of causing action below)"); // prettier-ignore } else { console.error(message, error); /** If debugging brought you here, please, read the above message :-). Tnx! */ } if (isSpyEnabled()) { spyReport({ type: "error", name: this.name, message: message, error: "" + error }); } globalState.globalReactionErrorHandlers.forEach(function (f) { return f(error, _this); }); }; Reaction.prototype.dispose = function () { if (!this.isDisposed) { this.isDisposed = true; if (!this._isRunning) { // if disposed while running, clean up later. Maybe not optimal, but rare case startBatch(); clearObserving(this); endBatch(); } } }; Reaction.prototype.getDisposer = function () { var r = this.dispose.bind(this); r[$mobx] = this; return r; }; Reaction.prototype.toString = function () { return "Reaction[" + this.name + "]"; }; Reaction.prototype.trace = function (enterBreakPoint) { if (enterBreakPoint === void 0) { enterBreakPoint = false; } trace(this, enterBreakPoint); }; return Reaction; }()); function onReactionError(handler) { globalState.globalReactionErrorHandlers.push(handler); return function () { var idx = globalState.globalReactionErrorHandlers.indexOf(handler); if (idx >= 0) globalState.globalReactionErrorHandlers.splice(idx, 1); }; } /** * Magic number alert! * Defines within how many times a reaction is allowed to re-trigger itself * until it is assumed that this is gonna be a never ending loop... */ var MAX_REACTION_ITERATIONS = 100; var reactionScheduler = function (f) { return f(); }; function runReactions() { // Trampolining, if runReactions are already running, new reactions will be picked up if (globalState.inBatch > 0 || globalState.isRunningReactions) return; reactionScheduler(runReactionsHelper); } function runReactionsHelper() { globalState.isRunningReactions = true; var allReactions = globalState.pendingReactions; var iterations = 0; // While running reactions, new reactions might be triggered. // Hence we work with two variables and check whether // we converge to no remaining reactions after a while. while (allReactions.length > 0) { if (++iterations === MAX_REACTION_ITERATIONS) { console.error("Reaction doesn't converge to a stable state after " + MAX_REACTION_ITERATIONS + " iterations." + (" Probably there is a cycle in the reactive function: " + allReactions[0])); allReactions.splice(0); // clear reactions } var remainingReactions = allReactions.splice(0); for (var i = 0, l = remainingReactions.length; i < l; i++) remainingReactions[i].runReaction(); } globalState.isRunningReactions = false; } var isReaction = createInstanceofPredicate("Reaction", Reaction); function setReactionScheduler(fn) { var baseScheduler = reactionScheduler; reactionScheduler = function (f) { return fn(function () { return baseScheduler(f); }); }; } function isSpyEnabled() { return process.env.NODE_ENV !== "production" && !!globalState.spyListeners.length; } function spyReport(event) { if (process.env.NODE_ENV === "production") return; // dead code elimination can do the rest if (!globalState.spyListeners.length) return; var listeners = globalState.spyListeners; for (var i = 0, l = listeners.length; i < l; i++) listeners[i](event); } function spyReportStart(event) { if (process.env.NODE_ENV === "production") return; var change = __assign(__assign({}, event), { spyReportStart: true }); spyReport(change); } var END_EVENT = { spyReportEnd: true }; function spyReportEnd(change) { if (process.env.NODE_ENV === "production") return; if (change) spyReport(__assign(__assign({}, change), { spyReportEnd: true })); else spyReport(END_EVENT); } function spy(listener) { if (process.env.NODE_ENV === "production") { console.warn("[mobx.spy] Is a no-op in production builds"); return function () { }; } else { globalState.spyListeners.push(listener); return once(function () { globalState.spyListeners = globalState.spyListeners.filter(function (l) { return l !== listener; }); }); } } function dontReassignFields() { fail(process.env.NODE_ENV !== "production" && "@action fields are not reassignable"); } function namedActionDecorator(name) { return function (target, prop, descriptor) { if (descriptor) { if (process.env.NODE_ENV !== "production" && descriptor.get !== undefined) { return fail("@action cannot be used with getters"); } // babel / typescript // @action method() { } if (descriptor.value) { // typescript return { value: createAction(name, descriptor.value), enumerable: false, configurable: true, writable: true // for typescript, this must be writable, otherwise it cannot inherit :/ (see inheritable actions test) }; } // babel only: @action method = () => {} var initializer_1 = descriptor.initializer; return { enumerable: false, configurable: true, writable: true, initializer: function () { // N.B: we can't immediately invoke initializer; this would be wrong return createAction(name, initializer_1.call(this)); } }; } // bound instance methods return actionFieldDecorator(name).apply(this, arguments); }; } function actionFieldDecorator(name) { // Simple property that writes on first invocation to the current instance return function (target, prop, descriptor) { Object.defineProperty(target, prop, { configurable: true, enumerable: false, get: function () { return undefined; }, set: function (value) { addHiddenProp(this, prop, action(name, value)); } }); }; } function boundActionDecorator(target, propertyName, descriptor, applyToInstance) { if (applyToInstance === true) { defineBoundAction(target, propertyName, descriptor.value); return null; } if (descriptor) { // if (descriptor.value) // Typescript / Babel: @action.bound method() { } // also: babel @action.bound method = () => {} return { configurable: true, enumerable: false, get: function () { defineBoundAction(this, propertyName, descriptor.value || descriptor.initializer.call(this)); return this[propertyName]; }, set: dontReassignFields }; } // field decorator Typescript @action.bound method = () => {} return { enumerable: false, configurable: true, set: function (v) { defineBoundAction(this, propertyName, v); }, get: function () { return undefined; } }; } var action = function action(arg1, arg2, arg3, arg4) { // action(fn() {}) if (arguments.length === 1 && typeof arg1 === "function") return createAction(arg1.name || "<unnamed action>", arg1); // action("name", fn() {}) if (arguments.length === 2 && typeof arg2 === "function") return createAction(arg1, arg2); // @action("name") fn() {} if (arguments.length === 1 && typeof arg1 === "string") return namedActionDecorator(arg1); // @action fn() {} if (arg4 === true) { // apply to instance immediately addHiddenProp(arg1, arg2, createAction(arg1.name || arg2, arg3.value, this)); } else { return namedActionDecorator(arg2).apply(null, arguments); } }; action.bound = boundActionDecorator; function runInAction(arg1, arg2) { var actionName = typeof arg1 === "string" ? arg1 : arg1.name || "<unnamed action>"; var fn = typeof arg1 === "function" ? arg1 : arg2; if (process.env.NODE_ENV !== "production") { invariant(typeof fn === "function" && fn.length === 0, "`runInAction` expects a function without arguments"); if (typeof actionName !== "string" || !actionName) fail("actions should have valid names, got: '" + actionName + "'"); } return executeAction(actionName, fn, this, undefined); } function isAction(thing) { return typeof thing === "function" && thing.isMobxAction === true; } function defineBoundAction(target, propertyName, fn) { addHiddenProp(target, propertyName, createAction(propertyName, fn.bind(target))); } /** * Creates a named reactive view and keeps it alive, so that the view is always * updated if one of the dependencies changes, even when the view is not further used by something else. * @param view The reactive view * @returns disposer function, which can be used to stop the view from being updated in the future. */ function autorun(view, opts) { if (opts === void 0) { opts = EMPTY_OBJECT; } if (process.env.NODE_ENV !== "production") { invariant(typeof view === "function", "Autorun expects a function as first argument"); invariant(isAction(view) === false, "Autorun does not accept actions since actions are untrackable"); } var name = (opts && opts.name) || view.name || "Autorun@" + getNextId(); var runSync = !opts.scheduler && !opts.delay; var reaction; if (runSync) { // normal autorun reaction = new Reaction(name, function () { this.track(reactionRunner); }, opts.onError, opts.requiresObservable); } else { var scheduler_1 = createSchedulerFromOptions(opts); // debounced autorun var isScheduled_1 = false; reaction = new Reaction(name, function () { if (!isScheduled_1) { isScheduled_1 = true; scheduler_1(function () { isScheduled_1 = false; if (!reaction.isDisposed) reaction.track(reactionRunner); }); } }, opts.onError, opts.requiresObservable); } function reactionRunner() { view(reaction); } reaction.schedule(); return reaction.getDisposer(); } var run = function (f) { return f(); }; function createSchedulerFromOptions(opts) { return opts.scheduler ? opts.scheduler : opts.delay ? function (f) { return setTimeout(f, opts.delay); } : run; } function reaction(expression, effect, opts) { if (opts === void 0) { opts = EMPTY_OBJECT; } if (process.env.NODE_ENV !== "production") { invariant(typeof expression === "function", "First argument to reaction should be a function"); invariant(typeof opts === "object", "Third argument of reactions should be an object"); } var name = opts.name || "Reaction@" + getNextId(); var effectAction = action(name, opts.onError ? wrapErrorHandler(opts.onError, effect) : effect); var runSync = !opts.scheduler && !opts.delay; var scheduler = createSchedulerFromOptions(opts); var firstTime = true; var isScheduled = false; var value; var equals = opts.compareStructural ? comparer.structural : opts.equals || comparer.default; var r = new Reaction(name, function () { if (firstTime || runSync) { reactionRunner(); } else if (!isScheduled) { isScheduled = true; scheduler(reactionRunner); } }, opts.onError, opts.requiresObservable); function reactionRunner() { isScheduled = false; // Q: move into reaction runner? if (r.isDisposed) return; var changed = false; r.track(function () { var nextValue = expression(r); changed = firstTime || !equals(value, nextValue); value = nextValue; }); if (firstTime && opts.fireImmediately) effectAction(value, r); if (!firstTime && changed === true) effectAction(value, r); if (firstTime) firstTime = false; } r.schedule(); return r.getDisposer(); } function wrapErrorHandler(errorHandler, baseFn) { return function () { try { return baseFn.apply(this, arguments); } catch (e) { errorHandler.call(this, e); } }; } function onBecomeObserved(thing, arg2, arg3) { return interceptHook("onBecomeObserved", thing, arg2, arg3); } function onBecomeUnobserved(thing, arg2, arg3) { return interceptHook("onBecomeUnobserved", thing, arg2, arg3); } function interceptHook(hook, thing, arg2, arg3) { var atom = typeof arg3 === "function" ? getAtom(thing, arg2) : getAtom(thing); var cb = typeof arg3 === "function" ? arg3 : arg2; var listenersKey = hook + "Listeners"; if (atom[listenersKey]) { atom[listenersKey].add(cb); } else { atom[listenersKey] = new Set([cb]); } var orig = atom[hook]; if (typeof orig !== "function") return fail(process.env.NODE_ENV !== "production" && "Not an atom that can be (un)observed"); return function () { var hookListeners = atom[listenersKey]; if (hookListeners) { hookListeners.delete(cb); if (hookListeners.size === 0) { delete atom[listenersKey]; } } }; } function configure(options) { var enforceActions = options.enforceActions, computedRequiresReaction = options.computedRequiresReaction, computedConfigurable = options.computedConfigurable, disableErrorBoundaries = options.disableErrorBoundaries, reactionScheduler = options.reactionScheduler, reactionRequiresObservable = options.reactionRequiresObservable, observableRequiresReaction = options.observableRequiresReaction; if (options.isolateGlobalState === true) { isolateGlobalState(); } if (enforceActions !== undefined) { if (typeof enforceActions === "boolean" || enforceActions === "strict") deprecated("Deprecated value for 'enforceActions', use 'false' => '\"never\"', 'true' => '\"observed\"', '\"strict\"' => \"'always'\" instead"); var ea = void 0; switch (enforceActions) { case true: case "observed": ea = true; break; case false: case "never": ea = false; break; case "strict": case "always": ea = "strict"; break; default: fail("Invalid value for 'enforceActions': '" + enforceActions + "', expected 'never', 'always' or 'observed'"); } globalState.enforceActions = ea; globalState.allowStateChanges = ea === true || ea === "strict" ? false : true; } if (computedRequiresReaction !== undefined) { globalState.computedRequiresReaction = !!computedRequiresReaction; } if (reactionRequiresObservable !== undefined) { globalState.reactionRequiresObservable = !!reactionRequiresObservable; } if (observableRequiresReaction !== undefined) { globalState.observableRequiresReaction = !!observableRequiresReaction; globalState.allowStateReads = !globalState.observableRequiresReaction; } if (computedConfigurable !== undefined) { globalState.computedConfigurable = !!computedConfigurable; } if (disableErrorBoundaries !== undefined) { if (disableErrorBoundaries === true) console.warn("WARNING: Debug feature only. MobX will NOT recover from errors when `disableErrorBoundaries` is enabled."); globalState.disableErrorBoundaries = !!disableErrorBoundaries; } if (reactionScheduler) { setReactionScheduler(reactionScheduler); } } function decorate(thing, decorators) { process.env.NODE_ENV !== "production" && invariant(isPlainObject(decorators), "Decorators should be a key value map"); var target = typeof thing === "function" ? thing.prototype : thing; var _loop_1 = function (prop) { var propertyDecorators = decorators[prop]; if (!Array.isArray(propertyDecorators)) { propertyDecorators = [propertyDecorators]; } process.env.NODE_ENV !== "production" && invariant(propertyDecorators.every(function (decorator) { return typeof decorator === "function"; }), "Decorate: expected a decorator function or array of decorator functions for '" + prop + "'"); var descriptor = Object.getOwnPropertyDescriptor(target, prop); var newDescriptor = propertyDecorators.reduce(function (accDescriptor, decorator) { return decorator(target, prop, accDescriptor); }, descriptor); if (newDescriptor) Object.defineProperty(target, prop, newDescriptor); }; for (var prop in decorators) { _loop_1(prop); } return thing; } function extendObservable(target, properties, decorators, options) { if (process.env.NODE_ENV !== "production") { invariant(arguments.length >= 2 && arguments.length <= 4, "'extendObservable' expected 2-4 arguments"); invariant(typeof target === "object", "'extendObservable' expects an object as first argument"); invariant(!isObservableMap(target), "'extendObservable' should not be used on maps, use map.merge instead"); } options = asCreateObservableOptions(options); var defaultDecorator = getDefaultDecoratorFromObjectOptions(options); initializeInstance(target); // Fixes #1740 asObservableObject(target, options.name, defaultDecorator.enhancer); // make sure object is observable, even without initial props if (properties) extendObservableObjectWithProperties(target, properties, decorators, defaultDecorator); return target; } function getDefaultDecoratorFromObjectOptions(options) { return options.defaultDecorator || (options.deep === false ? refDecorator : deepDecorator); } function extendObservableObjectWithProperties(target, properties, decorators, defaultDecorator) { var e_1, _a, e_2, _b; if (process.env.NODE_ENV !== "production") { invariant(!isObservable(properties), "Extending an object with another observable (object) is not supported. Please construct an explicit propertymap, using `toJS` if need. See issue #540"); if (decorators) { var keys = getPlainObjectKeys(decorators); try { for (var keys_1 = __values(keys), keys_1_1 = keys_1.next(); !keys_1_1.done; keys_1_1 = keys_1.next()) { var key = keys_1_1.value; if (!(key in properties)) fail("Trying to declare a decorator for unspecified property '" + stringifyKey(key) + "'"); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (keys_1_1 && !keys_1_1.done && (_a = keys_1.return)) _a.call(keys_1); } finally { if (e_1) throw e_1.error; } } } } startBatch(); try { var keys = ownKeys(properties); try { for (var keys_2 = __values(keys), keys_2_1 = keys_2.next(); !keys_2_1.done; keys_2_1 = keys_2.next()) { var key = keys_2_1.value; var descriptor = Object.getOwnPropertyDescriptor(properties, key); if (process.env.NODE_ENV !== "production") { if (!isPlainObject(properties)) fail("'extendObservable' only accepts plain objects as second argument"); if (isComputed(descriptor.value)) fail("Passing a 'computed' as initial property value is no longer supported by extendObservable. Use a getter or decorator instead"); } var decorator = decorators && key in decorators ? decorators[key] : descriptor.get ? computedDecorator : defaultDecorator; if (process.env.NODE_ENV !== "production" && typeof decorator !== "function") fail("Not a valid decorator for '" + stringifyKey(key) + "', got: " + decorator); var resultDescriptor = decorator(target, key, descriptor, true); if (resultDescriptor // otherwise, assume already applied, due to `applyToInstance` ) Object.defineProperty(target, key, resultDescriptor); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (keys_2_1 && !keys_2_1.done && (_b = keys_2.return)) _b.call(keys_2); } finally { if (e_2) throw e_2.error; } } } finally { endBatch(); } } function getDependencyTree(thing, property) { return nodeToDependencyTree(getAtom(thing, property)); } function nodeToDependencyTree(node) { var result = { name: node.name }; if (node.observing && node.observing.length > 0) result.dependencies = unique(node.observing).map(nodeToDependencyTree); return result; } function getObserverTree(thing, property) { return nodeToObserverTree(getAtom(thing, property)); } function nodeToObserverTree(node) { var result = { name: node.name }; if (hasObservers(node)) result.observers = Array.from(getObservers(node)).map(nodeToObserverTree); return result; } var generatorId = 0; function FlowCancellationError() { this.message = "FLOW_CANCELLED"; } FlowCancellationError.prototype = Object.create(Error.prototype); function isFlowCancellationError(error) { return error instanceof FlowCancellationError; } function flow(generator) { if (arguments.length !== 1) fail(!!process.env.NODE_ENV && "Flow expects 1 argument and cannot be used as decorator"); var name = generator.name || "<unnamed flow>"; // Implementation based on https://github.com/tj/co/blob/master/index.js return function () { var ctx = this; var args = arguments; var runId = ++generatorId; var gen = action(name + " - runid: " + runId + " - init", generator).apply(ctx, args); var rejector; var pendingPromise = undefined; var promise = new Promise(function (resolve, reject) { var stepId = 0; rejector = reject; function onFulfilled(res) { pendingPromise = undefined; var ret; try { ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.next).call(gen, res); } catch (e) { return reject(e); } next(ret); } function onRejected(err) { pendingPromise = undefined; var ret; try { ret = action(name + " - runid: " + runId + " - yield " + stepId++, gen.throw).call(gen, err); } catch (e) { return reject(e); } next(ret); } function next(ret) { if (ret && typeof ret.then === "function") { // an async iterator ret.then(next, reject); return; } if (ret.done) return resolve(ret.value); pendingPromise = Promise.resolve(ret.value); return pendingPromise.then(onFulfilled, onRejected); } onFulfilled(undefined); // kick off the process }); promise.cancel = action(name + " - runid: " + runId + " - cancel", function () { try { if (pendingPromise) cancelPromise(pendingPromise); // Finally block can return (or yield) stuff.. var res = gen.return(undefined); // eat anything that promise would do, it's cancelled! var yieldedPromise = Promise.resolve(res.value); yieldedPromise.then(noop, noop); cancelPromise(yieldedPromise); // maybe it can be cancelled :) // reject our original promise rejector(new FlowCancellationError()); } catch (e) { rejector(e); // there could be a throwing finally block } }); return promise; }; } function cancelPromise(promise) { if (typeof promise.cancel === "function") promise.cancel(); } function interceptReads(thing, propOrHandler, handler) { var target; if (isObservableMap(thing) || isObservableArray(thing) || isObservableValue(thing)) { target = getAdministration(thing); } else if (isObservableObject(thing)) { if (typeof propOrHandler !== "string") return fail(process.env.NODE_ENV !== "production" && "InterceptReads can only be used with a specific property, not with an object in general"); target = getAdministration(thing, propOrHandler); } else { return fail(process.env.NODE_ENV !== "production" && "Expected observable map, object or array as first array"); } if (target.dehancer !== undefined) return fail(process.env.NODE_ENV !== "production" && "An intercept reader was already established"); target.dehancer = typeof propOrHandler === "function" ? propOrHandler : handler; return function () { target.dehancer = undefined; }; } function intercept(thing, propOrHandler, handler) { if (typeof handler === "function") return interceptProperty(thing, propOrHandler, handler); else return interceptInterceptable(thing, propOrHandler); } function interceptInterceptable(thing, handler) { return getAdministration(thing).intercept(handler); } function interceptProperty(thing, property, handler) { return getAdministration(thing, property).intercept(handler); } function _isComputed(value, property) { if (value === null || value === undefined) return false; if (property !== undefined) { if (isObservableObject(value) === false) return false; if (!value[$mobx].values.has(property)) return false; var atom = getAtom(value, property); return isComputedValue(atom); } return isComputedValue(value); } function isComputed(value) { if (arguments.length > 1) return fail(process.env.NODE_ENV !== "production" && "isComputed expects only 1 argument. Use isObservableProp to inspect the observability of a property"); return _isComputed(value); } function isComputedProp(value, propName) { if (typeof propName !== "string") return fail(process.env.NODE_ENV !== "production" && "isComputed expected a property name as second argument"); return _isComputed(value, propName); } function _isObservable(value, property) { if (value === null || value === undefined) return false; if (property !== undefined) { if (process.env.NODE_ENV !== "production" && (isObservableMap(value) || isObservableArray(value))) return fail("isObservable(object, propertyName) is not supported for arrays and maps. Use map.has or array.length instead."); if (isObservableObject(value)) { return value[$mobx].values.has(property); } return false; } // For first check, see #701 return (isObservableObject(value) || !!value[$mobx] || isAtom(value) || isReaction(value) || isComputedValue(value)); } function isObservable(value) { if (arguments.length !== 1) fail(process.env.NODE_ENV !== "production" && "isObservable expects only 1 argument. Use isObservableProp to inspect the observability of a property"); return _isObservable(value); } function isObservableProp(value, propName) { if (typeof propName !== "string") return fail(process.env.NODE_ENV !== "production" && "expected a property name as second argument"); return _isObservable(value, propName); } function keys(obj) { if (isObservableObject(obj)) { return obj[$mobx].getKeys(); } if (isObservableMap(obj)) { return Array.from(obj.keys()); } if (isObservableSet(obj)) { return Array.from(obj.keys()); } if (isObservableArray(obj)) { return obj.map(function (_, index) { return index; }); } return fail(process.env.NODE_ENV !== "production" && "'keys()' can only be used on observable objects, arrays, sets and maps"); } function values(obj) { if (isObservableObject(obj)) { return keys(obj).map(function (key) { return obj[key]; }); } if (isObservableMap(obj)) { return keys(obj).map(function (key) { return obj.get(key); }); } if (isObservableSet(obj)) { return Array.from(obj.values()); } if (isObservableArray(obj)) { return obj.slice(); } return fail(process.env.NODE_ENV !== "production" && "'values()' can only be used on observable objects, arrays, sets and maps"); } function entries(obj) { if (isObservableObject(obj)) { return keys(obj).map(function (key) { return [key, obj[key]]; }); } if (isObservableMap(obj)) { return keys(obj).map(function (key) { return [key, obj.get(key)]; }); } if (isObservableSet(obj)) { return Array.from(obj.entries()); } if (isObservableArray(obj)) { return obj.map(function (key, index) { return [index, key]; }); } return fail(process.env.NODE_ENV !== "production" && "'entries()' can only be used on observable objects, arrays and maps"); } function set(obj, key, value) { if (arguments.length === 2 && !isObservableSet(obj)) { startBatch(); var values_1 = key; try { for (var key_1 in values_1) set(obj, key_1, values_1[key_1]); } finally { endBatch(); } return; } if (isObservableObject(obj)) { var adm = obj[$mobx]; var existingObservable = adm.values.get(key); if (existingObservable) { adm.write(key, value); } else { adm.addObservableProp(key, value, adm.defaultEnhancer); } } else if (isObservableMap(obj)) { obj.set(key, value); } else if (isObservableSet(obj)) { obj.add(key); } else if (isObservableArray(obj)) { if (typeof key !== "number") key = parseInt(key, 10); invariant(key >= 0, "Not a valid index: '" + key + "'"); startBatch(); if (key >= obj.length) obj.length = key + 1; obj[key] = value; endBatch(); } else { return fail(process.env.NODE_ENV !== "production" && "'set()' can only be used on observable objects, arrays and maps"); } } function remove(obj, key) { if (isObservableObject(obj)) { obj[$mobx].remove(key); } else if (isObservableMap(obj)) { obj.delete(key); } else if (isObservableSet(obj)) { obj.delete(key); } else if (isObservableArray(obj)) { if (typeof key !== "number") key = parseInt(key, 10); invariant(key >= 0, "Not a valid index: '" + key + "'"); obj.splice(key, 1); } else { return fail(process.env.NODE_ENV !== "production" && "'remove()' can only be used on observable objects, arrays and maps"); } } function has(obj, key) { if (isObservableObject(obj)) { // return keys(obj).indexOf(key) >= 0 var adm = getAdministration(obj); return adm.has(key); } else if (isObservableMap(obj)) { return obj.has(key); } else if (isObservableSet(obj)) { return obj.has(key); } else if (isObservableArray(obj)) { return key >= 0 && key < obj.length; } else { return fail(process.env.NODE_ENV !== "production" && "'has()' can only be used on observable objects, arrays and maps"); } } function get(obj, key) { if (!has(obj, key)) return undefined; if (isObservableObject(obj)) { return obj[key]; } else if (isObservableMap(obj)) { return obj.get(key); } else if (isObservableArray(obj)) { return obj[key]; } else { return fail(process.env.NODE_ENV !== "production" && "'get()' can only be used on observable objects, arrays and maps"); } } function observe(thing, propOrCb, cbOrFire, fireImmediately) { if (typeof cbOrFire === "function") return observeObservableProperty(thing, propOrCb, cbOrFire, fireImmediately); else return observeObservable(thing, propOrCb, cbOrFire); } function observeObservable(thing, listener, fireImmediately) { return getAdministration(thing).observe(listener, fireImmediately); } function observeObservableProperty(thing, property, listener, fireImmediately) { return getAdministration(thing, property).observe(listener, fireImmediately); } var defaultOptions = { detectCycles: true, exportMapsAsObjects: true, recurseEverything: false }; function cache(map, key, value, options) { if (options.detectCycles) map.set(key, value); return value; } function toJSHelper(source, options, __alreadySeen) { if (!options.recurseEverything && !isObservable(source)) return source; if (typeof source !== "object") return source; // Directly return null if source is null if (source === null) return null; // Directly return the Date object itself if contained in the observable if (source instanceof Date) return source; if (isObservableValue(source)) return toJSHelper(source.get(), options, __alreadySeen); // make sure we track the keys of the object if (isObservable(source)) keys(source); var detectCycles = options.detectCycles === true; if (detectCycles && source !== null && __alreadySeen.has(source)) { return __alreadySeen.get(source); } if (isObservableArray(source) || Array.isArray(source)) { var res_1 = cache(__alreadySeen, source, [], options); var toAdd = source.map(function (value) { return toJSHelper(value, options, __alreadySeen); }); res_1.length = toAdd.length; for (var i = 0, l = toAdd.length; i < l; i++) res_1[i] = toAdd[i]; return res_1; } if (isObservableSet(source) || Object.getPrototypeOf(source) === Set.prototype) { if (options.exportMapsAsObjects === false) { var res_2 = cache(__alreadySeen, source, new Set(), options); source.forEach(function (value) { res_2.add(toJSHelper(value, options, __alreadySeen)); }); return res_2; } else { var res_3 = cache(__alreadySeen, source, [], options); source.forEach(function (value) { res_3.push(toJSHelper(value, options, __alreadySeen)); }); return res_3; } } if (isObservableMap(source) || Object.getPrototypeOf(source) === Map.prototype) { if (options.exportMapsAsObjects === false) { var res_4 = cache(__alreadySeen, source, new Map(), options); source.forEach(function (value, key) { res_4.set(key, toJSHelper(value, options, __alreadySeen)); }); return res_4; } else { var res_5 = cache(__alreadySeen, source, {}, options); source.forEach(function (value, key) { res_5[key] = toJSHelper(value, options, __alreadySeen); }); return res_5; } } // Fallback to the situation that source is an ObservableObject or a plain object var res = cache(__alreadySeen, source, {}, options); getPlainObjectKeys(source).forEach(function (key) { res[key] = toJSHelper(source[key], options, __alreadySeen); }); return res; } function toJS(source, options) { // backward compatibility if (typeof options === "boolean") options = { detectCycles: options }; if (!options) options = defaultOptions; options.detectCycles = options.detectCycles === undefined ? options.recurseEverything === true : options.detectCycles === true; var __alreadySeen; if (options.detectCycles) __alreadySeen = new Map(); return toJSHelper(source, options, __alreadySeen); } function trace() { var args = []; for (var _i = 0; _i < arguments.length; _i++) { args[_i] = arguments[_i]; } var enterBreakPoint = false; if (typeof args[args.length - 1] === "boolean") enterBreakPoint = args.pop(); var derivation = getAtomFromArgs(args); if (!derivation) { return fail(process.env.NODE_ENV !== "production" && "'trace(break?)' can only be used inside a tracked computed value or a Reaction. Consider passing in the computed value or reaction explicitly"); } if (derivation.isTracing === TraceMode.NONE) { console.log("[mobx.trace] '" + derivation.name + "' tracing enabled"); } derivation.isTracing = enterBreakPoint ? TraceMode.BREAK : TraceMode.LOG; } function getAtomFromArgs(args) { switch (args.length) { case 0: return globalState.trackingDerivation; case 1: return getAtom(args[0]); case 2: return getAtom(args[0], args[1]); } } /** * During a transaction no views are updated until the end of the transaction. * The transaction will be run synchronously nonetheless. * * @param action a function that updates some reactive state * @returns any value that was returned by the 'action' parameter. */ function transaction(action, thisArg) { if (thisArg === void 0) { thisArg = undefined; } startBatch(); try { return action.apply(thisArg); } finally { endBatch(); } } function when(predicate, arg1, arg2) { if (arguments.length === 1 || (arg1 && typeof arg1 === "object")) return whenPromise(predicate, arg1); return _when(predicate, arg1, arg2 || {}); } function _when(predicate, effect, opts) { var timeoutHandle; if (typeof opts.timeout === "number") { timeoutHandle = setTimeout(function () { if (!disposer[$mobx].isDisposed) { disposer(); var error = new Error("WHEN_TIMEOUT"); if (opts.onError) opts.onError(error); else throw error; } }, opts.timeout); } opts.name = opts.name || "When@" + getNextId(); var effectAction = createAction(opts.name + "-effect", effect); var disposer = autorun(function (r) { if (predicate()) { r.dispose(); if (timeoutHandle) clearTimeout(timeoutHandle); effectAction(); } }, opts); return disposer; } function whenPromise(predicate, opts) { if (process.env.NODE_ENV !== "production" && opts && opts.onError) return fail("the options 'onError' and 'promise' cannot be combined"); var cancel; var res = new Promise(function (resolve, reject) { var disposer = _when(predicate, resolve, __assign(__assign({}, opts), { onError: reject })); cancel = function () { disposer(); reject("WHEN_CANCELLED"); }; }); res.cancel = cancel; return res; } function getAdm(target) { return target[$mobx]; } function isPropertyKey(val) { return typeof val === "string" || typeof val === "number" || typeof val === "symbol"; } // Optimization: we don't need the intermediate objects and could have a completely custom administration for DynamicObjects, // and skip either the internal values map, or the base object with its property descriptors! var objectProxyTraps = { has: function (target, name) { if (name === $mobx || name === "constructor" || name === mobxDidRunLazyInitializersSymbol) return true; var adm = getAdm(target); // MWE: should `in` operator be reactive? If not, below code path will be faster / more memory efficient // TODO: check performance stats! // if (adm.values.get(name as string)) return true if (isPropertyKey(name)) return adm.has(name); return name in target; }, get: function (target, name) { if (name === $mobx || name === "constructor" || name === mobxDidRunLazyInitializersSymbol) return target[name]; var adm = getAdm(target); var observable = adm.values.get(name); if (observable instanceof Atom) { var result = observable.get(); if (result === undefined) { // This fixes #1796, because deleting a prop that has an // undefined value won't retrigger a observer (no visible effect), // the autorun wouldn't subscribe to future key changes (see also next comment) adm.has(name); } return result; } // make sure we start listening to future keys // note that we only do this here for optimization if (isPropertyKey(name)) adm.has(name); return target[name]; }, set: function (target, name, value) { if (!isPropertyKey(name)) return false; set(target, name, value); return true; }, deleteProperty: function (target, name) { if (!isPropertyKey(name)) return false; var adm = getAdm(target); adm.remove(name); return true; }, ownKeys: function (target) { var adm = getAdm(target); adm.keysAtom.reportObserved(); return Reflect.ownKeys(target); }, preventExtensions: function (target) { fail("Dynamic observable objects cannot be frozen"); return false; } }; function createDynamicObservableObject(base) { var proxy = new Proxy(base, objectProxyTraps); base[$mobx].proxy = proxy; return proxy; } function hasInterceptors(interceptable) { return interceptable.interceptors !== undefined && interceptable.interceptors.length > 0; } function registerInterceptor(interceptable, handler) { var interceptors = interceptable.interceptors || (interceptable.interceptors = []); interceptors.push(handler); return once(function () { var idx = interceptors.indexOf(handler); if (idx !== -1) interceptors.splice(idx, 1); }); } function interceptChange(interceptable, change) { var prevU = untrackedStart(); try { // Interceptor can modify the array, copy it to avoid concurrent modification, see #1950 var interceptors = __spread((interceptable.interceptors || [])); for (var i = 0, l = interceptors.length; i < l; i++) { change = interceptors[i](change); invariant(!change || change.type, "Intercept handlers should return nothing or a change object"); if (!change) break; } return change; } finally { untrackedEnd(prevU); } } function hasListeners(listenable) { return listenable.changeListeners !== undefined && listenable.changeListeners.length > 0; } function registerListener(listenable, handler) { var listeners = listenable.changeListeners || (listenable.changeListeners = []); listeners.push(handler); return once(function () { var idx = listeners.indexOf(handler); if (idx !== -1) listeners.splice(idx, 1); }); } function notifyListeners(listenable, change) { var prevU = untrackedStart(); var listeners = listenable.changeListeners; if (!listeners) return; listeners = listeners.slice(); for (var i = 0, l = listeners.length; i < l; i++) { listeners[i](change); } untrackedEnd(prevU); } var MAX_SPLICE_SIZE = 10000; // See e.g. https://github.com/mobxjs/mobx/issues/859 var arrayTraps = { get: function (target, name) { if (name === $mobx) return target[$mobx]; if (name === "length") return target[$mobx].getArrayLength(); if (typeof name === "number") { return arrayExtensions.get.call(target, name); } if (typeof name === "string" && !isNaN(name)) { return arrayExtensions.get.call(target, parseInt(name)); } if (arrayExtensions.hasOwnProperty(name)) { return arrayExtensions[name]; } return target[name]; }, set: function (target, name, value) { if (name === "length") { target[$mobx].setArrayLength(value); } if (typeof name === "number") { arrayExtensions.set.call(target, name, value); } if (typeof name === "symbol" || isNaN(name)) { target[name] = value; } else { // numeric string arrayExtensions.set.call(target, parseInt(name), value); } return true; }, preventExtensions: function (target) { fail("Observable arrays cannot be frozen"); return false; } }; function createObservableArray(initialValues, enhancer, name, owned) { if (name === void 0) { name = "ObservableArray@" + getNextId(); } if (owned === void 0) { owned = false; } var adm = new ObservableArrayAdministration(name, enhancer, owned); addHiddenFinalProp(adm.values, $mobx, adm); var proxy = new Proxy(adm.values, arrayTraps); adm.proxy = proxy; if (initialValues && initialValues.length) { var prev = allowStateChangesStart(true); adm.spliceWithArray(0, 0, initialValues); allowStateChangesEnd(prev); } return proxy; } var ObservableArrayAdministration = /** @class */ (function () { function ObservableArrayAdministration(name, enhancer, owned) { this.owned = owned; this.values = []; this.proxy = undefined; this.lastKnownLength = 0; this.atom = new Atom(name || "ObservableArray@" + getNextId()); this.enhancer = function (newV, oldV) { return enhancer(newV, oldV, name + "[..]"); }; } ObservableArrayAdministration.prototype.dehanceValue = function (value) { if (this.dehancer !== undefined) return this.dehancer(value); return value; }; ObservableArrayAdministration.prototype.dehanceValues = function (values) { if (this.dehancer !== undefined && values.length > 0) return values.map(this.dehancer); return values; }; ObservableArrayAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableArrayAdministration.prototype.observe = function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } if (fireImmediately) { listener({ object: this.proxy, type: "splice", index: 0, added: this.values.slice(), addedCount: this.values.length, removed: [], removedCount: 0 }); } return registerListener(this, listener); }; ObservableArrayAdministration.prototype.getArrayLength = function () { this.atom.reportObserved(); return this.values.length; }; ObservableArrayAdministration.prototype.setArrayLength = function (newLength) { if (typeof newLength !== "number" || newLength < 0) throw new Error("[mobx.array] Out of range: " + newLength); var currentLength = this.values.length; if (newLength === currentLength) return; else if (newLength > currentLength) { var newItems = new Array(newLength - currentLength); for (var i = 0; i < newLength - currentLength; i++) newItems[i] = undefined; // No Array.fill everywhere... this.spliceWithArray(currentLength, 0, newItems); } else this.spliceWithArray(newLength, currentLength - newLength); }; ObservableArrayAdministration.prototype.updateArrayLength = function (oldLength, delta) { if (oldLength !== this.lastKnownLength) throw new Error("[mobx] Modification exception: the internal structure of an observable array was changed."); this.lastKnownLength += delta; }; ObservableArrayAdministration.prototype.spliceWithArray = function (index, deleteCount, newItems) { var _this = this; checkIfStateModificationsAreAllowed(this.atom); var length = this.values.length; if (index === undefined) index = 0; else if (index > length) index = length; else if (index < 0) index = Math.max(0, length + index); if (arguments.length === 1) deleteCount = length - index; else if (deleteCount === undefined || deleteCount === null) deleteCount = 0; else deleteCount = Math.max(0, Math.min(deleteCount, length - index)); if (newItems === undefined) newItems = EMPTY_ARRAY; if (hasInterceptors(this)) { var change = interceptChange(this, { object: this.proxy, type: "splice", index: index, removedCount: deleteCount, added: newItems }); if (!change) return EMPTY_ARRAY; deleteCount = change.removedCount; newItems = change.added; } newItems = newItems.length === 0 ? newItems : newItems.map(function (v) { return _this.enhancer(v, undefined); }); if (process.env.NODE_ENV !== "production") { var lengthDelta = newItems.length - deleteCount; this.updateArrayLength(length, lengthDelta); // checks if internal array wasn't modified } var res = this.spliceItemsIntoValues(index, deleteCount, newItems); if (deleteCount !== 0 || newItems.length !== 0) this.notifyArraySplice(index, newItems, res); return this.dehanceValues(res); }; ObservableArrayAdministration.prototype.spliceItemsIntoValues = function (index, deleteCount, newItems) { var _a; if (newItems.length < MAX_SPLICE_SIZE) { return (_a = this.values).splice.apply(_a, __spread([index, deleteCount], newItems)); } else { var res = this.values.slice(index, index + deleteCount); this.values = this.values .slice(0, index) .concat(newItems, this.values.slice(index + deleteCount)); return res; } }; ObservableArrayAdministration.prototype.notifyArrayChildUpdate = function (index, newValue, oldValue) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.proxy, type: "update", index: index, newValue: newValue, oldValue: oldValue } : null; // The reason why this is on right hand side here (and not above), is this way the uglifier will drop it, but it won't // cause any runtime overhead in development mode without NODE_ENV set, unless spying is enabled if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.atom.name })); this.atom.reportChanged(); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); }; ObservableArrayAdministration.prototype.notifyArraySplice = function (index, added, removed) { var notifySpy = !this.owned && isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { object: this.proxy, type: "splice", index: index, removed: removed, added: added, removedCount: removed.length, addedCount: added.length } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.atom.name })); this.atom.reportChanged(); // conform: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/observe if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); }; return ObservableArrayAdministration; }()); var arrayExtensions = { intercept: function (handler) { return this[$mobx].intercept(handler); }, observe: function (listener, fireImmediately) { if (fireImmediately === void 0) { fireImmediately = false; } var adm = this[$mobx]; return adm.observe(listener, fireImmediately); }, clear: function () { return this.splice(0); }, replace: function (newItems) { var adm = this[$mobx]; return adm.spliceWithArray(0, adm.values.length, newItems); }, /** * Converts this array back to a (shallow) javascript structure. * For a deep clone use mobx.toJS */ toJS: function () { return this.slice(); }, toJSON: function () { // Used by JSON.stringify return this.toJS(); }, /* * functions that do alter the internal structure of the array, (based on lib.es6.d.ts) * since these functions alter the inner structure of the array, the have side effects. * Because the have side effects, they should not be used in computed function, * and for that reason the do not call dependencyState.notifyObserved */ splice: function (index, deleteCount) { var newItems = []; for (var _i = 2; _i < arguments.length; _i++) { newItems[_i - 2] = arguments[_i]; } var adm = this[$mobx]; switch (arguments.length) { case 0: return []; case 1: return adm.spliceWithArray(index); case 2: return adm.spliceWithArray(index, deleteCount); } return adm.spliceWithArray(index, deleteCount, newItems); }, spliceWithArray: function (index, deleteCount, newItems) { var adm = this[$mobx]; return adm.spliceWithArray(index, deleteCount, newItems); }, push: function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var adm = this[$mobx]; adm.spliceWithArray(adm.values.length, 0, items); return adm.values.length; }, pop: function () { return this.splice(Math.max(this[$mobx].values.length - 1, 0), 1)[0]; }, shift: function () { return this.splice(0, 1)[0]; }, unshift: function () { var items = []; for (var _i = 0; _i < arguments.length; _i++) { items[_i] = arguments[_i]; } var adm = this[$mobx]; adm.spliceWithArray(0, 0, items); return adm.values.length; }, reverse: function () { // reverse by default mutates in place before returning the result // which makes it both a 'derivation' and a 'mutation'. // so we deviate from the default and just make it an dervitation if (process.env.NODE_ENV !== "production") { console.warn("[mobx] `observableArray.reverse()` will not update the array in place. Use `observableArray.slice().reverse()` to suppress this warning and perform the operation on a copy, or `observableArray.replace(observableArray.slice().reverse())` to reverse & update in place"); } var clone = this.slice(); return clone.reverse.apply(clone, arguments); }, sort: function (compareFn) { // sort by default mutates in place before returning the result // which goes against all good practices. Let's not change the array in place! if (process.env.NODE_ENV !== "production") { console.warn("[mobx] `observableArray.sort()` will not update the array in place. Use `observableArray.slice().sort()` to suppress this warning and perform the operation on a copy, or `observableArray.replace(observableArray.slice().sort())` to sort & update in place"); } var clone = this.slice(); return clone.sort.apply(clone, arguments); }, remove: function (value) { var adm = this[$mobx]; var idx = adm.dehanceValues(adm.values).indexOf(value); if (idx > -1) { this.splice(idx, 1); return true; } return false; }, get: function (index) { var adm = this[$mobx]; if (adm) { if (index < adm.values.length) { adm.atom.reportObserved(); return adm.dehanceValue(adm.values[index]); } console.warn("[mobx.array] Attempt to read an array index (" + index + ") that is out of bounds (" + adm.values.length + "). Please check length first. Out of bound indices will not be tracked by MobX"); } return undefined; }, set: function (index, newValue) { var adm = this[$mobx]; var values = adm.values; if (index < values.length) { // update at index in range checkIfStateModificationsAreAllowed(adm.atom); var oldValue = values[index]; if (hasInterceptors(adm)) { var change = interceptChange(adm, { type: "update", object: adm.proxy, index: index, newValue: newValue }); if (!change) return; newValue = change.newValue; } newValue = adm.enhancer(newValue, oldValue); var changed = newValue !== oldValue; if (changed) { values[index] = newValue; adm.notifyArrayChildUpdate(index, newValue, oldValue); } } else if (index === values.length) { // add a new item adm.spliceWithArray(index, 0, [newValue]); } else { // out of bounds throw new Error("[mobx.array] Index out of bounds, " + index + " is larger than " + values.length); } } }; [ "concat", "flat", "includes", "indexOf", "join", "lastIndexOf", "slice", "toString", "toLocaleString" ].forEach(function (funcName) { // Feature detection (eg flat may not be available) if (typeof Array.prototype[funcName] !== "function") { return; } arrayExtensions[funcName] = function () { var adm = this[$mobx]; adm.atom.reportObserved(); var res = adm.dehanceValues(adm.values); return res[funcName].apply(res, arguments); }; }); ["every", "filter", "find", "findIndex", "flatMap", "forEach", "map", "some"].forEach(function (funcName) { // Feature detection (eg flatMap may not be available) if (typeof Array.prototype[funcName] !== "function") { return; } arrayExtensions[funcName] = function (callback, thisArg) { var _this = this; var adm = this[$mobx]; adm.atom.reportObserved(); return adm.values[funcName](function (element, index) { element = adm.dehanceValue(element); return callback.call(thisArg, element, index, _this); }, thisArg); }; }); ["reduce", "reduceRight"].forEach(function (funcName) { arrayExtensions[funcName] = function (callback, initialValue) { var _this = this; var adm = this[$mobx]; adm.atom.reportObserved(); return adm.values[funcName](function (accumulator, currentValue, index) { currentValue = adm.dehanceValue(currentValue); return callback(accumulator, currentValue, index, _this); }, initialValue); }; }); var isObservableArrayAdministration = createInstanceofPredicate("ObservableArrayAdministration", ObservableArrayAdministration); function isObservableArray(thing) { return isObject(thing) && isObservableArrayAdministration(thing[$mobx]); } var _a; var ObservableMapMarker = {}; // just extend Map? See also https://gist.github.com/nestharus/13b4d74f2ef4a2f4357dbd3fc23c1e54 // But: https://github.com/mobxjs/mobx/issues/1556 var ObservableMap = /** @class */ (function () { function ObservableMap(initialData, enhancer, name) { if (enhancer === void 0) { enhancer = deepEnhancer; } if (name === void 0) { name = "ObservableMap@" + getNextId(); } this.enhancer = enhancer; this.name = name; this[_a] = ObservableMapMarker; this._keysAtom = createAtom(this.name + ".keys()"); this[Symbol.toStringTag] = "Map"; if (typeof Map !== "function") { throw new Error("mobx.map requires Map polyfill for the current browser. Check babel-polyfill or core-js/es6/map.js"); } this._data = new Map(); this._hasMap = new Map(); this.merge(initialData); } ObservableMap.prototype._has = function (key) { return this._data.has(key); }; ObservableMap.prototype.has = function (key) { var _this = this; if (!globalState.trackingDerivation) return this._has(key); var entry = this._hasMap.get(key); if (!entry) { // todo: replace with atom (breaking change) var newEntry = (entry = new ObservableValue(this._has(key), referenceEnhancer, this.name + "." + stringifyKey(key) + "?", false)); this._hasMap.set(key, newEntry); onBecomeUnobserved(newEntry, function () { return _this._hasMap.delete(key); }); } return entry.get(); }; ObservableMap.prototype.set = function (key, value) { var hasKey = this._has(key); if (hasInterceptors(this)) { var change = interceptChange(this, { type: hasKey ? "update" : "add", object: this, newValue: value, name: key }); if (!change) return this; value = change.newValue; } if (hasKey) { this._updateValue(key, value); } else { this._addValue(key, value); } return this; }; ObservableMap.prototype.delete = function (key) { var _this = this; checkIfStateModificationsAreAllowed(this._keysAtom); if (hasInterceptors(this)) { var change = interceptChange(this, { type: "delete", object: this, name: key }); if (!change) return false; } if (this._has(key)) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "delete", object: this, oldValue: this._data.get(key).value, name: key } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); transaction(function () { _this._keysAtom.reportChanged(); _this._updateHasMapEntry(key, false); var observable = _this._data.get(key); observable.setNewValue(undefined); _this._data.delete(key); }); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); return true; } return false; }; ObservableMap.prototype._updateHasMapEntry = function (key, value) { var entry = this._hasMap.get(key); if (entry) { entry.setNewValue(value); } }; ObservableMap.prototype._updateValue = function (key, newValue) { var observable = this._data.get(key); newValue = observable.prepareNewValue(newValue); if (newValue !== globalState.UNCHANGED) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "update", object: this, oldValue: observable.value, name: key, newValue: newValue } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); observable.setNewValue(newValue); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); } }; ObservableMap.prototype._addValue = function (key, newValue) { var _this = this; checkIfStateModificationsAreAllowed(this._keysAtom); transaction(function () { var observable = new ObservableValue(newValue, _this.enhancer, _this.name + "." + stringifyKey(key), false); _this._data.set(key, observable); newValue = observable.value; // value might have been changed _this._updateHasMapEntry(key, true); _this._keysAtom.reportChanged(); }); var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "add", object: this, name: key, newValue: newValue } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); }; ObservableMap.prototype.get = function (key) { if (this.has(key)) return this.dehanceValue(this._data.get(key).get()); return this.dehanceValue(undefined); }; ObservableMap.prototype.dehanceValue = function (value) { if (this.dehancer !== undefined) { return this.dehancer(value); } return value; }; ObservableMap.prototype.keys = function () { this._keysAtom.reportObserved(); return this._data.keys(); }; ObservableMap.prototype.values = function () { var self = this; var keys = this.keys(); return makeIterable({ next: function () { var _b = keys.next(), done = _b.done, value = _b.value; return { done: done, value: done ? undefined : self.get(value) }; } }); }; ObservableMap.prototype.entries = function () { var self = this; var keys = this.keys(); return makeIterable({ next: function () { var _b = keys.next(), done = _b.done, value = _b.value; return { done: done, value: done ? undefined : [value, self.get(value)] }; } }); }; ObservableMap.prototype[(_a = $mobx, Symbol.iterator)] = function () { return this.entries(); }; ObservableMap.prototype.forEach = function (callback, thisArg) { var e_1, _b; try { for (var _c = __values(this), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = __read(_d.value, 2), key = _e[0], value = _e[1]; callback.call(thisArg, value, key, this); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_1) throw e_1.error; } } }; /** Merge another object into this object, returns this. */ ObservableMap.prototype.merge = function (other) { var _this = this; if (isObservableMap(other)) { other = other.toJS(); } transaction(function () { if (isPlainObject(other)) getPlainObjectKeys(other).forEach(function (key) { return _this.set(key, other[key]); }); else if (Array.isArray(other)) other.forEach(function (_b) { var _c = __read(_b, 2), key = _c[0], value = _c[1]; return _this.set(key, value); }); else if (isES6Map(other)) { if (other.constructor !== Map) fail("Cannot initialize from classes that inherit from Map: " + other.constructor.name); // prettier-ignore other.forEach(function (value, key) { return _this.set(key, value); }); } else if (other !== null && other !== undefined) fail("Cannot initialize map from " + other); }); return this; }; ObservableMap.prototype.clear = function () { var _this = this; transaction(function () { untracked(function () { var e_2, _b; try { for (var _c = __values(_this.keys()), _d = _c.next(); !_d.done; _d = _c.next()) { var key = _d.value; _this.delete(key); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_2) throw e_2.error; } } }); }); }; ObservableMap.prototype.replace = function (values) { var _this = this; // Implementation requirements: // - respect ordering of replacement map // - allow interceptors to run and potentially prevent individual operations // - don't recreate observables that already exist in original map (so we don't destroy existing subscriptions) // - don't _keysAtom.reportChanged if the keys of resulting map are indentical (order matters!) // - note that result map may differ from replacement map due to the interceptors transaction(function () { var e_3, _b, e_4, _c; // Convert to map so we can do quick key lookups var replacementMap = convertToMap(values); var orderedData = new Map(); // Used for optimization var keysReportChangedCalled = false; try { // Delete keys that don't exist in replacement map // if the key deletion is prevented by interceptor // add entry at the beginning of the result map for (var _d = __values(_this._data.keys()), _e = _d.next(); !_e.done; _e = _d.next()) { var key = _e.value; // Concurrently iterating/deleting keys // iterator should handle this correctly if (!replacementMap.has(key)) { var deleted = _this.delete(key); // Was the key removed? if (deleted) { // _keysAtom.reportChanged() was already called keysReportChangedCalled = true; } else { // Delete prevented by interceptor var value = _this._data.get(key); orderedData.set(key, value); } } } } catch (e_3_1) { e_3 = { error: e_3_1 }; } finally { try { if (_e && !_e.done && (_b = _d.return)) _b.call(_d); } finally { if (e_3) throw e_3.error; } } try { // Merge entries for (var _f = __values(replacementMap.entries()), _g = _f.next(); !_g.done; _g = _f.next()) { var _h = __read(_g.value, 2), key = _h[0], value = _h[1]; // We will want to know whether a new key is added var keyExisted = _this._data.has(key); // Add or update value _this.set(key, value); // The addition could have been prevent by interceptor if (_this._data.has(key)) { // The update could have been prevented by interceptor // and also we want to preserve existing values // so use value from _data map (instead of replacement map) var value_1 = _this._data.get(key); orderedData.set(key, value_1); // Was a new key added? if (!keyExisted) { // _keysAtom.reportChanged() was already called keysReportChangedCalled = true; } } } } catch (e_4_1) { e_4 = { error: e_4_1 }; } finally { try { if (_g && !_g.done && (_c = _f.return)) _c.call(_f); } finally { if (e_4) throw e_4.error; } } // Check for possible key order change if (!keysReportChangedCalled) { if (_this._data.size !== orderedData.size) { // If size differs, keys are definitely modified _this._keysAtom.reportChanged(); } else { var iter1 = _this._data.keys(); var iter2 = orderedData.keys(); var next1 = iter1.next(); var next2 = iter2.next(); while (!next1.done) { if (next1.value !== next2.value) { _this._keysAtom.reportChanged(); break; } next1 = iter1.next(); next2 = iter2.next(); } } } // Use correctly ordered map _this._data = orderedData; }); return this; }; Object.defineProperty(ObservableMap.prototype, "size", { get: function () { this._keysAtom.reportObserved(); return this._data.size; }, enumerable: true, configurable: true }); /** * Returns a plain object that represents this map. * Note that all the keys being stringified. * If there are duplicating keys after converting them to strings, behaviour is undetermined. */ ObservableMap.prototype.toPOJO = function () { var e_5, _b; var res = {}; try { for (var _c = __values(this), _d = _c.next(); !_d.done; _d = _c.next()) { var _e = __read(_d.value, 2), key = _e[0], value = _e[1]; // We lie about symbol key types due to https://github.com/Microsoft/TypeScript/issues/1863 res[typeof key === "symbol" ? key : stringifyKey(key)] = value; } } catch (e_5_1) { e_5 = { error: e_5_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_5) throw e_5.error; } } return res; }; /** * Returns a shallow non observable object clone of this map. * Note that the values migth still be observable. For a deep clone use mobx.toJS. */ ObservableMap.prototype.toJS = function () { return new Map(this); }; ObservableMap.prototype.toJSON = function () { // Used by JSON.stringify return this.toPOJO(); }; ObservableMap.prototype.toString = function () { var _this = this; return (this.name + "[{ " + Array.from(this.keys()) .map(function (key) { return stringifyKey(key) + ": " + ("" + _this.get(key)); }) .join(", ") + " }]"); }; /** * Observes this object. Triggers for the events 'add', 'update' and 'delete'. * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe * for callback details */ ObservableMap.prototype.observe = function (listener, fireImmediately) { process.env.NODE_ENV !== "production" && invariant(fireImmediately !== true, "`observe` doesn't support fireImmediately=true in combination with maps."); return registerListener(this, listener); }; ObservableMap.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; return ObservableMap; }()); /* 'var' fixes small-build issue */ var isObservableMap = createInstanceofPredicate("ObservableMap", ObservableMap); var _a$1; var ObservableSetMarker = {}; var ObservableSet = /** @class */ (function () { function ObservableSet(initialData, enhancer, name) { if (enhancer === void 0) { enhancer = deepEnhancer; } if (name === void 0) { name = "ObservableSet@" + getNextId(); } this.name = name; this[_a$1] = ObservableSetMarker; this._data = new Set(); this._atom = createAtom(this.name); this[Symbol.toStringTag] = "Set"; if (typeof Set !== "function") { throw new Error("mobx.set requires Set polyfill for the current browser. Check babel-polyfill or core-js/es6/set.js"); } this.enhancer = function (newV, oldV) { return enhancer(newV, oldV, name); }; if (initialData) { this.replace(initialData); } } ObservableSet.prototype.dehanceValue = function (value) { if (this.dehancer !== undefined) { return this.dehancer(value); } return value; }; ObservableSet.prototype.clear = function () { var _this = this; transaction(function () { untracked(function () { var e_1, _b; try { for (var _c = __values(_this._data.values()), _d = _c.next(); !_d.done; _d = _c.next()) { var value = _d.value; _this.delete(value); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_1) throw e_1.error; } } }); }); }; ObservableSet.prototype.forEach = function (callbackFn, thisArg) { var e_2, _b; try { for (var _c = __values(this), _d = _c.next(); !_d.done; _d = _c.next()) { var value = _d.value; callbackFn.call(thisArg, value, value, this); } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (_d && !_d.done && (_b = _c.return)) _b.call(_c); } finally { if (e_2) throw e_2.error; } } }; Object.defineProperty(ObservableSet.prototype, "size", { get: function () { this._atom.reportObserved(); return this._data.size; }, enumerable: true, configurable: true }); ObservableSet.prototype.add = function (value) { var _this = this; checkIfStateModificationsAreAllowed(this._atom); if (hasInterceptors(this)) { var change = interceptChange(this, { type: "add", object: this, newValue: value }); if (!change) return this; // TODO: ideally, value = change.value would be done here, so that values can be // changed by interceptor. Same applies for other Set and Map api's. } if (!this.has(value)) { transaction(function () { _this._data.add(_this.enhancer(value, undefined)); _this._atom.reportChanged(); }); var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "add", object: this, newValue: value } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(change); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); } return this; }; ObservableSet.prototype.delete = function (value) { var _this = this; if (hasInterceptors(this)) { var change = interceptChange(this, { type: "delete", object: this, oldValue: value }); if (!change) return false; } if (this.has(value)) { var notifySpy = isSpyEnabled(); var notify = hasListeners(this); var change = notify || notifySpy ? { type: "delete", object: this, oldValue: value } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name })); transaction(function () { _this._atom.reportChanged(); _this._data.delete(value); }); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); return true; } return false; }; ObservableSet.prototype.has = function (value) { this._atom.reportObserved(); return this._data.has(this.dehanceValue(value)); }; ObservableSet.prototype.entries = function () { var nextIndex = 0; var keys = Array.from(this.keys()); var values = Array.from(this.values()); return makeIterable({ next: function () { var index = nextIndex; nextIndex += 1; return index < values.length ? { value: [keys[index], values[index]], done: false } : { done: true }; } }); }; ObservableSet.prototype.keys = function () { return this.values(); }; ObservableSet.prototype.values = function () { this._atom.reportObserved(); var self = this; var nextIndex = 0; var observableValues = Array.from(this._data.values()); return makeIterable({ next: function () { return nextIndex < observableValues.length ? { value: self.dehanceValue(observableValues[nextIndex++]), done: false } : { done: true }; } }); }; ObservableSet.prototype.replace = function (other) { var _this = this; if (isObservableSet(other)) { other = other.toJS(); } transaction(function () { if (Array.isArray(other)) { _this.clear(); other.forEach(function (value) { return _this.add(value); }); } else if (isES6Set(other)) { _this.clear(); other.forEach(function (value) { return _this.add(value); }); } else if (other !== null && other !== undefined) { fail("Cannot initialize set from " + other); } }); return this; }; ObservableSet.prototype.observe = function (listener, fireImmediately) { // TODO 'fireImmediately' can be true? process.env.NODE_ENV !== "production" && invariant(fireImmediately !== true, "`observe` doesn't support fireImmediately=true in combination with sets."); return registerListener(this, listener); }; ObservableSet.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableSet.prototype.toJS = function () { return new Set(this); }; ObservableSet.prototype.toString = function () { return this.name + "[ " + Array.from(this).join(", ") + " ]"; }; ObservableSet.prototype[(_a$1 = $mobx, Symbol.iterator)] = function () { return this.values(); }; return ObservableSet; }()); var isObservableSet = createInstanceofPredicate("ObservableSet", ObservableSet); var ObservableObjectAdministration = /** @class */ (function () { function ObservableObjectAdministration(target, values, name, defaultEnhancer) { if (values === void 0) { values = new Map(); } this.target = target; this.values = values; this.name = name; this.defaultEnhancer = defaultEnhancer; this.keysAtom = new Atom(name + ".keys"); } ObservableObjectAdministration.prototype.read = function (key) { return this.values.get(key).get(); }; ObservableObjectAdministration.prototype.write = function (key, newValue) { var instance = this.target; var observable = this.values.get(key); if (observable instanceof ComputedValue) { observable.set(newValue); return; } // intercept if (hasInterceptors(this)) { var change = interceptChange(this, { type: "update", object: this.proxy || instance, name: key, newValue: newValue }); if (!change) return; newValue = change.newValue; } newValue = observable.prepareNewValue(newValue); // notify spy & observers if (newValue !== globalState.UNCHANGED) { var notify = hasListeners(this); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "update", object: this.proxy || instance, oldValue: observable.value, name: key, newValue: newValue } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); observable.setNewValue(newValue); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); } }; ObservableObjectAdministration.prototype.has = function (key) { var map = this.pendingKeys || (this.pendingKeys = new Map()); var entry = map.get(key); if (entry) return entry.get(); else { var exists = !!this.values.get(key); // Possible optimization: Don't have a separate map for non existing keys, // but store them in the values map instead, using a special symbol to denote "not existing" entry = new ObservableValue(exists, referenceEnhancer, this.name + "." + stringifyKey(key) + "?", false); map.set(key, entry); return entry.get(); // read to subscribe } }; ObservableObjectAdministration.prototype.addObservableProp = function (propName, newValue, enhancer) { if (enhancer === void 0) { enhancer = this.defaultEnhancer; } var target = this.target; assertPropertyConfigurable(target, propName); if (hasInterceptors(this)) { var change = interceptChange(this, { object: this.proxy || target, name: propName, type: "add", newValue: newValue }); if (!change) return; newValue = change.newValue; } var observable = new ObservableValue(newValue, enhancer, this.name + "." + stringifyKey(propName), false); this.values.set(propName, observable); newValue = observable.value; // observableValue might have changed it Object.defineProperty(target, propName, generateObservablePropConfig(propName)); this.notifyPropertyAddition(propName, newValue); }; ObservableObjectAdministration.prototype.addComputedProp = function (propertyOwner, // where is the property declared? propName, options) { var target = this.target; options.name = options.name || this.name + "." + stringifyKey(propName); this.values.set(propName, new ComputedValue(options)); if (propertyOwner === target || isPropertyConfigurable(propertyOwner, propName)) Object.defineProperty(propertyOwner, propName, generateComputedPropConfig(propName)); }; ObservableObjectAdministration.prototype.remove = function (key) { if (!this.values.has(key)) return; var target = this.target; if (hasInterceptors(this)) { var change = interceptChange(this, { object: this.proxy || target, name: key, type: "remove" }); if (!change) return; } try { startBatch(); var notify = hasListeners(this); var notifySpy = isSpyEnabled(); var oldObservable = this.values.get(key); var oldValue = oldObservable && oldObservable.get(); oldObservable && oldObservable.set(undefined); // notify key and keyset listeners this.keysAtom.reportChanged(); this.values.delete(key); if (this.pendingKeys) { var entry = this.pendingKeys.get(key); if (entry) entry.set(false); } // delete the prop delete this.target[key]; var change = notify || notifySpy ? { type: "remove", object: this.proxy || target, oldValue: oldValue, name: key } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); } finally { endBatch(); } }; ObservableObjectAdministration.prototype.illegalAccess = function (owner, propName) { /** * This happens if a property is accessed through the prototype chain, but the property was * declared directly as own property on the prototype. * * E.g.: * class A { * } * extendObservable(A.prototype, { x: 1 }) * * classB extens A { * } * console.log(new B().x) * * It is unclear whether the property should be considered 'static' or inherited. * Either use `console.log(A.x)` * or: decorate(A, { x: observable }) * * When using decorate, the property will always be redeclared as own property on the actual instance */ console.warn("Property '" + propName + "' of '" + owner + "' was accessed through the prototype chain. Use 'decorate' instead to declare the prop or access it statically through it's owner"); }; /** * Observes this object. Triggers for the events 'add', 'update' and 'delete'. * See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/observe * for callback details */ ObservableObjectAdministration.prototype.observe = function (callback, fireImmediately) { process.env.NODE_ENV !== "production" && invariant(fireImmediately !== true, "`observe` doesn't support the fire immediately property for observable objects."); return registerListener(this, callback); }; ObservableObjectAdministration.prototype.intercept = function (handler) { return registerInterceptor(this, handler); }; ObservableObjectAdministration.prototype.notifyPropertyAddition = function (key, newValue) { var notify = hasListeners(this); var notifySpy = isSpyEnabled(); var change = notify || notifySpy ? { type: "add", object: this.proxy || this.target, name: key, newValue: newValue } : null; if (notifySpy && process.env.NODE_ENV !== "production") spyReportStart(__assign(__assign({}, change), { name: this.name, key: key })); if (notify) notifyListeners(this, change); if (notifySpy && process.env.NODE_ENV !== "production") spyReportEnd(); if (this.pendingKeys) { var entry = this.pendingKeys.get(key); if (entry) entry.set(true); } this.keysAtom.reportChanged(); }; ObservableObjectAdministration.prototype.getKeys = function () { var e_1, _a; this.keysAtom.reportObserved(); // return Reflect.ownKeys(this.values) as any var res = []; try { for (var _b = __values(this.values), _c = _b.next(); !_c.done; _c = _b.next()) { var _d = __read(_c.value, 2), key = _d[0], value = _d[1]; if (value instanceof ObservableValue) res.push(key); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (_c && !_c.done && (_a = _b.return)) _a.call(_b); } finally { if (e_1) throw e_1.error; } } return res; }; return ObservableObjectAdministration; }()); function asObservableObject(target, name, defaultEnhancer) { if (name === void 0) { name = ""; } if (defaultEnhancer === void 0) { defaultEnhancer = deepEnhancer; } if (Object.prototype.hasOwnProperty.call(target, $mobx)) return target[$mobx]; process.env.NODE_ENV !== "production" && invariant(Object.isExtensible(target), "Cannot make the designated object observable; it is not extensible"); if (!isPlainObject(target)) name = (target.constructor.name || "ObservableObject") + "@" + getNextId(); if (!name) name = "ObservableObject@" + getNextId(); var adm = new ObservableObjectAdministration(target, new Map(), stringifyKey(name), defaultEnhancer); addHiddenProp(target, $mobx, adm); return adm; } var observablePropertyConfigs = Object.create(null); var computedPropertyConfigs = Object.create(null); function generateObservablePropConfig(propName) { return (observablePropertyConfigs[propName] || (observablePropertyConfigs[propName] = { configurable: true, enumerable: true, get: function () { return this[$mobx].read(propName); }, set: function (v) { this[$mobx].write(propName, v); } })); } function getAdministrationForComputedPropOwner(owner) { var adm = owner[$mobx]; if (!adm) { // because computed props are declared on proty, // the current instance might not have been initialized yet initializeInstance(owner); return owner[$mobx]; } return adm; } function generateComputedPropConfig(propName) { return (computedPropertyConfigs[propName] || (computedPropertyConfigs[propName] = { configurable: globalState.computedConfigurable, enumerable: false, get: function () { return getAdministrationForComputedPropOwner(this).read(propName); }, set: function (v) { getAdministrationForComputedPropOwner(this).write(propName, v); } })); } var isObservableObjectAdministration = createInstanceofPredicate("ObservableObjectAdministration", ObservableObjectAdministration); function isObservableObject(thing) { if (isObject(thing)) { // Initializers run lazily when transpiling to babel, so make sure they are run... initializeInstance(thing); return isObservableObjectAdministration(thing[$mobx]); } return false; } function getAtom(thing, property) { if (typeof thing === "object" && thing !== null) { if (isObservableArray(thing)) { if (property !== undefined) fail(process.env.NODE_ENV !== "production" && "It is not possible to get index atoms from arrays"); return thing[$mobx].atom; } if (isObservableSet(thing)) { return thing[$mobx]; } if (isObservableMap(thing)) { var anyThing = thing; if (property === undefined) return anyThing._keysAtom; var observable = anyThing._data.get(property) || anyThing._hasMap.get(property); if (!observable) fail(process.env.NODE_ENV !== "production" && "the entry '" + property + "' does not exist in the observable map '" + getDebugName(thing) + "'"); return observable; } // Initializers run lazily when transpiling to babel, so make sure they are run... initializeInstance(thing); if (property && !thing[$mobx]) thing[property]; // See #1072 if (isObservableObject(thing)) { if (!property) return fail(process.env.NODE_ENV !== "production" && "please specify a property"); var observable = thing[$mobx].values.get(property); if (!observable) fail(process.env.NODE_ENV !== "production" && "no observable property '" + property + "' found on the observable object '" + getDebugName(thing) + "'"); return observable; } if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) { return thing; } } else if (typeof thing === "function") { if (isReaction(thing[$mobx])) { // disposer function return thing[$mobx]; } } return fail(process.env.NODE_ENV !== "production" && "Cannot obtain atom from " + thing); } function getAdministration(thing, property) { if (!thing) fail("Expecting some object"); if (property !== undefined) return getAdministration(getAtom(thing, property)); if (isAtom(thing) || isComputedValue(thing) || isReaction(thing)) return thing; if (isObservableMap(thing) || isObservableSet(thing)) return thing; // Initializers run lazily when transpiling to babel, so make sure they are run... initializeInstance(thing); if (thing[$mobx]) return thing[$mobx]; fail(process.env.NODE_ENV !== "production" && "Cannot obtain administration from " + thing); } function getDebugName(thing, property) { var named; if (property !== undefined) named = getAtom(thing, property); else if (isObservableObject(thing) || isObservableMap(thing) || isObservableSet(thing)) named = getAdministration(thing); else named = getAtom(thing); // valid for arrays as well return named.name; } var toString = Object.prototype.toString; function deepEqual(a, b, depth) { if (depth === void 0) { depth = -1; } return eq(a, b, depth); } // Copied from https://github.com/jashkenas/underscore/blob/5c237a7c682fb68fd5378203f0bf22dce1624854/underscore.js#L1186-L1289 // Internal recursive comparison function for `isEqual`. function eq(a, b, depth, aStack, bStack) { // Identical objects are equal. `0 === -0`, but they aren't identical. // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). if (a === b) return a !== 0 || 1 / a === 1 / b; // `null` or `undefined` only equal to itself (strict comparison). if (a == null || b == null) return false; // `NaN`s are equivalent, but non-reflexive. if (a !== a) return b !== b; // Exhaust primitive checks var type = typeof a; if (type !== "function" && type !== "object" && typeof b != "object") return false; // Compare `[[Class]]` names. var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { // Strings, numbers, regular expressions, dates, and booleans are compared by value. case "[object RegExp]": // RegExps are coerced to strings for comparison (Note: '' + /a/i === '/a/i') case "[object String]": // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is // equivalent to `new String("5")`. return "" + a === "" + b; case "[object Number]": // `NaN`s are equivalent, but non-reflexive. // Object(NaN) is equivalent to NaN. if (+a !== +a) return +b !== +b; // An `egal` comparison is performed for other numeric values. return +a === 0 ? 1 / +a === 1 / b : +a === +b; case "[object Date]": case "[object Boolean]": // Coerce dates and booleans to numeric primitive values. Dates are compared by their // millisecond representations. Note that invalid dates with millisecond representations // of `NaN` are not equivalent. return +a === +b; case "[object Symbol]": return (typeof Symbol !== "undefined" && Symbol.valueOf.call(a) === Symbol.valueOf.call(b)); case "[object Map]": case "[object Set]": // Maps and Sets are unwrapped to arrays of entry-pairs, adding an incidental level. // Hide this extra level by increasing the depth. if (depth >= 0) { depth++; } break; } // Unwrap any wrapped objects. a = unwrap(a); b = unwrap(b); var areArrays = className === "[object Array]"; if (!areArrays) { if (typeof a != "object" || typeof b != "object") return false; // Objects with different constructors are not equivalent, but `Object`s or `Array`s // from different frames are. var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(typeof aCtor === "function" && aCtor instanceof aCtor && typeof bCtor === "function" && bCtor instanceof bCtor) && ("constructor" in a && "constructor" in b)) { return false; } } if (depth === 0) { return false; } else if (depth < 0) { depth = -1; } // Assume equality for cyclic structures. The algorithm for detecting cyclic // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. // Initializing stack of traversed objects. // It's done here since we only need them for objects and arrays comparison. aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { // Linear search. Performance is inversely proportional to the number of // unique nested structures. if (aStack[length] === a) return bStack[length] === b; } // Add the first object to the stack of traversed objects. aStack.push(a); bStack.push(b); // Recursively compare objects and arrays. if (areArrays) { // Compare array lengths to determine if a deep comparison is necessary. length = a.length; if (length !== b.length) return false; // Deep compare the contents, ignoring non-numeric properties. while (length--) { if (!eq(a[length], b[length], depth - 1, aStack, bStack)) return false; } } else { // Deep compare objects. var keys = Object.keys(a); var key = void 0; length = keys.length; // Ensure that both objects contain the same number of properties before comparing deep equality. if (Object.keys(b).length !== length) return false; while (length--) { // Deep compare each member key = keys[length]; if (!(has$1(b, key) && eq(a[key], b[key], depth - 1, aStack, bStack))) return false; } } // Remove the first object from the stack of traversed objects. aStack.pop(); bStack.pop(); return true; } function unwrap(a) { if (isObservableArray(a)) return a.slice(); if (isES6Map(a) || isObservableMap(a)) return Array.from(a.entries()); if (isES6Set(a) || isObservableSet(a)) return Array.from(a.entries()); return a; } function has$1(a, key) { return Object.prototype.hasOwnProperty.call(a, key); } function makeIterable(iterator) { iterator[Symbol.iterator] = getSelf; return iterator; } function getSelf() { return this; } /** * (c) Michel Weststrate 2015 - 2018 * MIT Licensed * * Welcome to the mobx sources! To get an global overview of how MobX internally works, * this is a good place to start: * https://medium.com/@mweststrate/becoming-fully-reactive-an-in-depth-explanation-of-mobservable-55995262a254#.xvbh6qd74 * * Source folders: * =============== * * - api/ Most of the public static methods exposed by the module can be found here. * - core/ Implementation of the MobX algorithm; atoms, derivations, reactions, dependency trees, optimizations. Cool stuff can be found here. * - types/ All the magic that is need to have observable objects, arrays and values is in this folder. Including the modifiers like `asFlat`. * - utils/ Utility stuff. * */ if (typeof Proxy === "undefined" || typeof Symbol === "undefined") { throw new Error("[mobx] MobX 5+ requires Proxy and Symbol objects. If your environment doesn't support Symbol or Proxy objects, please downgrade to MobX 4. For React Native Android, consider upgrading JSCore."); } try { // define process.env if needed // if this is not a production build in the first place // (in which case the expression below would be substituted with 'production') process.env.NODE_ENV; } catch (e) { var g = getGlobal(); if (typeof process === "undefined") g.process = {}; g.process.env = {}; } (function () { function testCodeMinification() { } if (testCodeMinification.name !== "testCodeMinification" && process.env.NODE_ENV !== "production" && typeof process !== 'undefined' && process.env.IGNORE_MOBX_MINIFY_WARNING !== "true") { // trick so it doesn't get replaced var varName = ["process", "env", "NODE_ENV"].join("."); console.warn("[mobx] you are running a minified build, but '" + varName + "' was not set to 'production' in your bundler. This results in an unnecessarily large and slow bundle"); } })(); if (typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__ === "object") { // See: https://github.com/andykog/mobx-devtools/ __MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobx({ spy: spy, extras: { getDebugName: getDebugName }, $mobx: $mobx }); } exports.$mobx = $mobx; exports.FlowCancellationError = FlowCancellationError; exports.ObservableMap = ObservableMap; exports.ObservableSet = ObservableSet; exports.Reaction = Reaction; exports._allowStateChanges = allowStateChanges; exports._allowStateChangesInsideComputed = allowStateChangesInsideComputed; exports._allowStateReadsEnd = allowStateReadsEnd; exports._allowStateReadsStart = allowStateReadsStart; exports._endAction = _endAction; exports._getAdministration = getAdministration; exports._getGlobalState = getGlobalState; exports._interceptReads = interceptReads; exports._isComputingDerivation = isComputingDerivation; exports._resetGlobalState = resetGlobalState; exports._startAction = _startAction; exports.action = action; exports.autorun = autorun; exports.comparer = comparer; exports.computed = computed; exports.configure = configure; exports.createAtom = createAtom; exports.decorate = decorate; exports.entries = entries; exports.extendObservable = extendObservable; exports.flow = flow; exports.get = get; exports.getAtom = getAtom; exports.getDebugName = getDebugName; exports.getDependencyTree = getDependencyTree; exports.getObserverTree = getObserverTree; exports.has = has; exports.intercept = intercept; exports.isAction = isAction; exports.isArrayLike = isArrayLike; exports.isBoxedObservable = isObservableValue; exports.isComputed = isComputed; exports.isComputedProp = isComputedProp; exports.isFlowCancellationError = isFlowCancellationError; exports.isObservable = isObservable; exports.isObservableArray = isObservableArray; exports.isObservableMap = isObservableMap; exports.isObservableObject = isObservableObject; exports.isObservableProp = isObservableProp; exports.isObservableSet = isObservableSet; exports.keys = keys; exports.observable = observable; exports.observe = observe; exports.onBecomeObserved = onBecomeObserved; exports.onBecomeUnobserved = onBecomeUnobserved; exports.onReactionError = onReactionError; exports.reaction = reaction; exports.remove = remove; exports.runInAction = runInAction; exports.set = set; exports.spy = spy; exports.toJS = toJS; exports.trace = trace; exports.transaction = transaction; exports.untracked = untracked; exports.values = values; exports.when = when; Object.defineProperty(exports, '__esModule', { value: true }); })));
cdnjs/cdnjs
ajax/libs/mobx/5.15.5/mobx.umd.js
JavaScript
mit
205,279
import scipy as sp import numpy as np import matplotlib.pyplot as plt import matplotlib import sys import matplotlib.lines as lines import h5py from matplotlib.font_manager import FontProperties import matplotlib.ticker as ticker from scipy.fftpack import fft axial_label_font = FontProperties() axial_label_font.set_family('sans-serif') axial_label_font.set_style('normal') axial_label_font.set_weight('bold') # axial_label_font.set_size('x-large') axial_label_font.set_size(20) legend_label_font = FontProperties() legend_label_font.set_family('sans-serif') legend_label_font.set_style('normal') legend_label_font.set_weight('normal') # legend_label_font.set_size('large') legend_label_font.set_size(16) def node_response_extraction_sequential(node_ID, file_name, num_DOF): h5_file = h5py.File(file_name, 'r'); Time = h5_file['time'][:]; displacement_index = int(h5_file['Model/Nodes/Index_to_Generalized_Displacements'][node_ID]); displacement_component = h5_file['Model/Nodes/Generalized_Displacements'][int(displacement_index):int(displacement_index+num_DOF), :]; acceleration_component = h5_file['Model/Nodes/Generalized_Accelerations'][int(displacement_index):int(displacement_index+num_DOF), :]; for x1 in xrange(0,num_DOF): displacement_component[x1,:] = displacement_component[x1,:]-displacement_component[x1,0]; ### in case self weight loading stage, get relative displacement return Time, displacement_component, acceleration_component; numbercol = 1; surface_node_ID = 252; ## 252, 250, 249, 251 node_ID = [252, 212, 172, 132, 92, 52, 12]; ## node ID from surface to bottom depth = [0, 2, 4, 6, 8, 10, 12]; bottom_node_ID = 6; ## node just beyond DRM layer file_name = 'Motion1C_DRM_propagation.h5.feioutput' ## parameteric_case = 'Motion1C_Northridge' ## ### ========================================================================== postfix = '.feioutput'; middle_name_less_than_ten = '0'; num_DOF = 3; Time, displacement_component_surface, acceleration_component_surface = node_response_extraction_sequential(surface_node_ID, file_name, num_DOF); Time, displacement_component_bottom, acceleration_component_bottom = node_response_extraction_sequential(bottom_node_ID, file_name, num_DOF); # surface_acc = np.loadtxt('Kobe_acc.txt'); # surface_disp = np.loadtxt('Kobe_disp.txt'); surface_acc = np.loadtxt('scaled_northridge_acc.dat'); surface_disp = np.loadtxt('scaled_northridge_dis.dat'); ######################################################################################## #######===== Print acceleration of nodes ===== ###### ######################################################################################## fig = plt.figure() ax = fig.add_subplot(111) ax.plot(surface_acc[:, 0], surface_acc[:, 1], '-r', label='surface analytical', linewidth= 1.5); ax.plot(Time[200:]-2.0, acceleration_component_surface[0, 200:], '-k', label='DRM propagation', linewidth= 0.5); plt.gca().set_xlim([0,38]); # plt.gca().set_ylim([-10,10]); # plt.gca().get_xaxis().set_ticks(np.arange(0, 60.1, 10)) # plt.gca().get_yaxis().set_ticks(np.arange(-15, 3.1, 3)) plt.gca().get_yaxis().set_major_formatter(ticker.FormatStrFormatter('%0.2f')) plt.gca().get_xaxis().set_tick_params(direction='in',labelsize='x-large') plt.gca().get_yaxis().set_tick_params(direction='in',labelsize='x-large') plt.xlabel('Time [s]', fontproperties=axial_label_font); plt.ylabel('Acc. [$m/s^2$]', fontproperties=axial_label_font); plt.grid(True); plt.legend(ncol= numbercol, loc='upper right', prop=legend_label_font); filename = 'acc_check_'+ parameteric_case + '.pdf' plt.savefig(filename, bbox_inches='tight'); plt.show(); # # # ######################################################################################## # # # #######======================== Print Time series response along the depth ===== ###### # # # ######################################################################################## # print "Plot acceleration records along depth!"; # fig = plt.figure() # ax = fig.add_subplot(111) # # scale_meter = 7; # # plt.gca().text(32.7, 1.25, '$1g$', fontsize=20) # # l1 = lines.Line2D([32, 32], [0.5, 0.5+10/scale_meter], color='k', linewidth=2.0) # # l2 = lines.Line2D([31.7, 32.3], [0.5, 0.5], color='k', linewidth=0.5) # # l3 = lines.Line2D([31.7, 32.3], [0.5+10/scale_meter, 0.5+10/scale_meter], color='k', linewidth=0.5) # # plt.gca().add_line(l1); # # plt.gca().add_line(l2); # # plt.gca().add_line(l3); # PGA_depth = sp.zeros(len(depth)); # for x in xrange(0,len(node_ID)): # current_node = node_ID[x]; # current_depth = depth[x]; # Time, current_displacement_component, current_acceleration_component = node_response_extraction_sequential(current_node, file_name, num_DOF); # plot_current_acceleration = current_depth + current_acceleration_component/15.0; ## scale acceleration # PGA_depth[x] = max(abs(current_acceleration_component[0, :])); # ax.plot(Time, plot_current_acceleration[0, :], '-k', linewidth= 1); # plt.gca().set_ylim([-1,13]); # plt.gca().invert_yaxis() # # plt.gca().get_xaxis().set_ticks(np.arange(0, 60.1, 10)) # # plt.gca().get_yaxis().set_ticks(np.arange(-15, 3.1, 3)) # plt.gca().get_yaxis().set_major_formatter(ticker.FormatStrFormatter('%0.2f')) # plt.gca().get_xaxis().set_tick_params(direction='in',labelsize='x-large') # plt.gca().get_yaxis().set_tick_params(direction='in',labelsize='x-large') # plt.xlabel('Time [s]', fontproperties=axial_label_font); # plt.ylabel('Depth. [m]', fontproperties=axial_label_font); # plt.grid(True); # plt.legend(ncol= numbercol, loc='upper right', prop=legend_label_font); # filename = 'acc_depth_'+ parameteric_case + '.pdf' # plt.savefig(filename, bbox_inches='tight'); # plt.show();
BorisJeremic/Real-ESSI-Examples
motion_one_component/Deconvolution_DRM_Propagation_Northridge/python_plot_parameteric_study.py
Python
cc0-1.0
5,870
<?php /** * Cart Page * * @author WooThemes * @package WooCommerce/Templates * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly global $woocommerce; wc_print_notices(); do_action( 'woocommerce_before_cart' ); ?> <form action="<?php echo esc_url( WC()->cart->get_cart_url() ); ?>" method="post"> <?php do_action( 'woocommerce_before_cart_table' ); ?> <table class="shop_table cart" cellspacing="0"> <thead> <tr> <th class="product-remove">&nbsp;</th> <th class="product-thumbnail">&nbsp;</th> <th class="product-name"><?php _e( 'Product', 'woocommerce' ); ?></th> <th class="product-price"><?php _e( 'Price', 'woocommerce' ); ?></th> <th class="product-quantity"><?php _e( 'Quantity', 'woocommerce' ); ?></th> <th class="product-subtotal"><?php _e( 'Total', 'woocommerce' ); ?></th> </tr> </thead> <tbody> <?php do_action( 'woocommerce_before_cart_contents' ); ?> <?php foreach ( WC()->cart->get_cart() as $cart_item_key => $cart_item ) { $_product = apply_filters( 'woocommerce_cart_item_product', $cart_item['data'], $cart_item, $cart_item_key ); $product_id = apply_filters( 'woocommerce_cart_item_product_id', $cart_item['product_id'], $cart_item, $cart_item_key ); if ( $_product && $_product->exists() && $cart_item['quantity'] > 0 && apply_filters( 'woocommerce_cart_item_visible', true, $cart_item, $cart_item_key ) ) { ?> <tr class="<?php echo esc_attr( apply_filters( 'woocommerce_cart_item_class', 'cart_item', $cart_item, $cart_item_key ) ); ?>"> <td class="product-remove"> <?php echo apply_filters( 'woocommerce_cart_item_remove_link', sprintf( '<a href="%s" class="remove" title="%s">&times;</a>', esc_url( WC()->cart->get_remove_url( $cart_item_key ) ), __( 'Remove this item', 'woocommerce' ) ), $cart_item_key ); ?> </td> <td class="product-thumbnail"> <?php $thumbnail = apply_filters( 'woocommerce_cart_item_thumbnail', $_product->get_image(), $cart_item, $cart_item_key ); if ( ! $_product->is_visible() ) echo $thumbnail; else printf( '<a href="%s">%s</a>', $_product->get_permalink(), $thumbnail ); ?> </td> <td class="product-name"> <?php if ( ! $_product->is_visible() ) echo apply_filters( 'woocommerce_cart_item_name', $_product->get_title(), $cart_item, $cart_item_key ); else echo apply_filters( 'woocommerce_cart_item_name', sprintf( '<a href="%s">%s</a>', $_product->get_permalink(), $_product->get_title() ), $cart_item, $cart_item_key ); // Meta data echo WC()->cart->get_item_data( $cart_item ); // Backorder notification if ( $_product->backorders_require_notification() && $_product->is_on_backorder( $cart_item['quantity'] ) ) echo '<p class="backorder_notification">' . __( 'Available on backorder', 'woocommerce' ) . '</p>'; ?> </td> <td class="product-price"> <?php echo apply_filters( 'woocommerce_cart_item_price', WC()->cart->get_product_price( $_product ), $cart_item, $cart_item_key ); ?> </td> <td class="product-quantity"> <?php if ( $_product->is_sold_individually() ) { $product_quantity = sprintf( '1 <input type="hidden" name="cart[%s][qty]" value="1" />', $cart_item_key ); } else { $product_quantity = woocommerce_quantity_input( array( 'input_name' => "cart[{$cart_item_key}][qty]", 'input_value' => $cart_item['quantity'], 'max_value' => $_product->backorders_allowed() ? '' : $_product->get_stock_quantity(), 'min_value' => '0' ), $_product, false ); } echo apply_filters( 'woocommerce_cart_item_quantity', $product_quantity, $cart_item_key ); ?> </td> <td class="product-subtotal"> <?php echo apply_filters( 'woocommerce_cart_item_subtotal', WC()->cart->get_product_subtotal( $_product, $cart_item['quantity'] ), $cart_item, $cart_item_key ); ?> </td> </tr> <?php } } do_action( 'woocommerce_cart_contents' ); ?> <tr> <td colspan="6" class="actions"> <?php if ( WC()->cart->coupons_enabled() ) { ?> <div class="coupon"> <label for="coupon_code"><?php _e( 'Coupon', 'woocommerce' ); ?>:</label> <input type="text" name="coupon_code" class="input-text" id="coupon_code" value="" placeholder="<?php _e( 'Coupon code', 'woocommerce' ); ?>" /> <input type="submit" class="button" name="apply_coupon" value="<?php _e( 'Apply Coupon', 'woocommerce' ); ?>" /> <?php do_action('woocommerce_cart_coupon'); ?> </div> <?php } ?> <input type="submit" class="button" name="update_cart" value="<?php _e( 'Update Cart', 'woocommerce' ); ?>" /> <input type="submit" class="checkout-button button alt wc-forward" name="proceed" value="<?php _e( 'Proceed to Checkout', 'woocommerce' ); ?>" /> <?php do_action( 'woocommerce_proceed_to_checkout' ); ?> <?php wp_nonce_field( 'woocommerce-cart' ); ?> </td> </tr> <?php do_action( 'woocommerce_after_cart_contents' ); ?> </tbody> </table> <?php do_action( 'woocommerce_after_cart_table' ); ?> </form> <div class="cart-collaterals"> <?php do_action( 'woocommerce_cart_collaterals' ); ?> <!-- RDP Commented out to remove 'Calculate Shipping' link GEOSTOREDITS --> <?php //woocommerce_cart_totals(); ?> <?php //woocommerce_shipping_calculator(); ?> </div> <?php do_action( 'woocommerce_after_cart' ); ?>
ArkansasGIS/ArkansasGIS-WP
wp-content/themes/mystile-child/woocommerce/cart/cart.php
PHP
cc0-1.0
5,589
#!/usr/bin/env gjs const Gtk = imports.gi.Gtk; Gtk.init(null); function on_item_activated() { var uri = recentchoosermenu.get_current_uri(); if (uri != null) { print("Recent document selected: " + uri); } } var window = new Gtk.Window(); window.set_default_size(200, -1); window.set_title('RecentChooserMenu'); window.connect('destroy', Gtk.main_quit); var menubar = new Gtk.MenuBar(); window.add(menubar); var menuitem = new Gtk.MenuItem({label: 'Recent'}); menubar.add(menuitem); var recentchoosermenu = new Gtk.RecentChooserMenu(); recentchoosermenu.connect('item-activated', on_item_activated); menuitem.set_submenu(recentchoosermenu); window.show_all(); Gtk.main();
Programmica/gjs-gtk-examples
recentchoosermenu.js
JavaScript
cc0-1.0
705
jsonp({"cep":"16270000","cidade":"Glic\u00e9rio","uf":"SP","estado":"S\u00e3o Paulo"});
lfreneda/cepdb
api/v1/16270000.jsonp.js
JavaScript
cc0-1.0
88
import React from "react"; import {graphql} from "gatsby"; import "../styles/main.scss"; import BlogIndexCover from "../assets/images/blog_covers/blog_index_cover.jpeg"; import CompactHeader from "../components/compact-header"; import BlogListing from "../components/blog-post-listing"; import PageFooter from "../components/footer"; class BlogListPage extends React.Component { render() { const posts = this.props.data.allMarkdownRemark.edges; return ( <div> <CompactHeader title="Blog Articles" mood="#fdfdfd" bgUrl={BlogIndexCover}> </CompactHeader> <main> <div className="post-list-container"> <BlogListing posts={posts}> </BlogListing> </div> </main> <PageFooter> </PageFooter> </div> ); } } export default BlogListPage; export const pageQuery = graphql` query { site { siteMetadata { title } } allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }, limit: 20) { edges { node { excerpt frontmatter { date(formatString: "MMMM DD, YYYY") title basecolor author enablecomments category bgimage external_link external_site_name external_site_link page_slug } } } } } `;
rajmayank/personal-website
src/pages/blog.js
JavaScript
cc0-1.0
1,419